Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText embedded ttf font not visible in Adobe Reader

I'm stamping an existing PDF file with extra information using the iText library. The extra information is text that should be rendered in a custom TTF font.

Problem is that the text is not visible in the Adobe Reader only. Other PDF viewers, such as the default eVince reader in Ubuntu and the Google online PDF reader render the stamped text in the custom embedded font just fine.

I tried multiple encodings, such as Cp1251, BaseFont.Identity_H, ...

The code where the magic happens:

PdfReader pdfReader = new PdfReader(new FileInputStream(inputPdf));
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("stamped.pdf"));
PdfContentByte canvas = pdfStamper.getOverContent(1);
String text = "The stamp";
BaseFont bf = BaseFont.createFont("assign.ttf", "Cp1251",BaseFont.EMBEDDED);
canvas.beginText();
canvas.setColorFill(BaseColor.BLUE);
canvas.setFontAndSize(bf, 13);
canvas.moveText(310, 600);
canvas.showText(text);
pdfStamper.close();
like image 435
nkr1pt Avatar asked Nov 21 '12 13:11

nkr1pt


1 Answers

You have a syntax problem. Text state in PDF is marked with BT and ET. These operators are added using the beginText() and endText() methods. You have a BT, but no ET. Adobe Reader is more strict than the other viewers (that's why I prefer Adobe Reader over all other viewers: people should respect the syntax when writing code).

Add the following line before pdfStamper.close();

canvas.endText();

Better yet, read my book and you'll find out you can reduce the complexity of your code by using ColumnText.showTextAligned().

like image 138
Bruno Lowagie Avatar answered Sep 22 '22 09:09

Bruno Lowagie