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();
有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top