简体   繁体   English

与NReco PdfGenerator合并PDF

[英]Merge pdfs with NReco PdfGenerator

In the features section on NReco's site, in the examples list: there is a line about MergePdf. 在NReco网站的功能部分中,在示例列表中:关于MergePdf的一行。 I have looked in the API-reference and using the intellisense in visualstudio but I can't find anything. 我已经查看了API参考,并在visualstudio中使用了智能感知功能,但找不到任何东西。

I wan't to merge several pdf's before I sent them in a mail. 在通过邮件发送之前,我不会合并几个pdf。 The Pdf's is generated with nreco wkhtmltopdf with different headers and footers which I could not get to work in the same generate so I splitted the generation and now I want to merge the pdf's again. Pdf是使用nreco wkhtmltopdf生成的,具有不同的页眉和页脚,而我无法在同一生成中使用它,因此我拆分了一代,现在我想再次合并pdf。 Or do I have to get yet another library involved. 还是我必须让另一个图书馆参与进来。

Just sharing what I ended up with. 只是分享我最终得到的。 At least for now. 至少现在(是。 It is a modification of the suggested solution with iTextSharp. 它是对iTextSharp建议解决方案的修改。

public static byte[] MergePdfs(IEnumerable<byte[]> pdfs)
    {
        using (var memoryStream = new MemoryStream())
        {
            var document = new Document(PageSize.A4);
            var writer = PdfWriter.GetInstance(document, memoryStream);

            document.Open();
            var writerDirectContent = writer.DirectContent;

            foreach (var pdf in pdfs)
            {
                var pdfReader = new PdfReader(pdf);
                var numberOfPages = pdfReader.NumberOfPages;

                for (var currentPageNumber = 1; currentPageNumber <= numberOfPages; currentPageNumber++)
                {
                    document.SetPageSize(PageSize.A4);
                    document.NewPage();

                    var page = writer.GetImportedPage(pdfReader, currentPageNumber);
                    writerDirectContent.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
            }

            document.Close();

            return memoryStream.ToArray();
        }
    }

There are 2 ways how you can achieve the goal you mentioned: 有两种方法可以实现您提到的目标:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM