PDF Merging by ItextSharp

倾然丶 夕夏残阳落幕 提交于 2019-12-02 04:41:24
Jonathan

See my answer here Merging Memory Streams. I give an example of how to merge PDFs with itextsharp.

For updating form field names add this code that uses the stamper to change the form field names.

/// <summary>
/// Merges pdf files from a byte list
/// </summary>
/// <param name="files">list of files to merge</param>
/// <returns>memory stream containing combined pdf</returns>
public MemoryStream MergePdfForms(List<byte[]> files)
{
    if (files.Count > 1)
    {
        string[] names;
        PdfStamper stamper;
        MemoryStream msTemp = null;
        PdfReader pdfTemplate = null;
        PdfReader pdfFile;
        Document doc;
        PdfWriter pCopy;
        MemoryStream msOutput = new MemoryStream();

        pdfFile = new PdfReader(files[0]);

        doc = new Document();
        pCopy = new PdfSmartCopy(doc, msOutput);
        pCopy.PdfVersion = PdfWriter.VERSION_1_7;

        doc.Open();

        for (int k = 0; k < files.Count; k++)
        {
            for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)
            {
                msTemp = new MemoryStream();
                pdfTemplate = new PdfReader(files[k]);

                stamper = new PdfStamper(pdfTemplate, msTemp);

                names = new string[stamper.AcroFields.Fields.Keys.Count];
                stamper.AcroFields.Fields.Keys.CopyTo(names, 0);
                foreach (string name in names)
                {
                    stamper.AcroFields.RenameField(name, name + "_file" + k.ToString());
                }

                stamper.Close();
                pdfFile = new PdfReader(msTemp.ToArray());
                ((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));
                pCopy.FreeReader(pdfFile);
            }
        }

        pdfFile.Close();
        pCopy.Close();
        doc.Close();

        return msOutput;
    }
    else if (files.Count == 1)
    {
        return new MemoryStream(files[0]);
    }

    return null;
}

Here is my simplified version of Jonathan's Merge code with namespaces added, and stamping removed.

public IO.MemoryStream MergePdfForms(System.Collections.Generic.List<byte[]> files)
{
    if (files.Count > 1) {
        using (System.IO.MemoryStream msOutput = new System.IO.MemoryStream()) {
            using (iTextSharp.text.Document doc = new iTextSharp.text.Document()) {
                using (iTextSharp.text.pdf.PdfSmartCopy pCopy = new iTextSharp.text.pdf.PdfSmartCopy(doc, msOutput) { PdfVersion = iTextSharp.text.pdf.PdfWriter.VERSION_1_7 }) {
                    doc.Open();
                    foreach (byte[] oFile in files) {
                        using (iTextSharp.text.pdf.PdfReader pdfFile = new iTextSharp.text.pdf.PdfReader(oFile)) {
                            for (i = 1; i <= pdfFile.NumberOfPages; i++) {
                                pCopy.AddPage(pCopy.GetImportedPage(pdfFile, i));
                                pCopy.FreeReader(pdfFile);
                            }
                        }
                    }
                }
            }

            return msOutput;
        }
    } else if (files.Count == 1) {
        return new System.IO.MemoryStream(files[0]);
    }

    return null;
}
mns

Below is my code for pdf merging.Thanks Jonathan for giving suggestion abt renaming fields,which resolved the issues while merging pdf pages with form fields.

 private static void CombineAndSavePdf(string savePath, List<string> lstPdfFiles)
    {
        using (Stream outputPdfStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {

            Document document = new Document();
            PdfSmartCopy copy = new PdfSmartCopy(document, outputPdfStream);
            document.Open();
            PdfReader reader;
            int totalPageCnt;
            PdfStamper stamper;
            string[] fieldNames;
            foreach (string file in lstPdfFiles)
            {
                reader = new PdfReader(file);
                totalPageCnt = reader.NumberOfPages;
                for (int pageCnt = 0; pageCnt < totalPageCnt; )
                {
                     //have to create a new reader for each page or PdfStamper will throw error
                    reader = new PdfReader(file);
                    stamper = new PdfStamper(reader, outputPdfStream);
                    fieldNames = new string[stamper.AcroFields.Fields.Keys.Count];
                    stamper.AcroFields.Fields.Keys.CopyTo(fieldNames, 0);
                    foreach (string name in fieldNames)
                    {
                        stamper.AcroFields.RenameField(name, name + "_file" + pageCnt.ToString());
                    }
                    copy.AddPage(copy.GetImportedPage(reader, ++pageCnt));                     
                }
                copy.FreeReader(reader);                    
            }
            document.Close();
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!