How to use iText to make Chinese PDF

1. Download itextpdf.jar

Basic package: http://jaist.dl.sourceforge.net/project/itext/iText/iText5.5.2/itext-5.5.2.zip

Additional package: http://cznic.dl.sourceforge.net/project/itext/extrajars/extrajars-2.3.zip

 

We just download the basic package.

2. Create working folder

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

  

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

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

  

daniel@daniel-mint ~/itext $ cat daniel.java 
import java.io.FileOutputStream;
import java.io.IOException;
 
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));
        document.open();

	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);
	par1.add(chk1);

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

	document.add(par1);
        document.close();
    }
}

  

3. You can write a shell to encode Unicode

Download the unicode tool first

sudo apt-get install unicode

  

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

  

daniel@daniel-mint ~/itext $ bash tounicode.sh This man is a programmer
\u8FD9\u4E2A\u4EBA\u662F\u4E2A\u7A0B\u5E8F\u5458\u554A

  

4. Execute script to generate PDF file

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

  

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.java  daniel.pdf  fonts  itextpdf-5.5.2.jar  run.sh  src  tags  tounicode.sh

  

Reprinted at: https://www.cnblogs.com/long123king/p/3945358.html

Tags: Java shell sudo

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