How to flatten pdf with Itext in c#?

3.5k views Asked by At

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

There are 1 answers

0
Al Phaba On BEST ANSWER

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