Add an existing PDF from file to an unwritten document using iTextSharp

China☆狼群 提交于 2019-12-04 08:58:29

Here's a simple merge method that copies PDF files into one PDF. I use this method quite often when merging pdfs. I have used this to merge different sized pages as well without issue. Hope it helps.

public MemoryStream MergePdfForms(List<byte[]> files)
{
    if (files.Count > 1)
    {
        PdfReader pdfFile;
        Document doc;
        PdfWriter pCopy;
        MemoryStream msOutput = new MemoryStream();

        pdfFile = new PdfReader(files[0]);

        doc = new Document();
        pCopy = new PdfSmartCopy(doc, msOutput);

        doc.Open();

        for (int k = 0; k < files.Count; k++)
        {
            pdfFile = new PdfReader(files[k]);
            for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)
            {
                ((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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!