0

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.

Aronsson
  • 25
  • 6

2 Answers2

2

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();
        }
    }
Aronsson
  • 25
  • 6
  • Be sure to set the page size to the current page to handle rotated or different size pages without cutting them off. document.SetPageSize(pdfReader.GetPageSize(currentPageNumber)); – mgrowan Mar 26 '19 at 23:44
0

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

Vitaliy Fedorchenko
  • 8,447
  • 3
  • 37
  • 34