I believe that friends who have used Itext know that Chinese display has always been a problem (the latest version of 5.5.7 is not directly integrated with Chinese fonts).
Of course, such a problem, has long been a master to solve, that is, the use of Itextasian.jar.
but instead of using Itextasian.jar, this article describes another workaround.
Prior to this, you need to prepare only the Chinese font for Itextpdf-5.x.jar and a TTF format . For example, we often use the song body Simsun.ttf.
The first thing we need to do is integrate Simsun.ttf into our project:
Test examples:
Package Com.example.itext;import Java.io.fileoutputstream;import Java.io.ioexception;import Com.itextpdf.text.chunk;import Com.itextpdf.text.document;import Com.itextpdf.text.documentexception;import Com.itextpdf.text.font;import Com.itextpdf.text.pagesize;import Com.itextpdf.text.paragraph;import Com.itextpdf.text.phrase;import Com.itextpdf.text.pdf.basefont;import Com.itextpdf.text.pdf.pdfwriter;public Class Demo1 {//custom Chinese font location private static final String Fontpath = "/com/example/itext/simsun.ttf";p rivate static final Strin G Cfontpath = "/com/example/itext/dnmbxs.ttf";p ublic static void Main (string[] args) throws Documentexception, IOException {//create base font basefont BF = Basefont.createfont (fontpath,basefont.identity_h,basefont.embedded);// Custom font properties Font font = new Font (bf,30);D ocument document = new Document (PageSize.A4.rotate ()); PDFWriter writer = pdfwriter.getinstance (document, New FileOutputStream ("Test_cn.pdf")); Writer.setpdfversion ( pdfwriter.pdf_version_1_7);//make document Taggedwriter.Settagged ();//===============writer.setviewerpreferences (Pdfwriter.displaydoctitle);d ocument.addtitle ("Chinese test"); Writer.createxmpmetadata ();//=====================document.open (); Paragraph p = new Paragraph (),//embed fontp.setfont (font),//==================chunk c = new Chunk ("Chinese test");p. Add (c); Document.add (P); Basefont CBF = Basefont.createfont (cfontpath,basefont.identity_h,basefont.embedded); Font cfont = new Font (CBF,64); Phrase ph = new Phrase ("Chinese test", CFont);d ocument.add (ph);d ocument.close ();}}
Build Effect:
in fact, look at the implementation of Basefont, you will find that Itext also support the other 4 kinds of fonts:
TTF is our most common font.
Itext Generate PDF Chinese Font solution