如何在使用 iText 创建的 PDF 中显示阿拉伯语

How to display Arabic in PDF created using iText

我需要您的帮助来显示阿拉伯语内容并在我尝试创建的 PDF 示例中从右到左开始书写。这是示例代码:

public static void main(String[] args) throws IOException {
    try {

        BaseFont ArialBase = BaseFont.createFont("C:\Users\dell\Desktop\arialbd.ttf", BaseFont.IDENTITY_H, true);
        Font ArialFont = new Font(ArialBase, 20);


        Document document = new Document(PageSize.LETTER);


        PdfWriter.getInstance(document, new FileOutputStream("C:\Users\dell\Desktop\HelloWorld.pdf"));
        document.setMargins(72f, 72f, 72f, 0f);

        document.open();
        document.add(new Paragraph("الموقع الإلكتروني,",ArialFont));
        document.close();
        System.out.println("PDF Completed");

    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

使用上面的代码,阿拉伯语文本将显示如下:

الÙ...وقع الإلكترÙцني,

无法识别,文字从左到右。那么我该如何解决呢?

编码错误:

在源代码中使用非 ASCII 字符是一种糟糕的编程习惯。例如,您有 "الموقع الإلكتروني"。此 String 应解释为双字节 UNICODE 字符。但是,当您使用不同于 UNICODE 的编码保存源代码文件时,或者当您使用不同的编码编译该代码时,或者当你的 JVM 使用不同的编码,每个双字节字符都有被破坏的风险,导致乱码,例如 "الموقع الإلكتروني"

如何解决这个问题?使用 UNICODE 符号:"\u0627\u0644\u0645\u0648\u0642\u0639 \u0627\u0644\u0625\u0644\u0643\u062a\u0631\u0648\u0646\u064a"

请查阅官方文档,免费电子书The Best iText Questions on Whosebug, where you will discover that this problem has already been described here: Can't get Czech characters while generating a PDF

字体错误:

如果您仔细阅读本书,您会发现您的示例可能无法正常工作,因为您可能使用了错误的字体。这在我对这个问题的回答中有解释:

您假设 arialbd.ttf 可以生成阿拉伯字形。据我所知只有arialuni.ttf支持阿拉伯语。

错误做法:

此外,您忽略了一个事实,即您只能在 ColumnTextPdfPCell 对象的上下文中使用阿拉伯语。这在这里解释:how to create persian content in pdf using eclipse

例如:

BaseFont bf = BaseFont.createFont(
    "c:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(bf, 20);
ColumnText column = new ColumnText(writer.getDirectContent());
column.setSimpleColumn(36, 730, 569, 36);
column.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
column.addElement(new Paragraph(
    "\u0627\u0644\u0645\u0648\u0642\u0639 \u0627\u0644\u0625\u0644\u0643\u062a\u0631\u0648\u0646\u064a", font));
column.go();

请注意,我使用的是 Identity-H 编码,因为涉及到 UNICODE。

使用 PdfTable 将以 pdf 格式打印阿拉伯语文本。以下是代码

Font f = FontFactory.getFont("assets/NotoNaskhArabic-Regular.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    f.setStyle(Font.BOLD);
    f.setColor(new BaseColor(context.getResources().getColor(R.color.colorPrimary)));
   PdfPTable pdfTable=new PdfPTable(1);
   pdfTable.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
   PdfPCell pdfPCell=new PdfPCell();
   pdfPCell.setBorder(Rectangle.NO_BORDER);
   Paragraph paragraph=new Paragraph(string,f);
   paragraph.setAlignment(PdfPCell.ALIGN_LEFT);
   pdfPCell.addElement(paragraph);
   pdfTable.addCell(pdfPCell);
   document.add(pdfTable);

此代码将在您的 pdf 中添加阿拉伯语文本。 pdfPCell.setBorder(Rectangle.NO_BORDER); 将为 PdfTable 提供段落视图