无法在 PDF 中保存阿拉伯语单词 - PDFBox Java [英] Unable to save Arabic words in a PDF - PDFBox Java

查看:52
本文介绍了无法在 PDF 中保存阿拉伯语单词 - PDFBox Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将阿拉伯语字词保存在可编辑的 PDF 中.它适用于英语,但是当我使用阿拉伯语单词时,我得到了这个例外:

Trying to save Arabic words in an editable PDF. It works all fine with English ones but when I use Arabic words, I am getting this exception:

java.lang.IllegalArgumentException:U+0627 在此字体中不可用 Helvetica 编码:WinAnsiEncoding

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

这是我生成 PDF 的方式:

Here is how I generated 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"); 
  }
}

推荐答案

我就是这样做的,希望能帮到其他人.只需使用您要在 PDF 中使用的语言支持的字体即可.

That's how I made it work, I hope it would help others. Just use the font that is supported by the language that you want to use in the 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"); 
  }
}

Edited:添加mkl的评论字体名称和字体大小是Tf指令的参数,黑色的灰度值0是g指令的参数.参数和指令名称必须适当分开.

Edited: Adding the comment of mkl The font name and the font size are parameters of the Tf instruction, and the gray value 0 for black is the parameter for the g instruction. Parameters and instruction names must be appropriately separated.

这篇关于无法在 PDF 中保存阿拉伯语单词 - PDFBox Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆