iTextSharp Efficient Batch Pdf Generation From a 1 Page Template

梦想的初衷 提交于 2019-12-03 16:25:59

I have done something a little similar before and found that after combining all the pages, running the entire generated document through the PDFStamper again resulted in a noticeable compression of the file size.

Ok, so a friend of mine came up with a solution. The only problem remaining is the amount of memory it takes to create a new PdfStamper. So here's the rewritten procedure.

Anyway. Hope this hepls anyone else. And if you have a better solution please don't be shy.

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);

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!