How to flatten pdf with Itext in c#?

2019-06-13 17:49发布

问题:

I need to remove all form fields of a pdf, so I am using iText and try to flatten the pdf.

Because of legacy code I am restricted to iText version 4.1.6.1

My Code is:

    public static byte[] RemoveAcroFields(String filename)
    {
        if (filename != null && File.Exists(filename))
        {

            byte[] pdfFile = File.ReadAllBytes(filename);
            PdfReader reader = new PdfReader(pdfFile);
            MemoryStream stream = new MemoryStream(pdfFile);
            PdfStamper stamper = new PdfStamper(reader, stream);

            stamper.FormFlattening = true;
            stamper.Close();

            var flattenedPdfBytes = stream.ToArray();

            reader.Close();
            stream.Close();
            return flattenedPdfBytes;                

        }
        else
        {
            return null;
        }            
    }

This produces this Exception

bei System.IO.MemoryStream.set_Capacity(Int32 value)
 bei System.IO.MemoryStream.set_Capacity(Int32 value)
  bei System.IO.MemoryStream.EnsureCapacity(Int32 value)
  bei System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)

When I uncomment the stamper.close() method no Exception occurs but the resulting pdf has not been flattened

回答1:

Just in case someone has a similiar problem. I could solve it by changing the InputStream for the PdfStamper from MemoryStream to FileStream. With this change it worked for me.

public static void RemoveAcroFields(String filename)
    {
        if (filename != null && File.Exists(filename))
        {                
            byte[] pdfFile = File.ReadAllBytes(filename);
            PdfReader reader = new PdfReader(pdfFile);
            PdfStamper stamper = new PdfStamper(reader, new FileStream(filename, FileMode.Create));

            stamper.FormFlattening = true;
            stamper.Close();                                             

            reader.Close();
        }              
    }


标签: c# itext