ITextPdf: Printing Arabic strings from Right To Left (RTL)

蓝咒 提交于 2019-11-30 18:23:39

问题


I use iTextpdf on java in order to generate stamped PDFs, sometimes the generated PDF is in Arabic and I am facing a funny problem. To let the Arabic page being created from Right To Left (RTL) I use tables and cells which have the property PdfPCell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL). When I use this property Arabic does not show at all, if I avoid the call to this property Arabic strings are correctly showed, this means I shouldn't have problems with fonts and I don't really know if this is an issue with iText or I'm just missing something.

Here a small piece of code which shows an Arabic string correctly:

BaseFont bf = BaseFont.createFont(Application.getBASEPATH() + "fonts/arabic.ttf",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font trebuchetSmaller = new Font(bf, 10, 0);

PdfPTable tbl = new PdfPTable(1); 
PdfPCell cell = new PdfPCell();
Paragraph paragraph = new Paragraph();
paragraph.add(new Phrase("ربط صفحة على شبكة الإنترنت"), trebuchetSmaller));
cell.addElement(paragraph);
tbl.addCell(cell);

Here the needed change which makes the Arabic string disappear:

BaseFont bf = BaseFont.createFont(Application.getBASEPATH() + "fonts/arabic.ttf",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font trebuchetSmaller = new Font(bf, 10, 0);

PdfPTable tbl = new PdfPTable(1); 
PdfPCell cell = new PdfPCell();
cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
Paragraph paragraph = new Paragraph();
paragraph.add(new Phrase("ربط صفحة على شبكة الإنترنت"), trebuchetSmaller));
cell.addElement(paragraph);
tbl.addCell(cell);

If I use PdfWriter.RUN_DIRECTION_RTL with an English string it shows correctly in the format it has supposed to be. If I use a string with mixed English and Arabic characters just the English ones are showed.


回答1:


Change your code to include the registered font:

new Phrase("آزمايش", font)

Also you can add the phrase directly:

PdfPCell pdfCell = new PdfPCell(new Phrase("آزمايش", font));  
pdfCell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL); 



回答2:


Thanks a lot. Actually the problem was the font used that when switched in RTL was behaving bad. I found a lot of very interesting unicode arabic fonts at this address: http://cooltext.com/Fonts-Unicode-Arabic for whoever is interested.



来源:https://stackoverflow.com/questions/10122610/itextpdf-printing-arabic-strings-from-right-to-left-rtl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!