Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten already filled out PDF form using iTextSharp

Tags:

c#

pdf

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

like image 974
andryuha Avatar asked Dec 21 '09 20:12

andryuha


People also ask

What is flattened PDF?

What is flattening a PDF? When you flatten a PDF, you merge previously separated contents of your document into one. Flattening a PDF makes it so that: Interactive elements in PDF forms such as checkboxes, text boxes, radio buttons, drop-down lists are no longer fillable. Annotations become “native text”.

What does save as flatten do?

Flattening a PDF for print removes transparency information and converts images to a format that the printer can read.


2 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();
  }
like image 118
andryuha Avatar answered Sep 20 '22 09:09

andryuha


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

Works Great.

like image 44
Feliciano Montoya Avatar answered Sep 19 '22 09:09

Feliciano Montoya