Itext html转PDF,解决中文不显示与样式问题

网上有好多的代码实例,好多都说可以解决中文以及样式问题,然而并不能,好不容易找到一篇,可以解决的,真心不容易,赶紧贴出来,备份一下。
import com.itextpdf.text.pdf.BaseFont;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;

/**
 * 文件格式转换工具类
 *
 * @author lbj
 *
 * 2015-10-8 上午10:52:22
 */
public class FileTypeConvertUtil {

    /**
     * 将HTML转成PD格式的文件。html文件的格式比较严格
     * @param htmlFile
     * @param pdfFile
     * @throws Exception
     */
    // <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
    public static void html2pdf(String htmlFile, String pdfFile) throws Exception {
        // step 1
        String url = new File(htmlFile).toURI().toURL().toString();
        System.out.println(url);
        // step 2
        OutputStream os = new FileOutputStream(pdfFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(getXmlString());
//        renderer.setDocument(url);

        // step 3 解决中文支持
        ITextFontResolver fontResolver = renderer.getFontResolver();
        if("linux".equals(getCurrentOperatingSystem())){
            fontResolver.addFont("/usr/share/fonts/chiness/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        }else{
            fontResolver.addFont("C:\\Users\\Spring\\Desktop\\simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont("C:\\Users\\Spring\\Desktop\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        }

        renderer.layout();
        renderer.createPDF(os);
        os.close();

        System.out.println("create pdf done!!");

    }

    public static String getCurrentOperatingSystem(){
        String os = System.getProperty("os.name").toLowerCase();
        System.out.println("---------当前操作系统是-----------" + os);
        return os;
    }
    public static String getXmlString() {
        String xmlString="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
                "<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\"/>\n" +
                "    <title>Hello World</title>\n" +
                "\t<style>\n" +
                "\t  table.table-separate th{\n" +
                "    font-weight:bold;\n" +
                "    font-size:14px;\n" +
                "    border-top:1px solid #F3EDE9 !important;\n" +
                "  }\n" +
                "  table.table-separate td{\n" +
                "    padding: 13px 0;\n" +
                "    font-weight:100;\n" +
                "  }\n" +
                "  .table-separate td.tit{\n" +
                "    background-color: #f4f9fe;\n" +
                "    font-weight:normal;\n" +
                "    padding:22px 0;\n" +
                "    width:15%;\n" +
                "  }\n" +
                "  .table-separate td.cont{\n" +
                "    text-align: left;\n" +
                "    padding:16px 22px;\n" +
                "    width:85%;\n" +
                "    line-height:175%;\n" +
                "  }\n" +
                "  .table-separate.no-border th{\n" +
                "    border:none;\n" +
                "    text-align: left;\n" +
                "  }\n" +
                "  .table-separate.no-border td{\n" +
                "    text-align: left;\n" +
                "    border:none;\n" +
                "  }\n" +
                "\[email protected] {\n" +
                "\tsize:210mm 297mm;//纸张大小A4\n" +
                "\tmargin: 0.25in;\n" +
                "\t-fs-flow-bottom: \"footer\";\n" +
                "\t-fs-flow-left: \"left\";\n" +
                "\t-fs-flow-right: \"right\";\n" +
                "\tborder: thin solid black;\n" +
                "\tpadding: 1em;\n" +
                "\t}\n" +
                "\t#footer {\n" +
                "\tfont-size: 90%; font-style: italic;\n" +
                "\tposition: absolute; top: 0; left: 0;\n" +
                "\t-fs-move-to-flow: \"footer\";\n" +
                "\t}\n" +
                "\t#pagenumber:before {\n" +
                "\tcontent: counter(page);\n" +
                "\t}\n" +
                "\t#pagecount:before {content: counter(pages);\n" +
                "\t}\n" +
                "\ttable {\n" +
                "\t\t\tborder-collapse: collapse;\n" +
                "\t\t\ttable-layout: fixed;\n" +
                "\t\t\tword-break:break-all;\n" +
                "\t\t\tfont-size: 10px;\n" +
                "\t\t\twidth: 100%;\n" +
                "\t\t\ttext-align: center;\n" +
                "\t}\n" +
                "\ttd {\n" +
                "\t\tword-break:break-all;\n" +
                "\t\tword-wrap : break-word;\n" +
                "\t}\n" +
                "\t</style>\n" +
                "\t</head>\n" +
                "<body style = \"font-family: SimSun;\">\n" +
                "<div id=\"footer\" style=\"\">  Page <span id=\"pagenumber\"/> of <span id=\"pagecount\"/> </div>\n" +
                "<div id=\"main\">\n" +
                "    <div style=\"max-width:600px;margin:0 auto;padding:10px;\">\n" +
                "        <div style=\"text-align: center; padding: 5mm 0;\">\n" +
                "            <div style=\"font-weight: bold; font-size: 30px;\"> HI Fudi&amp;More</div>\n" +
                "            <div> THANK YOU FOR SHOPPING WITH Fudi&amp;More!</div>\n" +
                "        </div>\n" +
                "        <div style=\"border: 1px solid black; background-color: #f8f8f8; padding: 4mm;\">\n" +
                "            <div style=\"font-size: 17px; font-weight: bold; border-bottom: 1px solid black; padding-bottom: 5mm;\"> ORDER DETAILS</div>\n" +
                "            <div style=\"padding-top: 10px;\">\n" +
                "                <div><strong>Order:&nbsp;</strong>D-8C2Y Placed on 29/09/2019 10:04</div>\n" +
                "                <div><strong>Carrier:&nbsp;</strong>Delivery</div>\n" +
                "                <div><strong>Payment:&nbsp;</strong>Cash Payment</div>\n" +
                "            </div>\n" +
                "        </div>\n" +
                "        <div style=\"margin-top: 4mm;\">\n" +
                "            <table class=\"table-separate\" cellpadding=\"0\" cellspacing=\"0\" style=\"max-width:600px;margin:0 auto;padding:10px;\">\n" +
                "                <thead>\n" +
                "                <tr style=\"text-align: center; height: 40px;\">\n" +
                "                    <th style=\"width: 90px; background-color: #f8f8f8; border-top: 1px solid black; border-left: 1px solid black; border-right: 1px solid black;\">\n" +
                "                        Reference\n" +
                "                    </th>\n" +
                "                    <th colspan=\"2\" style=\"background-color: #f8f8f8; border-top: 1px solid black; border-right: 1px solid black;\">Product</th>\n" +
                "                    <th style=\"width: 110px; background-color: #f8f8f8; border-top: 1px solid black; border-right: 1px solid black;\">Unit price</th>\n" +
                "                    <th style=\"width: 80px; background-color: #f8f8f8; border-top: 1px solid black; border-right: 1px solid black;\">Quantity</th>\n" +
                "                    <th style=\"width: 90px; background-color: #f8f8f8; border-top: 1px solid black; border-right: 1px solid black;\">Total price</th>\n" +
                "                </tr>\n" +
                "                </thead>\n" +
                "                <tbody>\n" +
                "                <tr style=\"text-align: center; \">\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-left: 1px solid black; border-right: 1px solid black;\">\n" +
                "                        Main\n" +
                "                    </td>\n" +
                "                    <td colspan=\"2\"\n" +
                "                        style=\"border-top: 1px solid black; border-bottom:1px solid black; border-right: 1px solid black; text-align: left; padding: 010px;\">\n" +
                "                        SweetSour Chicken\n" +
                "                    </td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">&euro; 7.00</td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">1</td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">&euro; 7.00</td>\n" +
                "                </tr>\n" +
                "                <tr style=\"text-align: center; \">\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-left: 1px solid black; border-right: 1px solid black;\">\n" +
                "                        Main\n" +
                "                    </td>\n" +
                "                    <td colspan=\"2\"\n" +
                "                        style=\"border-top: 1px solid black; border-bottom:1px solid black; border-right: 1px solid black; text-align: left; padding: 010px;\">\n" +
                "                        Black Bean Stir Fry\n" +
                "                    </td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">&euro; 9.00</td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">1</td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">&euro; 9.00</td>\n" +
                "                </tr>\n" +
                "                <tr style=\"text-align: center; \">\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-left: 1px solid black; border-right: 1px solid black;\">\n" +
                "                        Pizzas\n" +
                "                    </td>\n" +
                "                    <td colspan=\"2\"\n" +
                "                        style=\"border-top: 1px solid black; border-bottom:1px solid black; border-right: 1px solid black; text-align: left; padding: 010px;\">\n" +
                "                        Test Design Your Own 8\" Pizza\n" +
                "                    </td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">&euro; 6.00</td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">1</td>\n" +
                "                    <td style=\"border-top: 1px solid black; border-bottom: 1px solid black; border-right: 1px solid black;\">&euro; 6.00</td>\n" +
                "                </tr>\n" +
                "                </tbody>\n" +
                "                <tfoot>\n" +
                "                <tr style=\"text-align: center; height: 8mm;\">\n" +
                "                    <td colspan=\"5\"\n" +
                "                        style=\"text-align: right; width: 90px; background-color: #f8f8f8; border-bottom: 1px solid black; border-left: 1px solid black; border-right: 1px solid black; padding: 0 10px;\">\n" +
                "                        Item:\n" +
                "                    </td>\n" +
                "                    <td style=\"background-color: #f8f8f8; border-bottom: 1px solid black; border-right: 1px solid black;\">3</td>\n" +
                "                </tr>\n" +
                "                <tr style=\"text-align: center; height: 8mm;\">\n" +
                "                    <td colspan=\"5\"\n" +
                "                        style=\"text-align: right; width: 90px; background-color: #f8f8f8; border-bottom: 1px solid black; border-left: 1px solid black; border-right: 1px solid black; padding: 0 10px;\">\n" +
                "                        Subtotal:\n" +
                "                    </td>\n" +
                "                    <td style=\"background-color: #f8f8f8; border-bottom: 1px solid black; border-right: 1px solid black;\">&euro;24.00</td>\n" +
                "                </tr>\n" +
                "                <tr style=\"text-align: center; height: 8mm;\">\n" +
                "                    <td colspan=\"5\"\n" +
                "                        style=\"text-align: right; width: 90px; background-color: #f8f8f8; border-bottom: 1px solid black; border-left: 1px solid black; border-right: 1px solid black; padding: 0 10px;\">\n" +
                "                        Deliver Fee:\n" +
                "                    </td>\n" +
                "                    <td style=\"background-color: #f8f8f8; border-bottom: 1px solid black; border-right: 1px solid black;\">+&euro;2.00</td>\n" +
                "                </tr>\n" +
                "                <tr style=\"text-align: center; height: 8mm;\">\n" +
                "                    <td colspan=\"5\"\n" +
                "                        style=\"text-align: right; width: 90px; background-color: #f8f8f8; border-bottom: 1px solid black; border-left: 1px solid black; border-right: 1px solid black; padding: 0 10px;\">\n" +
                "                        Discount:\n" +
                "                    </td>\n" +
                "                    <td style=\"background-color: #f8f8f8; border-bottom: 1px solid black; border-right: 1px solid black;\">-&euro;0.00</td>\n" +
                "                </tr>\n" +
                "                <tr style=\"text-align: center; height: 8mm;\">\n" +
                "                    <td colspan=\"5\"\n" +
                "                        style=\"text-align: right; width: 90px; background-color: #f8f8f8; border-bottom: 1px solid black; border-left: 1px solid black; border-right: 1px solid black; padding: 0 10px;\">\n" +
                "                        Total:\n" +
                "                    </td>\n" +
                "                    <td style=\"background-color: #f8f8f8; border-bottom: 1px solid black; border-right: 1px solid black;\">&euro;24.00</td>\n" +
                "                </tr>\n" +
                "                </tfoot>\n" +
                "            </table>\n" +
                "        </div>\n" +
                "        <div>\n" +
                "            <div style=\"border: 1px solid black; background-color: #f8f8f8; padding:5mm; margin-top: 5mm;\">\n" +
                "                <div style=\"font-size: 17px; font-weight: bold; border-bottom: 1px solid black; padding-bottom: 15px;\"> DELIVERY ADDRESS</div>\n" +
                "                <div style=\"padding-top: 10px;\">\n" +
                "                    <div><strong>guan</strong> ☎ <strong>13656690321</strong></div>\n" +
                "                    <div> 1024/ Edenhall,ModelFarmRd,Cork,爱尔兰,A 2048</div>\n" +
                "                </div>\n" +
                "            </div>\n" +
                "        </div>\n" +
                "        <div style=\"font-size: 13px;\"><p>You can review your order and download your invoice from the \"<a target=\"_blank\"\n" +
                "                                                                                                          href=\"http://www.fudiandmore.ie/#/FudiIndex/Order1\">Order\n" +
                "            history</a>\"section of your customer account by clicking \"<a target=\"_blank\" href=\"http://www.fudiandmore.ie/#/FudiIndex/Personalcenter1\">My\n" +
                "            account</a>\" on ourshop.</p></div>\n" +
                "        <hr style=\"border-width: 5px;\"/>\n" +
                "        <div> Fudi,More powered by <a target=\"_blank\" href=\"http://www.fudiandmore.ie\">A2BLiving</a></div>\n" +
                "    </div>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>";
        StringBuffer stringBuffer=new StringBuffer();

        return xmlString;
    }

    public static void main(String[] args) {
        //        String htmlFile = "/home/lbj/sign.jsp";
        //        String pdfFile = "/home/lbj/sign.pdf";
        String htmlFile = "C:\\Users\\Spring\\Desktop\\qqq.html";
        String pdfFile = "C:\\Users\\Spring\\Desktop\\testoone2.pdf";
        try {
            FileTypeConvertUtil.html2pdf(htmlFile, pdfFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.9</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.9</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf-itext5</artifactId>
            <version>9.0.3</version>
        </dependency>

这就完了.直接运行没问题。还有比如 & 在正文中的要转义 &amp; 要不然报错,格式一定要正确,</>结束符一定要有,标准也要有

<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
                <html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">这个缺了你可以试试,出了问题你自己该,还有一点很重要,body 中指定字体,不指定的,中文你就不要想它出现了。还有一些 分页啥的,样式里写好就行,要是超宽了,那就自己看着实例的样式改改,大概就好了。

原文地址:https://www.cnblogs.com/hxz-nl/p/11611909.html

时间: 2024-10-09 21:06:34

Itext html转PDF,解决中文不显示与样式问题的相关文章

itext7 List序号 有序列表 解决中文不显示

注意:1.itextpdf的版本为7.0.5(7.1.4的版本过高,用本示例会报错(比如7.0.5是这个包是com.itextpdf.kernel.color.Color,在7.1.4会升级为com.itextpdf.kernel.colors.Color):  7.0.0的版本低,  也会报错.) 2.jdk要在1.7及以上 3.maven版本也不要太低了(推荐3.3) 4.本文根据官方例子(https://itextpdf.com/en/resources/examples/itext-7/

Visual Studio Code 1.44 解决中文代码显示乱码问题(小白图文教程)

现今主流的计算机中文字符编码方案是:GBK和UTF-8. 不同编码方案使用不同的字符集,GBK字符集在中文字符长度和字符数量上存在绝对优势,但对国外字符并不支持.所以,完全面向国内的程序/网页使用的是GBK字符集的GBK编码,而面向国外或面向国内兼国外的程序/网页使用的是Unicode字符集的UTF-8编码. 如果在使用Visual Studio Code 1.44打开源码文件时,出现乱码,那很有可能是因为该文件字符编码是GBK.(没错,Visual Studio Code 1.44默认的字符编

iReport 5.6.0 PDF导出中文不显示问题 解决方案

问题描述 iReport 5.6.0 PDF格式导出,中文不显示. 报错信息如下: Error exporting print... Could not load the following font : pdfFontName   : STSong-LightpdfEncoding   : UniGB-UCS2-HisPdfEmbedded : truenet.sf.jasperreports.engine.JRRuntimeException: Could not load the foll

Zabbix监控(十一):解决中文字体显示乱码问题

问题: 在WEB端上中文会显示为问号,当创建一个GRAPH,名字中带中文时会报错: (latin1_swedish_ci,IMPLICIT)  and (utf8_general_ci,COERCIBLE) for operation '=' 意思是使用了两种不同的字符集(latin1和utf8) 1.方法一:网上找到最多也就是添加字体文件方法 将windows系统中的字体文件(控制面板->字体->楷体simkai.ttf)拷贝到/var/www/html/zabbix/fonts/ 修改服务

iText 中文无法显示

/** * 导出PDF工具com.lowagie.itext测试 * * @param response * @throws IOException * @throws DocumentException */ @RequestMapping(value = "/emp/download/pdf", method = RequestMethod.GET) public void downloadPdf(HttpServletResponse response) throws IOExc

Sublime的中文GBK显示乱码的解决方法

import urllib2,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.

cocos2d-x 3.0 使用Sax解析xml文档(解决中文显示问题)

今天是个好日子,心想的事儿都能成,明天是个好日子,打开了家门儿迎春风... 恩,听着歌写文档生活就是这么享受. 今天以前的邻居大神突然在qq上赞了我一下,这让我异常激动啊..这还要从前前前几天说起,那会无意间看到cocos微信上的一个实话实说活动,反正就是参加了可以抽奖这样子啦,没错,我就是本着那官方T恤去的,本着分子越大分母越大抽奖几率越大的原则,然后就连着发了一番感慨,而且还都是比较罗嗦,没想到隔天cocos君竟然给我回复了,中奖了有木有,cocos2dx的官方T恤,哈哈..然后就是以前的大

解决Ubuntu系统中文乱码显示问题,终端打开文件及查看目录

解决Ubuntu系统中文乱码显示问题 [日期:2014-02-20] 来源:Linux社区  作者:njchenyi [字体:大 中 小] 我是先安装了Ubuntu 12.04 Server,然后安装桌面.进入以后发现中文有问题. 解决方法:一. Ubuntu默认的中文字符编码Ubuntu默认的中文字符编码为zh_CN.UTF-8,这个可以在/etc/environment中看到:sudo gedit /etc/environment可以看到如下内容:PATH="/usr/local/sbin:

plsql中文乱码显示问号的解决办法

问题现象:  PLSQL执行sql语句,不识别中文,输出的中文标题显示成问号????. 解决办法: 1. 登陆plsql,执行sql语句,输出的中文标题显示成问号????:条件包含中文,则无数据输出:查询出的内容含有中文显示成????. 2.输入sql语句select * from V$NLS_PARAMETERS t WHERE t.PARAMETER='NLS_LANGUAGE'查看字符集,查看value值是否为简体中文. 3.进入注册表,依次单击HKEY_LOCAL_MACHINE ---