Michael Hallock
Michael Hallock

Reputation: 1413

iTextSharp merging documents with forms

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();

Upvotes: 1

Views: 1626

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77538

Please read chapter 6 of my book, and you'll notice that using PdfWriter to concatenate (or merge) PDF documents is wrong. Concatenating PDFs is done using PdfCopy.

If the documents that are being merged contain AcroForm forms, the book recommends the use of PdfCopyFields. In more recent versions of iTextSharp, PdfCopyFields is deprecated in favor of the method that is described here: copy pdf form with PdfCopy not working in itextsharp 5.4.5.0

Without an example, nobody will be able to give you a better answer. You'll need to share some of the PDFs that cause the problem.

Upvotes: 1

Related Questions