How to flatten already filled out PDF form using iTextSharp

后端 未结 4 1655
清酒与你
清酒与你 2021-01-01 22:57

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, wh

相关标签:
4条回答
  • 2021-01-01 23:31

    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();
      }
    
    0 讨论(0)
  • 2021-01-01 23:31

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

    Works Great.

    0 讨论(0)
  • 2021-01-01 23:39

    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();
    }
    
    0 讨论(0)
  • 2021-01-01 23:45

    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;
    
    0 讨论(0)
提交回复
热议问题