2017-12-27 14 views
2

Ich brauche Hilfe beim Hinzufügen kyrillischer Werte zu einem Feld mit der PDFBox API. Hier ist, was ich bis jetzt habe:PDFBox API: Umgang mit kyrillischen Werten

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 

Es funktioniert perfekt, wenn meine Eingabe im lateinischen Alphabet ist. Aber ich muss auch mit kyrillischen Eingaben umgehen. Wie kann ich es tun?

p.s. dies ist die Ausnahme erhalte ich: Verursacht durch: java.lang.IllegalArgumentException: U + 043D (‚afii10079‘) ist in dieser Schriftart Helvetica Codierung nicht zur Verfügung: WinAnsiEncoding

+0

Das Beispiel CreateSimpleFormWithEmbeddedFont.java zeigt, wie eine bestimmte Schriftart verwendet wird, d. H. Der Code kann teilweise verwendet werden. Brauchen Sie das für ein PDF oder nur für ein bestimmtes Feld eines bestimmten PDF? Können Sie das PDF teilen? –

+0

Sicher. Ich werde das PDF auf meinem google.drive veröffentlichen. Hier ist der Link -> https://drive.google.com/open?id=1eI1iRQnrxMA2kEVJPLH9FhQMx2_2kMHj – Cronck

Antwort

1

Der folgende Code eine entsprechende Schriftart in der AcroForm Standard fügt Ressourcenwörterbuch und ersetzt den Namen in den Standarderscheinungen. PDFBox erstellt beim Aufruf von setValue() den Aussehensstrom der Felder mit der neuen Schriftart neu.

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(); 
}