问题
I am using PDFBox library to populate PDF forms but I am not able to flatten them. I have already tried the following solutions:
PDAcroForm acroForm = docCatalog.getAcroForm();
PDField field = acroForm.getField( name );
field.setReadonly(true); //Solution 1
field.getDictionary().setInt("Ff",1);//Solution 2
But nothing seems to be working. Please suggest a solution for the same.
回答1:
PDFBOX 2.0.0 has a PDAcroForm.flatten() method
回答2:
As mentioned by Maruan, PDAcroForm.flatten()
method may be used.
Although the fields might need some preprocessing and most importantly the nested field structure had to be traversed and DV and V checked for values.
In our case what worked was:
private static void flattenPDF(String src, String dst) throws IOException {
PDDocument doc = PDDocument.load(new File(src));
PDDocumentCatalog catalog = doc.getDocumentCatalog();
PDAcroForm acroForm = catalog.getAcroForm();
PDResources resources = new PDResources();
acroForm.setDefaultResources(resources);
List<PDField> fields = new ArrayList<>(acroForm.getFields());
processFields(fields, resources);
acroForm.flatten();
doc.save(dst);
doc.close();
}
private static void processFields(List<PDField> fields, PDResources resources) {
fields.stream().forEach(f -> {
f.setReadOnly(true);
COSDictionary cosObject = f.getCOSObject();
String value = cosObject.getString(COSName.DV) == null ?
cosObject.getString(COSName.V) : cosObject.getString(COSName.DV);
System.out.println("Setting " + f.getFullyQualifiedName() + ": " + value);
try {
f.setValue(value);
} catch (IOException e) {
if (e.getMessage().matches("Could not find font: /.*")) {
String fontName = e.getMessage().replaceAll("^[^/]*/", "");
System.out.println("Adding fallback font for: " + fontName);
resources.put(COSName.getPDFName(fontName), PDType1Font.HELVETICA);
try {
f.setValue(value);
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
e.printStackTrace();
}
}
if (f instanceof PDNonTerminalField) {
processFields(((PDNonTerminalField) f).getChildren(), resources);
}
});
}
来源:https://stackoverflow.com/questions/33383389/pdfbox-how-can-a-pdacroform-be-flattened