How to use iText to make Chinese PDF

1. Download itextpdf.jar

Basic package:

Additional package:


We just download the basic package.

2. Create working folder

daniel@daniel-mint ~/itext $ ls  fonts  itextpdf-5.5.2.jar


fonts is a directory to store the font files we use.

daniel@daniel-mint ~/itext $ cat 
javac -cp .:itextpdf-5.5.2.jar $
java -cp .:itextpdf-5.5.2.jar $1 
rm $1.class


daniel@daniel-mint ~/itext $ cat 
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Rectangle;

import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.BaseFont;
public class daniel 
    public static final String RESULT = "daniel.pdf";
    public static void main(String[] args)
         throws DocumentException, IOException 
        Document document = new Document(PageSize.A4);
        PdfWriter.getInstance(document, new FileOutputStream(RESULT));;

	BaseFont noto_hans_bold  = BaseFont.createFont("./fonts/kaiti.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
	Font noto_hans_bold_24  = new Font(noto_hans_bold, 24);

        Paragraph par1 = new Paragraph(20);

	Chunk chk1 = new Chunk("Daniel King is a software engineer", noto_hans_bold_24);

	Chunk chk2 = new Chunk("\u8FD9\u4E2A\u4EBA\u662F\u4E2A\u7A0B\u5E8F\u5458\u554A", noto_hans_bold_24);



3. You can write a shell to encode Unicode

Download the unicode tool first

sudo apt-get install unicode


daniel@daniel-mint ~/itext $ cat 
unicode -s $1 | grep 'Uppercase' | sed -re 's/^U.*: U\+/\\u/g' | awk '{printf("%s", $1);}END{print ""}'


daniel@daniel-mint ~/itext $ bash This man is a programmer


4. Execute script to generate PDF file

daniel@daniel-mint ~/itext $ bash daniel
daniel@daniel-mint ~/itext $ ls  daniel.pdf  fonts  itextpdf-5.5.2.jar


5. Add source directory

Unzip itextpdf-5.5.2-sources.jar to src directory

Then create ctags file, so that you can easily browse back and forth in the source code.

daniel@daniel-mint ~/itext $ ls  daniel.pdf  fonts  itextpdf-5.5.2.jar  src  tags


Reprinted at:

Tags: Java shell sudo

Posted on Fri, 01 Nov 2019 15:15:11 -0700 by chrisuk