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