I am using PDFBox 2.0.0-SNAPSHOT to create a PDF file in Java. It works great for very simple characters (e.g. [a-zA-Z9-0]), but I get coding errors for more advanced characters like ’( quoteright). Here is my code:
PDDocument pdf = new PDDocument();
PDPage page = new PDPage(PDRectangle.A4);
pdf.addPage(page);
PDPageContentStream contents = new PDPageContentStream(pdf, page);
PDFont font = PDType1Font.HELVETICA;
contents.beginText();
contents.setFont(font, 12);
String text = "’";
contents.showText(text);
contents.endText();
contents.close();
I get this exception:
Unable to encode U + 2019 in Helvetica font. Type 1 fonts only support 8-bit code points
I looked at the supported characters for non-embedded fonts in Section D.1 of the PDF Specification , and this character must be supported.
In fact, if I use this trick , I can insert the correct character:
byte[] commands = "(x) Tj ".getBytes();
commands[1] = (byte)145;
contents.appendRawCommands(commands);
. , , appendRawCommands .
, ? , showText drawString, - .
: , :
Exception in thread "main" java.lang.IllegalArgumentException: Can't encode U+2019 in font Helvetica. Type 1 fonts only support 8-bit code points
at org.apache.pdfbox.pdmodel.font.PDType1Font.encode(PDType1Font.java:343)
at org.apache.pdfbox.pdmodel.font.PDFont.encode(PDFont.java:285)
at org.apache.pdfbox.pdmodel.font.PDFont.getStringWidth(PDFont.java:314)
at com.fatfractal.test.PDFBoxTest.textWidth(PDFBoxTest.java:148)
at com.fatfractal.test.PDFBoxTest.showFlowingTextAt(PDFBoxTest.java:128)
at com.fatfractal.test.PDFBoxTest.build(PDFBoxTest.java:73)
at com.fatfractal.test.PDFBoxTest.main(PDFBoxTest.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)