My Hebrew Text in iText is left-aligned - java

I am using the following code to generate Hebrew text in iText.
It works nicely (creates a Hebrew font, and makes the text flow from right-to-left) but the text is left-aligned rather than right-aligned.
Can anyone help me make it right-aligned? Notice that I tried to make the MultiColumnText right-aligned, and the paragraph right-aligned - but to no avail!
Thanks
static Color darkBlue = new Color(0x2F, 0x36, 0x99);
BaseFont unicode = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font fontDarkBlueHebrew = new Font(unicode, 12, Font.NORMAL,darkBlue);
MultiColumnText mct=new MultiColumnText();
mct.addSimpleColumn(36, PageSize.A4.width()-36);
mct.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
mct.setAlignment(Element.ALIGN_RIGHT);
Paragraph section1a = new Paragraph("כותרת 1",fontDarkBlueHebrew );
section1a.setAlignment(Element.ALIGN_RIGHT);
mct.addElement(section1a);
Paragraph section1b = new Paragraph("הטקסט שלע",fontDarkBlueHebrew);
section1b.setAlignment(Element.ALIGN_RIGHT);
mct.addElement(section1b);
document.add(mct);

This is by design. When changing the writing direction, everything is reversed: left becomes right and right becomes left. So you need Element.ALIGN_LEFT instead of Element.ALIGN_RIGHT.

Related

itext pdf change default font size in Paragraph not working

while using itext5 in android to display pdf from XHTML am trying to change the font size but it's not reflecting.
I would like to know the substitutes(or hack) for CSS as itext5 is not supporting CSS.
preparedText = output.toString("UTF-8");
list = XMLWorkerHelper.parseToElementList(preparedText, null);
// URL path =Thread.currentThread().getContextClassLoader().getResource("fontname");
// FontFactory.register(path.toString(), "test_font");
Font titleFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD,7f);
paragraph.setFont(titleFont);
paragraph.addAll(list);
publishProgress(88);
// write to document
document.open();
document.newPage();
Paragraph p= new Paragraph(paragraph);
p.setFont(titleFont);
document.add(p);
document.close();
The font you set in a paragraph applies to all text added to the paragraph afterwards, it does not change the previously added text. To set the font of the text you add to a paragraph in the constructor, there is a constructor that also accepts a font parameter.
Thus, instead of
Paragraph p= new Paragraph(paragraph);
p.setFont(titleFont);
use
Paragraph p = new Paragraph(paragraphText, titleFont);
or
Paragraph p = new Paragraph();
p.setFont(titleFont);
p.add(paragraphText);

Itext Paragraph alignment issue in Android

I am creating PDF outfile file using itext library in android but Paragraph is not centered align while similar code is Java desktop application creates output with center align.
I have also checked by using Element.ALIGN_CENTER and Paragraph.ALIGN_CENTER but no success in android.
Android Code
Here is my code in android for creating centered align Paragraph.
Paragraph prefaceX = new Paragraph();
prefaceX.setAlignment(Element.ALIGN_CENTER);
addEmptyLine(preface, 1);
prefaceX.add(new Paragraph(getString(R.string.report_title), catFont));
prefaceX.add(new Paragraph(getString(R.string.disclaimer), smallBoldMM));
document.add(prefaceX);
where addEmptyLine is as follow
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
Output PDF in android
Java Desktop application code
Paragraph prefaceX = new Paragraph();
prefaceX.setAlignment(Paragraph.ALIGN_CENTER);
prefaceX.add(new Paragraph("Dummy Text", catFont));
prefaceX.add(new Paragraph("* Dummy Details ", smallBoldMM));
document.add(prefaceX);
Output PDF in Java Desktop
Font (catFont and smallBoldMM) are custom font and both are same as follow
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font smallBoldMM = new Font(Font.FontFamily.TIMES_ROMAN, 7,
Font.ITALIC)
Please don't suggest to use tables.
I guess that the difference between your Android application and your Desktop application is the version of iText that is used.
You can get the same behavior by using Paragraph the way one would expect when talking about a paragraph.
Paragraph prefaceX = new Paragraph();
prefaceX.setAlignment(Element.ALIGN_CENTER);
document.add(prefaceX);
document.add(Chunk.NEWLINE);
document.add(new Paragraph(getString(R.string.report_title), catFont));
document.add(new Paragraph(getString(R.string.disclaimer), smallBoldMM));
There is no reason why you'd want to put all the different Paragraph objects into one big Paragraph.
If you take a look at iText 7 (but you're using iText 5 or earlier), you'll notice that we make a distinction between the Paragraphobject (single paragraphs) and the Div object (that can contain several Paragraph and other objects).

Encoding for FontFactor.getFont() [duplicate]

This question already has an answer here:
iText : Unable to print mathematical characters like ∈, ∩, ∑, ∫, ∆ √, ∠
(1 answer)
Closed 6 years ago.
Hiyas
I'm trying to display this string:
λλλλλλλλλλλλλλλλλλλλλλλλ
which is read from a RTF file, parsed and put into this variable. It is NOT used as constant in the code.
Font pdfFont = FontFactory.getFont(font.getFont().getName(), BaseFont.IDENTITY_H, embed, font.getFont().getSize2D(), style);
Phrase phrase = new Phrase("λλλλλλλλλλλλλλλλλλλλλλλλ", pdfFont);
ColumnText.showTextAligned(content[i], alignment, phrase, x, y, rotation);
I also tried CP1252 (and basically all the other encodings I found) together with a simple ArialMT.ttf font, but that damn string is never displayed. I can see that the conversion to the byte array inside iText (we use 5.5.0) always returns a null length byte array which explains why the text is not used, but I don't understand why. What encoding would I need to use to make this visible in a PDF?
Thanks a lot
I suppose that you want to get a result that looks like this:
That's easy. I first tried the SunCharacter example from the official documentation. That example was written in answer to the question: iText : Unable to print mathematical characters like ∈, ∩, ∑, ∫, ∆ √, ∠
I then changed the TEXT to:
public static final String TEXT = "Always use the Unicode notation for special characters: \u03bb";
As you can see, I don't use λ in my source code (that's bad practice). Instead I use \u03bb which is the Unicode notation of λ.
The result looked like this:
That's not what you want; you want ArialMT. So I changed the FONT to:
public static final String FONT = "c:/windows/fonts/arial.ttf";
This gave me the desired PDF.
This is the full code sample:
public class LambdaCharacter {
public static final String DEST = "results/fonts/lambda_character.pdf";
public static final String FONT = "c:/windows/fonts/arial.ttf";
public static final String TEXT = "Always use the Unicode notation for special characters: \u03bb";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new LambdaCharacter().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font f = new Font(bf, 12);
Paragraph p = new Paragraph(TEXT, f);
document.add(p);
document.close();
}
}
I works just fine.
Maybe you aren't really using Arial. Maybe font.getFont().getName() doesn't give you the correct name of the font. Or maybe it gives you the correct name of the font, but you forgot to register the font. In that case, you will see that Helvetica is used. Helvetica can't render a lambda. You need Arial or Cardo-Regular or Arial Unicode or another font, as long as that font knows how to render a lambda.
If you don't know how to register a font, read:
How to load custom font in FontFactory.register in iText or
Creating fonts from *.ttf files using iText or
Using Fonts in System with iTextSharp or
Get list of supported fonts in ITextSharp or
Why is my font not applied when I create a PDF document? or... (there are just too many hits when I search for an answer to that question)

Icepdf special character rendering issue

I use itext library for creating PDF file because has very detailed rendering functions for PDF creation. When user click the button i write a template and fill the blank cells from DB everytime.
Than i use Icepdf library for show to user and taking output of the created pdf file.
But Icepdf has some character encoding problem i think. When PDf created and callled by Icepdf one of Turkish character looks as square. Turkish characters can be seen at this link. All characters rendered succesfully but eighth character at the picture is not.
When i go to filepath of created pdf file (created by itext library) and open it manually with Adobe Acrobat Reader all characters showing correctly. But if programaticly Icepdf open the file and show to user, eighth character at the picture looks as square.
I need change character encoding of Icepdf but i can't yet. Reading many articles about character and Font encoding of Icepdf but i have not yet succeeded. If i solve this character problem my application ready to deploy.
The generated PDF file can be downloaded here.
When I open this file with Adobe Acrobat it looks like this:
When I open the file with IcePDF programaticly it looks like thi:
Also i read some questions and answers about this on Stackoverflow but none of them have an accepted answer/help.
Code used to create the file path:
File fUrl = new File(CreateAndViewPdf
.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath()
);
String path = fUrl
.toString()
.substring(0,fUrl.toString().lastIndexOf(File.separator))
.replace("%20", " ") + "\\hello.pdf";
Code for the createPdf() method:
public void createPdf()throws DocumentException, IOException {
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, "ISO-8859-9", BaseFont.EMBEDDED);
Document document = new Document(PageSize.A5);
PdfWriter.getInstance(document, new FileOutputStream(path));
document.setMargins(10, 10, 10, 10);
document.setMarginMirroring(true);
document.open();
Font font = new Font( bf );
PdfPCell cell;
PdfPTable table = new PdfPTable(2);
font = new Font( bf );
font.setSize(15);
font.setStyle("bold");
cell = new PdfPCell(new Phrase("Sender\n"+"Information", font));
cell.setPaddingBottom(7);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
font = new Font( bf );
font.setSize(12);
font.setStyle("normal");
cell = new PdfPCell(new Phrase("â ç ğ ı İ î ö ş ü û\n\n"+"Â Ç Ğ I İ Î Ö Ş Ü Û",font));
cell.setPaddingBottom(7);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
table.setWidths(new int[]{50,200});
table.setWidthPercentage(100);
table.setSpacingAfter(10);
table.setSpacingBefore(10);
document.add(table);
document.close();
}
Code for the viewPdf() method:
public void viewPdf(String fileP)throws IOException, InterruptedException {
String filePath = fileP;
SwingController controller = new SwingController();
SwingViewBuilder factory = new SwingViewBuilder(controller);
JPanel viewerComponentPanel = factory.buildViewerPanel();
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
CreateAndViewPdf.this.getContentPane().add(viewerComponentPanel);
CreateAndViewPdf.this.setSize(new Dimension(screen.width/2,screen.height));
CreateAndViewPdf.this.setLocationRelativeTo(null);
controller.openDocument(filePath);
}
--- SOLVED ---
Firstly, thanks for the router comment to #Mike 'Pomax' Kamermans
After reading him/her comments begin investigating " how can i embed the spesific font file to PDF with iText " After 1-2 days later, i found solution just like below;
Going to Windows Control Panel\Appearance and Personalization\Fonts and copy the times.ttf (which tested all special characters supported font) file to my Java Application resources container.
Than i add below lines to top of my createPDF method.
Font fontBase = FontFactory.getFont("/resources/times.ttf",
BaseFont.IDENTITY_H,
BaseFont.EMBEDDED,
0.8f, Font.NORMAL,
BaseColor.BLACK);
BaseFont bf = fontBase.getBaseFont();
After this, viewPdf() method get the document to screen with all special characters truely rendering.

PdfPcell empty output of Arabic strings

I have that part of code:
//Staff
// Title font
BaseFont titleBf = null;
try {
titleBf = BaseFont.createFont(BaseFont.TIMES_ROMAN,BaseFont.CP1252, BaseFont.EMBEDDED);
} catch (IOException e) {
System.out.println(e.getMessage());
}
com.itextpdf.text.Font titleFont = new com.itextpdf.text.Font(titleBf,24);
titleFont.setColor(new BaseColor(0, 0, 204));
/*
* Pdf creation
*/
Document document = new Document();
PdfWriter.getInstance(document,new FileOutputStream(fc.getSelectedFile() + ".pdf"));
document.open();
/*
* Title
*/
Paragraph p = new Paragraph("مرحبا بكم",titleFont);
p.setSpacingAfter(20);
p.setAlignment(1); // Center
document.add(p);
//Staff
document.close();
The output was empty.
Even when I tried to add simple pdfpcell, I got same result, here is the way:
com.itextpdf.text.Font fontNormal = FontFactory.getFont(
("arialuni.ttf"), BaseFont.CP1252, BaseFont.EMBEDDED,
8, com.itextpdf.text.Font.NORMAL);
Chunk chunkArabic = new Chunk("مرحبا العالم", fontNormal);
infoTab.addCell(new PdfPCell(new Phrase(chunkArabic)));
document.add(infoTab);
Different problems may be at play.
Encoding: You are putting Arabic text in your source code. If you save your Java file using the wrong encoding, that text will become corrupt. If you compile your Java file using the wrong encoding, that text will become corrupt. And so on. I hope you get the idea. Store literal text like this: "\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628" to avoid problems like this.
As documented in Chapter 11 of my book, right-to-left writing and Arabic ligatures are only supported in the context of PdfPCell and ColumnText. I see that you're using PdfPCell, but I don't see you using cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL); anywhere. That's wrong.
You are using an object fontNormal, but you're not telling us which font you're actually using. For instance: if you're using the standard Type1 font Helvetica, no text will show up, because Helvetica doesn't know how to render Arabic text.
Amendment: You've now updated your question, showing that you're using "arialuni.ttf". However, you are using the wrong encoding: CP1252 is the encoding for the Latin Alphabet. You should use BaseFont.IDENTITY_H.
Update: looking at the update of your question as well as the extra comment, I see two major errors.
You are assuming that the name of the font is "arialuni.ttf". That's the font file, but not the font name. Also: you are asking the FontFactory for this font, but did you tell the FontFactory where to look for fonts? Are you sure the FontFactory can locate c:/windows/fonts/ or whatever directory the file arialuni.ttf is stored.
You are declaring a font, but you're not using it: Paragraph p = new Paragraph("\u062D\u064A\u0633\u0648"); creates a Paragraph using the default font.
This is code that works:
BaseFont bf = BaseFont.createFont(
"c://windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(bf, 8);
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell(new Phrase("\u062D\u064A\u0633\u0648", font));
cell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
table.addCell(cell);
document.add(table);
The result looks like this (zoomed in):

Categories

Resources