/** * <summary>Replaces the Acroform fields with their corresponding graphics representation.</summary> * <param name="document">Document to flatten.</param> */ public void Flatten(Document document) { Dictionary <Page, PageStamper> pageStampers = new Dictionary <Page, PageStamper>(); Form form = document.Form; Fields formFields = form.Fields; foreach (Field field in formFields.Values) { foreach (Widget widget in field.Widgets) { Page widgetPage = widget.Page; AnnotationFlagsEnum flags = widget.Flags; // Is the widget to be rendered? if (((flags & AnnotationFlagsEnum.Hidden) == 0 || hiddenRendered) && ((flags & AnnotationFlagsEnum.Print) > 0 || nonPrintableRendered)) { // Stamping the current state appearance of the widget... PdfName widgetCurrentState = (PdfName)widget.BaseDataObject[PdfName.AS]; FormXObject widgetCurrentAppearance = widget.Appearance.Normal[widgetCurrentState]; if (widgetCurrentAppearance != null) { PageStamper widgetStamper; if (!pageStampers.TryGetValue(widgetPage, out widgetStamper)) { pageStampers[widgetPage] = widgetStamper = new PageStamper(widgetPage); } SKRect widgetBox = widget.Box; widgetStamper.Foreground.ShowXObject(widgetCurrentAppearance, widgetBox.Location, widgetBox.Size); } } // Removing the widget from the page annotations... PageAnnotations widgetPageAnnotations = widgetPage.Annotations; widgetPageAnnotations.Remove(widget); if (widgetPageAnnotations.Count == 0) { widgetPage.Annotations = null; widgetPageAnnotations.Delete(); } // Removing the field references relating the widget... PdfDictionary fieldPartDictionary = widget.BaseDataObject; while (fieldPartDictionary != null) { PdfDictionary parentFieldPartDictionary = (PdfDictionary)fieldPartDictionary.Resolve(PdfName.Parent); PdfArray kidsArray; if (parentFieldPartDictionary != null) { kidsArray = (PdfArray)parentFieldPartDictionary.Resolve(PdfName.Kids); } else { kidsArray = formFields.BaseDataObject; } kidsArray.Remove(fieldPartDictionary.Reference); fieldPartDictionary.Delete(); if (kidsArray.Count > 0) { break; } fieldPartDictionary = parentFieldPartDictionary; } } } if (formFields.Count == 0) { // Removing the form root... document.Form = null; form.Delete(); } foreach (PageStamper pageStamper in pageStampers.Values) { pageStamper.Flush(); } }