flatten method
Flattens the form fields.
Without fieldNames, flattens all of them. With the list, only the fields
whose fully qualified name is in it; the rest stay in the form and the
/AcroForm remains in the catalog.
Implementation
PdfFormFlattenResult flatten({Iterable<String>? fieldNames}) {
// The warnings belong to this call; the collections do not: calling
// [flatten] again with another list of names has to reuse the content
// editor already created for each page, otherwise the page would get a
// second pair of streams wrapping the original content.
_warnings.clear();
if (!acroForm.exists) {
_warnings.add('O documento não tem /AcroForm: nada a achatar.');
return PdfFormFlattenResult(
flattened: const <PdfFlattenedField>[],
warnings: List<String>.unmodifiable(_warnings),
remainingFields: 0,
acroFormRemoved: false,
);
}
final selected = fieldNames == null ? null : Set<String>.of(fieldNames);
final targets = _collectWidgets();
final flattened = <PdfFlattenedField>[];
for (final target in targets) {
if (selected != null && !selected.contains(target.name)) continue;
final field = _flattenWidget(target);
if (field != null) flattened.add(field);
}
if (selected != null) {
for (final name in selected) {
if (targets.any((target) => target.name == name)) continue;
_warnings.add('Campo "$name" não existe no formulário.');
}
}
// After flattening there is no appearance to regenerate; leaving
// `/NeedAppearances true` would make the reader try to rebuild fields that
// no longer exist.
acroForm.removeNeedAppearances();
final remaining = acroForm.fields?.values.length ?? 0;
final removed = options.removeAcroFormWhenEmpty &&
remaining == 0 &&
acroForm.removeWhenEmpty();
return PdfFormFlattenResult(
flattened: List<PdfFlattenedField>.unmodifiable(flattened),
warnings: List<String>.unmodifiable(_warnings),
remainingFields: remaining,
acroFormRemoved: removed,
);
}