C# iTextSharp 通过字节数组合并多个 pdf

C# iTextSharp Merge multiple pdf via byte array

我对使用 iTextSharp 和一般的 Pdf 文件不熟悉,但我认为我走在正确的轨道上。

我遍历 pdf 文件列表,将它们转换为字节,并将所有生成的字节放入字节数组。从那里我将字节数组传递给 concatAndAddContent() 以将所有 pdf 合并为一个大的 pdf。目前我只是得到列表中的最后一个 pdf(它们似乎被覆盖)

public static byte[] concatAndAddContent(List<byte[]> pdfByteContent)
    {
        byte[] allBytes;

        using (MemoryStream ms = new MemoryStream())
        {
            Document doc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, ms);

            doc.SetPageSize(PageSize.LETTER);
            doc.Open();
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage page;

            PdfReader reader;
            foreach (byte[] p in pdfByteContent)
            {
                reader = new PdfReader(p);
                int pages = reader.NumberOfPages;

                // loop over document pages
                for (int i = 1; i <= pages; i++)
                {
                    doc.SetPageSize(PageSize.LETTER);
                    doc.NewPage();
                    page = writer.GetImportedPage(reader, i);
                    cb.AddTemplate(page, 0, 0);

                }
            }

            doc.Close();
            allBytes = ms.GetBuffer();
            ms.Flush();
            ms.Dispose();
        }

        return allBytes;
    }

以上是导致创建单个 pdf 的工作代码,其余文件将被忽略。任何建议

这几乎只是 Bruno's code here 的 C# 版本。

这几乎是最简单、最安全和推荐的合并 PDF 文件的方法。 PdfSmartCopy 对象能够检测多个文件中的冗余,有时可以减小文件大小。它的其中一个重载接受一个完整的 PdfReader 对象,可以根据需要对其进行实例化。

public static byte[] concatAndAddContent(List<byte[]> pdfByteContent) {

    using (var ms = new MemoryStream()) {
        using (var doc = new Document()) {
            using (var copy = new PdfSmartCopy(doc, ms)) {
                doc.Open();

                //Loop through each byte array
                foreach (var p in pdfByteContent) {

                    //Create a PdfReader bound to that byte array
                    using (var reader = new PdfReader(p)) {

                        //Add the entire document instead of page-by-page
                        copy.AddDocument(reader);
                    }
                }

                doc.Close();
            }
        }

        //Return just before disposing
        return ms.ToArray();
    }
}
List<byte[]> branchWiseList = new List<byte[]>();
 branchWiseList.Add(bytes); // add here byte array.
then call your function concatAndAddContent(branchWiseList);
System.IO.File.WriteAllBytes("path", concatAndAddContent(branchWiseList));

谢谢