首页 文章

使用PDFBox将cyrillic chars写入PDF表单字段

提问于
浏览
4

我使用pdfbox 2.0.5使用以下代码填写PDF文档的表单字段:

doc = PDDocument.load(inputStream);
        PDDocumentCatalog catalog = doc.getDocumentCatalog();
        PDAcroForm form = catalog.getAcroForm();
        for (PDField field : form.getFieldTree()){
            field.setValue("должен");
        }

我收到此错误: U+0434 ('afii10069') is not available in this font Times-Roman (generic: TimesNewRomanPSMT) encoding: StandardEncoding with differences

PDF文档本身包含显示正常的西里尔文本 . 我尝试过使用不同的字体 . 对于“Arial Unicode MS”,它想下载一个50MB的“Adobe Acrobat Reader DC字体包” . 这是西里尔字符的要求吗?

我必须在文本字段中指定哪种字体来处理西里尔(或亚洲)字符?

谢谢,Ropo

2 回答

  • 4

    Adobe通过重用{/ Ubuntu}字体中的嵌入字体文件来处理它,并从中创建新的字体资源 . 这是一个快速的黑客,可以作为如何实现类似的东西的指南 . 代码特定于我得到的样本 .

    PDDocument doc = PDDocument.load(new File(...));
    PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
    PDResources formResources = acroForm.getDefaultResources();
    PDTrueTypeFont font = (PDTrueTypeFont) formResources.getFont(COSName.getPDFName("Ubuntu"));
    
    // here is the 'magic' to reuse the font as a new font resource
    TrueTypeFont ttFont = font.getTrueTypeFont();
    
    PDFont font2 = PDType0Font.load(doc, ttFont, true);
    ttFont.close();
    
    formResources.put(COSName.getPDFName("F0"), font2);
    
    PDTextField formField = (PDTextField) acroForm.getField("Text2");
    formField.setDefaultAppearance("/F0 0 Tf 0 g");
    formField.setValue("öäüинформацию");
    
    doc.save(...);
    doc.close();
    
  • 2

    解决方案很简单:form.setNeedAppearances(true);

    然后我删除字段的蓝色框:field.setReadOnly(true);

相关问题