Page 1 of 1

Console: Flatten form fields in PDF document.

Posted: Tue Jun 01, 2021 11:27 am
by Alex
Here is C# example that shows how to flatten form fields in PDF document:

Code: Select all

static void Main(string[] args)
{
    FlattenFormFieldsInPdfDocument("PdfButtonFields.pdf", "PdfButtonFields_FlatteningWidget.pdf");
}

public static void FlattenFormFieldsInPdfDocument(string inPdfFilename, string outPdfFilename)
{
    // open PDF document
    using (Vintasoft.Imaging.Pdf.PdfDocument document = new Vintasoft.Imaging.Pdf.PdfDocument(inPdfFilename))
    {
        // for each PDF page
        foreach (Vintasoft.Imaging.Pdf.Tree.PdfPage page in document.Pages)
        {
            // if page has annotations
            if (page.Annotations != null)
            {
                // open PDF graphics on current page
                using (Vintasoft.Imaging.Pdf.Drawing.PdfGraphics graphics = page.GetGraphics())
                {
                    // for each annotation
                    foreach (Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotation annotation in page.Annotations.ToArray())
                    {
                        // if annotation is widget annotation (represent form field)
                        if (annotation.AnnotationType == Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationType.Widget)
                        {
                            // draw annotation on PDF page
                            graphics.DrawAnnotation(annotation);
                            // remove annotation from annotation collection
                            page.Annotations.Remove(annotation);
                        }
                    }
                }
            }
        }
                
        // remove interactive form of PDF document
        document.InteractiveForm = null;
                
        // pack document to output file
        document.Pack(outPdfFilename);
    }
}