Java读取pdf中文

直接使用系统字体读取或创建带中文的pdf,需要注意jar的版本。

        <dependency>
            <groupId>com.itextpdfgroupId>
            <artifactId>itextpdfartifactId>
            <version>5.5.8version>
        dependency>
        <dependency>
            <groupId>com.itextpdfgroupId>
            <artifactId>itext-asianartifactId>
            <version>5.2.0version>
        dependency>
        <dependency>
            <groupId>com.itextpdf.toolgroupId>
            <artifactId>xmlworkerartifactId>
            <version>5.5.6version>
        dependency>

代码如下,覆写XMLWorkerFontProvider$getFont即可读取中文

    public void createPdf(String src, String dest) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(src), null, new XMLWorkerFontProvider(){

            public Font getFont(final String fontname, final String encoding,  
                    final boolean embedded, final float size, final int style,  
                    final BaseColor color) {  
                BaseFont bf = null;  
                try {  
                    bf = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); 
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
                Font font = new Font(bf, size, style, color);  
                font.setColor(color);  
                return font;  
            }  

        });
        document.close();
    }

创建时,使用系统(windows下)的字体即可

    BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/SIMYOU.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);     
        Font font = new Font(baseFont); 

你可能感兴趣的:(java)