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

con*_*sed 4 .net c# itext

我是新手使用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;
    }
Run Code Online (Sandbox Code Playgroud)

上面是工作代码,导致创建单个pdf,其余文件被忽略.有什么建议

Chr*_*aas 21

这几乎只是Bruno代码的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();
    }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

13440 次

最近记录:

9 年,4 月 前