The default fonts in PDFBox do not support Chinese characters hence we need Unicode fonts for that. Lets see how to write Chinese in pdf using Apache PDFBox.
Exception using default fonts
If you try to write Chinese characters in a PDF using the any of the default fonts provided, then we get exceptions something like displayed below
1 2 3 4 5 |
Exception in thread "main" java.lang.IllegalArgumentException: U+8FD9 ('.notdef') is not available in this font Helvetica encoding: WinAnsiEncoding at org.apache.pdfbox.pdmodel.font.PDType1Font.encode(PDType1Font.java:426) at org.apache.pdfbox.pdmodel.font.PDFont.encode(PDFont.java:324) at org.apache.pdfbox.pdmodel.PDPageContentStream.showTextInternal(PDPageContentStream.java:509) at org.apache.pdfbox.pdmodel.PDPageContentStream.showText(PDPageContentStream.java:471) |
To avoid this, we need to add a Unicode font while writing Chinese characters. I have used Arial Unicode. You can download it from here
Lets see an example using the Unicode fonts file and some Chinese words
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package com.kscodes.examples.pdfbox; import java.io.File; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.font.PDFont; import org.apache.pdfbox.pdmodel.font.PDType0Font; public class PdfChineseExample { public static void main(String args[]) { // Create a Document object. PDDocument pdDocument = new PDDocument(); // Create a Page object PDPage pdPage = new PDPage(); // Add the page to the document and save the document to a desired file. pdDocument.addPage(pdPage); try { // Create a Content Stream PDPageContentStream pdPageContentStream = new PDPageContentStream(pdDocument, pdPage); // Start the stream pdPageContentStream.beginText(); // Set the X and Y corodinates for the text to be positioned pdPageContentStream.newLineAtOffset(25, 700); // Set a Font and its Size // We cannot use the standard fonts provided. // pdPageContentStream.setFont(PDType1Font.HELVETICA, 12); PDFont unicodeFont = PDType0Font.load(pdDocument, new File("K:\\Kscodes\\pdf\\ARIALUNI.TTF")); pdPageContentStream.setFont(unicodeFont, 14); pdPageContentStream.showText("这是我的第一个字"); // End the Stream pdPageContentStream.endText(); // Once all the content is written, close the stream pdPageContentStream.close(); pdDocument.save("K:\\Kscodes\\pdf\\chinese-sample.pdf"); pdDocument.close(); System.out.println("PDF saved to the location !!!"); } catch (IOException ioe) { System.out.println("Error while saving pdf" + ioe.getMessage()); } } } |
Output