How to flatten already filled out PDF form using iTextSharp

I'm using iTextSharp to merge a number of pdf files together into a single file.

I'm using method described in iTextSharp official tutorials, specifically here, which merges files page by page via PdfWriter and PdfImportedPage.

Turns out some of the files I need to merge are filled out PDF Forms and using this method of merging form data is lost.

I've see several examples of using PdfStamper to fill out forms and flatten them.

What I can't find, is a way to flatten already filled out PDF Form and hopefully merge it with the other files without saving it flattened out version first.

Thanks

2

4 Answers

Just setting .FormFlattening on PdfStamper wasn't quite enough...I ended up using a PdfReader with byte array of file contents that i used to stamp/flatten the data to get the byte array of that to put in a new PdfReader. Below is how i did it. works great now.

 private void AppendPdfFile(FileDTO file, PdfContentByte cb, iTextSharp.text.Document printDocument, PdfWriter iwriter) { var reader = new PdfReader(file.FileContents); if (reader.AcroForm != null) reader = new PdfReader(FlattenPdfFormToBytes(reader,file.FileID)); AppendFilePages(reader, printDocument, iwriter, cb); } private byte[] FlattenPdfFormToBytes(PdfReader reader, Guid fileID) { var memStream = new MemoryStream(); var stamper = new PdfStamper(reader, memStream) {FormFlattening = true}; stamper.Close(); return memStream.ToArray(); }
2

When creating the files to be merged, I changed this setting: pdfStamper.FormFlattening = true;

Works Great.

I think this problem is same with this one: AcroForm values missing after flattening

Based on the answer, this should do the trick:

pdfStamper.FormFlattening = true;
pdfStamper.AcroFields.GenerateAppearances = true;
1

This is the same answer as the accepted one but without any unused variables:

private byte[] GetUnEditablePdf(byte[] fileContents)
{ byte[] newFileContents = null; var reader = new PdfReader(fileContents); if (reader.AcroForm != null) newFileContents = FlattenPdfFormToBytes(reader); else newFileContents = fileContents; return newFileContents;
}
private byte[] FlattenPdfFormToBytes(PdfReader reader)
{ var memStream = new MemoryStream(); var stamper = new PdfStamper(reader, memStream) { FormFlattening = true }; stamper.Close(); return memStream.ToArray();
}
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like