magran x
magran x

Reputation: 91

How to display Arabic strings from RTL in PDF generated using itext 7 API?

I'm struggling with this problem for hours now but I can't find a way out, the problem is that:

I wrote a program that generate a pdf file using itext version 7 (and a lot of it) along with some statistics, every things is right till here, but when my pdf should contain some arabic strings they just appear from left to right, no matter what I've tried (changing fonts, using universal encodings, making the string inside a cell of table, using canvas, ...) I can't make them appear normally. Here is a piece of code I use for displaying arabic strings:

PdfFont fArabic=PdfFontFactory.createFont(ARABICFONT,PdfEncodings.IDENTITY_H, true);
final String ARABIC = "\u0627\u0644\u0633\u0644\u0627\u0645 \u0639\u0644\u064A\u0643\u0645";
document.add(new Paragraph(ARABIC).setFont(fArabic).setBaseDirection(BaseDirection.RIGHT_TO_LEFT));

Note: I think that itext 5 version perhaps can solve it but as I said I can't undone the code I wrote especially I have with it a third library for statistics and also the project is already late.I just want a solution using itext 7 version.

Upvotes: 1

Views: 3077

Answers (2)

Saddam Alwaheab
Saddam Alwaheab

Reputation: 33

 FileOutputStream outputStream = new FileOutputStream(filePath);

 PdfWriter writer = PdfWriter.getInstance(document, outputStream);     
 BaseFont ArialBase = BaseFont.createFont("assets/cario.ttf", BaseFont.IDENTITY_H, true);
 Font repotoFont = new Font(ArialBase, 20);

 PdfPTable table = new PdfPTable(6);
 float[] columnWidth = new float[]{6, 30, 30, 20, 20, 30};
 table.setWidths(columnWidth);
 table.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);

 table.addCell(new PdfPCell(new Phrase("علي محمد" + i, repotoFont)));

Upvotes: 0

Alexey Subach
Alexey Subach

Reputation: 12302

Step 1: load pdfCalligraph and licensekey jars into your classpath

Step 2: load license key from xml file:

LicenseKey.loadLicenseFile("itextkey-typography.xml");

Step 3: Create your Document as usual:

Document document = new Document(new PdfDocument(new PdfWriter(outFileName)));

PdfFont bf = PdfFontFactory.createFont(ARABIC_FONT, PdfEncodings.IDENTITY_H);
document.setFont(bf);

document.add(new Paragraph(ARABIC_TEXT).setTextAlignment(TextAlignment.RIGHT));

document.close();

Upvotes: 6

Related Questions