【问题标题】:iTextSharp Efficient Batch Pdf Generation From a 1 Page TemplateiTextSharp 从 1 页模板高效批量生成 Pdf
【发布时间】:2011-06-11 03:28:38
【问题描述】:

我正在使用 ITextSharp 生成多页 PDF,每个页面都有相同的模板。

问题在于 PDF 的物理尺寸会随着模板的大小而增长。

必须使用ACROFIELDS

如何减小最终文件大小?

这里是pdf处理程序的代码sn-p:

public void ProcessRequest(HttpContext context)
{
    Context = context;
    Response = context.Response;
    Request = context.Request;

    try
    {
        LoadDataInternal();
    }
    catch (System.Threading.ThreadAbortException)
    {
        // no-op
    }
    catch (Exception ex)
    {
        Logger.LogError(ex);
        Response.Write("Error");
        Response.End();
    }

    Response.BufferOutput = true;
    Response.ClearHeaders();
    Response.ContentType = "application/pdf";

    if (true)
    {
        Response.AddHeader("Content-Disposition", "attachment; filename=" +
            (string.IsNullOrEmpty(DownloadFileName) ? context.Session.SessionID + ".pdf" : DownloadFileName));
    }

    PdfCopyFields copy
        = new PdfCopyFields(Response.OutputStream);
    // add a document
    for (int i = 0; i < dataset.Tables["Model"].Rows.Count; i++)
    {
        copy.AddDocument(new PdfReader(renameFieldsIn(TemplatePath, i)));

        // add a document           
    }        
    copy.SetFullCompression();                   
    // Close the PdfCopyFields object        
    copy.Close();       
}

private byte[] renameFieldsIn(String datasheet, int i)

{
    MemoryStream baos = new MemoryStream();
    // Create the stamper
    PdfStamper stamper = new PdfStamper(new PdfReader(GetTemplateBytes()), baos);
    // Get the fields
    AcroFields form = stamper.AcroFields;
    // Loop over the fields
    List<String> keys = new List<String>(form.Fields.Keys);
    foreach (var key in keys) 
    {
        // rename the fields
        form.RenameField(key, String.Format("{0}_{1}", key, i));
    }
    stamper.FormFlattening = true;
    stamper.FreeTextFlattening = true;
    stamper.SetFullCompression();
    SetFieldsInternal(form, i);
    // close the stamper
    stamper.Close();
    return baos.ToArray();
}

protected byte[] GetTemplateBytes()
{
    var data = Context.Cache[PdfTemplateCacheKey] as byte[];
    if (data == null)
    {
        data = File.ReadAllBytes(Context.Server.MapPath(TemplatePath));
        Context.Cache.Insert(PdfTemplateCacheKey, data,
            null, DateTime.Now.Add(PdfTemplateCacheDuration), Cache.NoSlidingExpiration);
    }
    return data;
}

【问题讨论】:

    标签: c# asp.net pdf-generation itextsharp


    【解决方案1】:

    我之前做过一些类似的事情,发现在合并所有页面后,再次通过 PDFStamper 运行整个生成的文档会导致文件大小明显压缩。

    【讨论】:

      【解决方案2】:

      好的,所以我的一个朋友想出了一个解决方案。剩下的唯一问题是创建新 PdfStamper 所需的内存量。所以这是重写的过程。

      无论如何。希望这对其他人有帮助。如果您有更好的解决方案,请不要害羞。

      public void ProcessRequest (HttpContext context) 
      {
          var watch = System.Diagnostics.Stopwatch.StartNew();
          Context = context;
          Response = context.Response;
          Request = context.Request;
      
          Response.BufferOutput = true;
          Response.ClearHeaders();
          Response.ContentType = "application/pdf";
          Response.AddHeader("Content-Disposition", "attachment; filename=itextsharp_multiple.pdf");
      
          var pageBytes = (byte[])null;
          var pagesAll = new List<byte[]>();        
      
          try 
          {
              for (int i = 0; i < GlobalHttpApplication.Model.TestData.Rows.Count; i++) 
              {
                  PdfStamper pst = null;
                  MemoryStream mstr = null;
                  using (mstr = new MemoryStream()) 
                  {
                      try 
                      {
                          PdfReader reader = new PdfReader(GetTemplateBytes());
                          pst = new PdfStamper(reader, mstr);
                          var acroFields = pst.AcroFields;
      
                          SetFieldsInternal(acroFields, 0);
      
                          pst.FormFlattening = true;
                          pst.SetFullCompression();
      
                      } finally 
                      {
                          if (pst != null)
                              pst.Close();
                      }                    
                  }
                  pageBytes = mstr.ToArray();
                  pagesAll.Add(pageBytes);
      
              }
          } finally 
          {
      
          }   
      
          Document doc = new Document(PageSize.A4);        
          var writer = PdfWriter.GetInstance(doc, Response.OutputStream);
          var copy2 = new PdfSmartCopy(doc, Response.OutputStream);
          doc.Open();
          doc.OpenDocument();
      
          foreach (var b in pagesAll) 
          {
              doc.NewPage();
              copy2.AddPage(copy2.GetImportedPage(new PdfReader(b), 1));
          }
          copy2.Close();
          watch.Stop();
          File.AppendAllText(context.Server.MapPath("~/App_Data/log.txt"), watch.Elapsed + Environment.NewLine);
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-24
        • 1970-01-01
        • 2019-04-11
        • 1970-01-01
        • 2012-08-23
        • 1970-01-01
        • 2015-02-13
        相关资源
        最近更新 更多