如何在使用OpenPDF和Java时在PDF中编写阿拉伯文本。

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月14日 20:05:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定