How to flatten already filled out PDF form using iTextSharp

亡梦爱人 提交于 2019-11-29 18:05:45

问题


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


回答1:


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

Works Great.




回答2:


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



回答3:


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;



回答4:


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


来源:https://stackoverflow.com/questions/1942357/how-to-flatten-already-filled-out-pdf-form-using-itextsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!