0
votes

I'm trying to merge a whole bunch of pdfs together. This is what I have so far

            using (FileStream stream = new FileStream(OutputDirectory+"/"+ OutputFileName+".pdf", FileMode.Create))
            {
                Document pdfDoc = new Document();
                PdfCopy pdf = new PdfCopy(pdfDoc, stream);
                pdfDoc.Open();
                Console.WriteLine("Merging files count: " + Input.Count);
                int i = 1;
                foreach (var item in Input)
                {
                    Console.WriteLine(i + ". Adding: " + item.FileName);
                    pdf.AddDocument(new PdfReader(item.FileWithPath));
                    i++;
                }
                pdfDoc.Close();
                Console.WriteLine("PDF merge complete.");
            }

However, after some pdfs have been merged properly, I get this exception:

iTextSharp.text.exceptions.InvalidPdfException: 'Rebuild failed: trailer not found.; Original message: PDF startxref not found.'

Its pointing at my pdf.AddDocument(new PdfReader line

I have looked around and some comments have mentioned that my file is corrupt. However, I am able to open and read the source pdfs without any issue. I am unsure of how to continue now.

1

1 Answers

0
votes

I have looked around and some comments have mentioned that my file is corrupt.

The information you found most likely is correct, the file you try to read is likely to be corrupt.

However, I am able to open and read the source pdfs without any issue.

PDF viewers often try to repair a certain amount of corruption under the hood. As the person viewing the PDF can usually quickly recognize whether the repair succeeded or only left some pages full of garbage, this is ok-ish, i.e. less a bug and more a feature.

Libraries that automatically process PDFs, on the other hand, should not try this (at least not as much as viewers do) as their outputs might directly go into some archive never to be checked until an audit some years later. A document full of garbage then will cause lots of trouble.

I am unsure of how to continue now.

Try to repair the PDF in question.

If you open it in a current Adobe Acrobat Reader, the program usually upon closing the document will ask whether you want to save the document. This will actually save a repaired version which iText is very likely to accept without further ado.

If that does not work, i.e. if either Adobe Acrobat Reader does not offer to safe a repaired version or iText does not even accept the repaired versions, please share the PDF in question here for further analysis.