2017-12-27 246 views
2

我需要使用PDFBox API将西里尔文值添加到字段方面的帮助。这是我到目前为止:PDFBox API:如何处理西里尔值

PDDocument document = PDDocument.load(file); 
PDDocumentCatalog dc = document.getDocumentCatalog(); 
PDAcroForm acroForm = dc.getAcroForm(); 
PDField naziv = acroForm.getField("naziv"); 
naziv.setValue("Наслов"); // this part right here 
naziv.setValue("Naslov"); // it works like this 

当我的输入是在拉丁字母表中,它的工作原理非常完美。但我还需要处理西里尔文的输入。 我该怎么办?

p.s.这是我得到的异常: 引起:java.lang.IllegalArgumentException:U + 043D('afii10079')不适用于此字体Helvetica编码:WinAnsiEncoding

+0

CreateSimpleFormWithEmbeddedFont.java示例显示如何使用特定字体,即代码可以部分使用。您是否需要这些用于任何PDF或仅用于特定PDF的某个特定领域?你能分享PDF吗? –

+0

当然。我会在我的google.drive上公开PDF。 这里是链接 - > https://drive.google.com/open?id=1eI1iRQnrxMA2kEVJPLH9FhQMx2_2kMHj – Cronck

回答

1

下面的代码在acroform default资源字典,并以默认外观替换名称。当您调用setValue()时,PDFBox将使用新字体重新创建字段的外观流。

public static void main(String[] args) throws IOException 
{ 
    PDDocument doc = PDDocument.load(new File("ZPe.pdf")); 
    PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm(); 
    PDResources dr = acroForm.getDefaultResources(); 

    // Important: the font is Type0 (allows more than 256 glyphs) and NOT SUBSETTED 
    PDFont font = PDType0Font.load(doc, new FileInputStream("c:/windows/fonts/arial.ttf"), false); 

    COSName fontName = dr.add(font); 
    Iterator<PDField> it = acroForm.getFieldIterator(); 
    while (it.hasNext()) 
    { 
     PDField field = it.next(); 
     if (field instanceof PDTextField) 
     { 
      PDTextField textField = (PDTextField) field; 
      String da = textField.getDefaultAppearance(); 

      // replace font name in default appearance string 
      Pattern pattern = Pattern.compile("\\/(\\w+)\\s.*"); 
      Matcher matcher = pattern.matcher(da); 
      if (!matcher.find() || matcher.groupCount() < 2) 
      { 
       // oh-oh 
      } 
      String oldFontName = matcher.group(1); 
      da = da.replaceFirst(oldFontName, fontName.getName()); 

      textField.setDefaultAppearance(da); 
     } 
    } 
    acroForm.getField("name1").setValue("Наслов"); 
    doc.save("result.pdf"); 
    doc.close(); 
}