英文:
How to write Arabic text in a PDF using OpenPDF and Java
问题
I use OpenPDF to generate a PDF from a Spring Boot application. Everything works fine when I use French or English alphabets, but when I write in Arabic nothing is displayed.
I read that I have to use the Unicode form for the Arabic words. For example, the Arabic word الاسم converted to its Unicode form gives the following string:
\u0627\u0644\u0627\u0633\u0645
So I am wondering whether there is any way to convert Arabic words to Unicode in Java, and could I use that approach with OpenPDF? Or is there any alternative way to write Arabic in a PDF using OpenPDF and Java 17/Spring Boot?
英文:
I use OpenPDF to generate a PDF from a Spring Boot application. Everything works fine when I use French or English alphabets, but when I write in Arabic nothing is displayed.
I read that I have to use the Unicode form for the Arabic words. For example, the Arabic word الاسم converted to its Unicode form gives the following string:
\u0627\u0644\u0627\u0633\u0645
So I am wondering whether there is any way to convert Arabic words to Unicode in Java, and could I use that approach with OpenPDF? Or is there any alternative way to write Arabic in a PDF using OpenPDF and Java 17/Spring Boot?
答案1
得分: 1
使用OpenPDF将阿拉伯文本写入PDF的示例解决了我的问题(OpenPDF文档中的_RightToLeft.java_)。
主要思路是创建支持阿拉伯文本的BaseFont
,如第51行所示:
BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\times.ttf", BaseFont.IDENTITY_H, true);
您可以用支持阿拉伯文本的 .ttf 文件替换它,并将其放在 resources 文件夹中,命名为 src/main/resources/yourTtfFile.ttf。
此外,您还需要指定从右到左(RTL)的方向性,如第61行所示:
ct.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
英文:
This example of writing Arabic text to a PDF using OpenPDF solves my problem. (RightToLeft.java in the OpenPDF documentation.)
The main idea is to create a BaseFont
that supports Arabic text, as shown on line 51:
BaseFont bf = BaseFont.createFont("c:\\windows\\fonts\\times.ttf", BaseFont.IDENTITY_H, true);
You can replace that .ttf file supporting Arabic text with your own file. You put it in the resources folder, and name it like this: src/main/resources/youTtfFile.ttf.
You also need to specify right to left (RTL) directionality, as shown on line 61:
ct.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论