So I have a fairly basic iTextSharp implementation that creates a PDF. As part of that, any "attached documents" need to be read and merged into the generated document. This works fine except I just ran into a document someone attached that breaks everything. The PDF still get's generated, but the document that comes out only displays the first page, and Adobe Reader spits out errors (18 if it means anything to anyone) whenever it tries to view pages 2 - 7.
On page 8 is ANOTHER document that was merged PRIOR to the problem document, and that show up fine. Then the merged document that is causing the issue is next (25 pages) and IT shows up fine.
But something with merging that document breaks those previous pages. It's really weird because I'd expect it to break the documents that were merged right before it, as well as page 1, etc...
The only thing I can see in the document that is different, is that page 2 of the problem document being merged in has a filled out form on it. I'm trying to get one of the people here that know PDFs better than me to get me one without that form to ensure that's the issue, but it seems like my best candidate right now...
I tried the following (adding the "Remove any forms" part), but I still have issues. Any ideas?
var reader = new PdfReader(filePath);
// Remove any forms
if (reader.AcroForm != null)
{
var memStream = new MemoryStream();
var stamper = new PdfStamper(reader, memStream) { FormFlattening = true };
stamper.Close();
reader = new PdfReader(memStream.ToArray());
}
var numberOfPages = reader.NumberOfPages;
var cb = writer.DirectContent;
var i = 0;
while (i < numberOfPages)
{
i++;
document.SetPageSize(reader.GetPageSizeWithRotation(i));
document.NewPage();
var page = writer.GetImportedPage(reader, i);
var rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
reader.Close();