Aronsson
Aronsson

Reputation: 25

Merge pdfs with NReco PdfGenerator

In the features section on NReco's site, in the examples list: there is a line about MergePdf. I have looked in the API-reference and using the intellisense in visualstudio but I can't find anything.

I wan't to merge several pdf's before I sent them in a mail. 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. Or do I have to get yet another library involved.

Upvotes: 0

Views: 2720

Answers (2)

Aronsson
Aronsson

Reputation: 25

Just sharing what I ended up with. At least for now. It is a modification of the suggested solution with 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();
        }
    }

Upvotes: 2

Vitaliy Fedorchenko
Vitaliy Fedorchenko

Reputation: 9245

There are 2 ways how you can achieve the goal you mentioned:

Upvotes: 0

Related Questions