'Remove hidden elements from a pdf document using iText
I do want to flatten a pdf document.
PdfAcroForm FlattenFields does flatten the document, but it does not remove hidden elements. e.g. elements which are only visible when when another element is hovered over. In this cased, the hidden elements are part of the flattened document.
Based on a stackoverflow issue (PdfFormField simply does not hide when setting the visibility to HIDDEN), this seems to be the current behavior of FlattenFields.
using (var pdfReader = new PdfReader(preparedPdfStream))
{
using (PdfDocument docToSign = new PdfDocument(pdfReader, pdfWriter))
{
PdfAcroForm form = PdfAcroForm.GetAcroForm(docToSign, true);
// Flatten all fields
form.FlattenFields();
docToSign.Close();
}
}
I now have implemented a solution which checks for the flags and which removes elements when they have a flag HIDDEN or NoView.
using (PdfDocument docToSign = new PdfDocument(pdfReader, pdfWriter))
{
PdfAcroForm form = PdfAcroForm.GetAcroForm(docToSign, true);
IDictionary<string, PdfFormField> formFields = form.GetFormFields();
var fieldsToRemove = new List<string>();
foreach (var item in formFields)
{
//Load Flags
PdfNumber num = (PdfNumber)item.Value.GetPdfObject().Get(PdfName.F);
if (num == null)
continue;
//Convert flag to our own enum
PdfAnnotationEnum flags = (PdfAnnotationEnum)num.IntValue();
Console.WriteLine(flags);
if ((flags & PdfAnnotationEnum.HIDDEN) == PdfAnnotationEnum.HIDDEN || (flags & PdfAnnotationEnum.NO_VIEW) == PdfAnnotationEnum.NO_VIEW)
fieldsToRemove.Add(item.Key);
}
foreach (var item in fieldsToRemove)
{
//Remove the hidden fields from the pdf
form.RemoveField(item);
}
// Flatten all fields
form.FlattenFields();
docToSign.Close();
}
This does work for the one document i have with hidden elements.
Question: Can/Does this work in general or is there a better solution for not showing hidden content when flattening a pdf?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
