copy/paste 后 PDFBox 的文本外观不正确

PDFBox incorrect text appearance after copy/paste

我正在使用 PDFBox 2.0.4 通过 acroForms 创建 PDF 文档。这是我的测试代码示例:

PDDocument document = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);

PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);

String dir = "../testPdfBox/src/main/resources/fonts/";
PDType0Font font = PDType0Font.load(document, new File(dir + "Roboto-Regular.ttf"));

PDResources resources = new PDResources();
String fontName = resources.add(font).getName();
acroForm.setDefaultResources(resources);

String defaultAppearanceString = format("/%s 12 Tf 0 g", fontName);
acroForm.setDefaultAppearance(defaultAppearanceString);

PDTextField field = new PDTextField(acroForm);
field.setPartialName("SampleField");
field.setDefaultAppearance(defaultAppearanceString);
acroForm.getFields().add(field);

PDAnnotationWidget widget = field.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 750, 200, 50);
widget.setRectangle(rect);
widget.setPage(page);
widget.setPrinted(true);

page.getAnnotations().add(widget);

field.setValue("Sample field 123456");

acroForm.flatten();

document.save("target/SimpleForm.pdf");
document.close();

一切正常。但是当我尝试从创建的文档中复制文本并将其粘贴到记事本或 Word 时,它变成了正方形。

关于这个问题我搜索了很多。最流行的答案是创建的 PDF 中没有 toUnicode cmap。因此,我使用 CanOpener for Acrobat 浏览我的文档:

是的,没有 toUnicode cmap,但一切正常,如果不使用 acroForm.flatten()。当表单字段未展平时,我可以 copy/paste 文档中的文本,它看起来是正确的。尽管如此,我需要将所有字段都展平。

那么,我有两个问题:

  1. 为什么copy/pasting文本在扁平化时有问题,而在非扁平化时一切正常?

  2. 如何避免文本 copy/pasting 出现问题? 是否只有一种解决方案——我自己创建 toUnicode CMap,比如

我的测试 pdf 文件可用 here

请替换

PDType0Font font = PDType0Font.load(document, new File(dir + "Roboto-Regular.ttf"));

PDType0Font font = PDType0Font.load(document, new FileInputStream(dir + "Roboto-Regular.ttf"), false);

这可以确保字体是完整嵌入的,而不仅仅是作为子集嵌入的。