无法将阿拉伯语单词保存为 PDF - PDFBox Java

Unable to save Arabic words in a PDF - PDFBox Java

正在尝试在可编辑的 PDF 中保存 阿拉伯语 字词。它适用于 英语 那些,但是当我使用阿拉伯语单词时,我得到这个异常:

java.lang.IllegalArgumentException: U+0627 is not available in this font Helvetica encoding: WinAnsiEncoding

这是我生成 PDF 的方式:

public static void main(String[] args) throws IOException
{
  String formTemplate = "myFormPdf.pdf";
  try (PDDocument pdfDocument = PDDocument.load(new File(formTemplate)))
  {
    PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
    if (acroForm != null)
    {
        PDTextField field = (PDTextField) acroForm.getField( "sampleField" );
        field.setValue("جملة");
    }
    pdfDocument.save("updatedPdf.pdf"); 
  }
}

您需要一种支持这些阿拉伯符号的字体。
获得兼容字体后,您可以使用 PDType0Font

加载它
final PDFont font = PDType0Font.load(...);

Type 0 字体是一种引用多种其他字体格式的字体,并且有可能加载所有可用符号。

另请参阅 Cookbook - working with fonts(没有 Type 0 的示例,但仍然有用)。

我就是这样实现的,希望对大家有帮助。只需使用您要在 PDF 中使用的语言所支持的字体即可。

public static void main(String[] args) throws IOException
{
  String formTemplate = "myFormPdf.pdf";

  try (PDDocument pdfDocument = PDDocument.load(new File(formTemplate)))
  {
    PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
    // you can read ttf from resources as well, this is just for testing 
    PDFont font = PDType0Font.load(pdfDocument,new File("/path/to/font.ttf"));
    String fontName = acroForm.getDefaultResources().add(pdfont).getName();
    if (acroForm != null)
    {
        PDTextField field = (PDTextField) acroForm.getField( "sampleField" );
        field.setDefaultAppearance("/"+fontName +" 0 Tf 0 g");
        field.setValue("جملة");
    }

    pdfDocument.save("updatedPdf.pdf"); 
  }
}

已编辑: 添加 mkl 的注释 字体名称和字体大小是Tf指令的参数,黑色的灰度值0是g指令的参数。参数和指令名称必须适当分开。