Search code examples
c#itext7

itext7 CopyPagesTo not opening PDF


I am trying to add a Cover Page PDF file to another PDF file. I am using CopyPagesTo method. CoverPageFilePath will go before any pages in the pdfDocumentFile. I then need to rewrite that new file to the same location. When I run the code and open the new pdf file I get an error about it being damaged.

 public static void iText7MergePDF()
        {
            byte[] modifiedPdfInBytes = null;
            string pdfCoverPageFilePath = @"PathtoCoverPage\Cover Page.pdf";
            PdfDocument pdfDocumentCover = new PdfDocument(new iText.Kernel.Pdf.PdfReader(pdfCoverPageFilePath));
            string pdfDocumentFile =@"PathtoFullDocument.pdf";
            var buffer = File.ReadAllBytes(pdfDocumentFile);
            using (var originalPdfStream = new MemoryStream(buffer))
            using (var modifiedPdfStream = new MemoryStream())
            {
                var pdfReader = new iText.Kernel.Pdf.PdfReader(originalPdfStream);
                var pdfDocument = new PdfDocument(pdfReader, new PdfWriter(modifiedPdfStream));
                int numberOfPages = pdfDocumentCover.GetNumberOfPages();
                pdfDocumentCover.CopyPagesTo(1, numberOfPages, pdfDocument);
                modifiedPdfInBytes = modifiedPdfStream.ToArray();
                pdfDocument.Close();
            }
            System.IO.File.WriteAllBytes(pdfGL, modifiedPdfInBytes);
        }

Solution

  • Whenever you have some other type, like a StreamWriter, or here a PdfWriter writing to a Stream, it may not write all the data to the Stream immediately.

    Here you Close the pdfDocument for all the data to be written to the MemoryStream.

    ie this

    modifiedPdfInBytes = modifiedPdfStream.ToArray();
    pdfDocument.Close();
    

    Should be

    pdfDocument.Close();
    modifiedPdfInBytes = modifiedPdfStream.ToArray();