zoukankan      html  css  js  c++  java
  • itext转html为pdf遇到的问题

    记录一下使用itext将html文件转为pdf文件遇到的一些问题

    1、中文不显示

    原因:itext默认不支持中文

    解决方法:引入中文字体

    需要注意的是在java代码中设置好中文字体后,还需要在html引用该字体,否则不会起效果。

    2、css不起作用

    原因:css文件使用的是相对路径

    解决方法:将相对路径改为绝对路径或者将css写在html文件内部

    3、html内容转换为pdf后,内容显示不全

    原因:

    解决方法:在html文件中设定纸张大小,如A4纸张@page{size:a4}

     

    具体请参考以下代码

    首先在pom.xml文件中引入itext相关jar包

    <!--itext-->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>
    
    <dependency>
        <groupId>org.xhtmlrenderer</groupId>
        <artifactId>core-renderer</artifactId>
        <version>R8</version>
    </dependency>

    实现将html文件转换为pdf文件代码如下:

    package com.lnjecit.util;
    
    import com.lowagie.text.pdf.BaseFont;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.ResourceUtils;
    import org.xhtmlrenderer.pdf.ITextFontResolver;
    import org.xhtmlrenderer.pdf.ITextRenderer;
    
    import java.io.*;
    import java.net.MalformedURLException;
    
    /**
     * Pdf处理工具类
     *
     * @author
     * @create 2017-12-18 21:25
     **/
    public class PdfUtil {
    
        protected static Logger logger = LoggerFactory.getLogger(PdfUtil.class);
    
        /**
         *
         * @param htmlFile html文件存储路径
         * @param pdfFile  生成的pdf文件存储路径
         * @param chineseFontPath 中文字体存储路径
         */
        public static void html2pdf(String htmlFile, String pdfFile, String chineseFontPath)  {
            // step 1
            String url;
            OutputStream os = null;
            try {
                url = new File(htmlFile).toURI().toURL().toString();
                os = new FileOutputStream(pdfFile);
                ITextRenderer renderer = new ITextRenderer();
                renderer.setDocument(url);
                // 解决中文不显示问题
                ITextFontResolver fontResolver = renderer.getFontResolver();
                fontResolver.addFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    
                renderer.layout();
                renderer.createPDF(os);
            } catch (MalformedURLException e) {
                logger.warn(e.toString(), e);
            } catch (FileNotFoundException e) {
                logger.warn(e.toString(), e);
            } catch (com.lowagie.text.DocumentException e) {
                logger.warn(e.toString(), e);
            } catch (IOException e) {
                logger.warn(e.toString(), e);
            } finally {
                if(os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        logger.warn(e.toString(), e);
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            try {
                //html文件路径
                String htmlFilePath = "E:\projects\learn\spring-boot\springboot-learn\springboot-learn\springboot-poi\src\main\resources\templates\index.html";
                // 中文字体存储路径
                String chineseFontPath = "E:\projects\learn\spring-boot\springboot-learn\springboot-learn\springboot-poi\src\main\resources\Fonts\simsun.ttc";
                // html转pdf
                html2pdf(htmlFilePath,"E:\projects\learn\spring-boot\springboot-learn\springboot-learn\springboot-poi\src\main\resources\templates\index.pdf", chineseFontPath);
                System.out.println("转换成功!");
            } catch (Exception e) {
                logger.error("html转换为pdf失败", e);
            }
        }
    }

    测试的html内容如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>认识table表标签</title>
        <style type="text/css">
            /*解决html转pdf文件中文不显示的问题*/
            body {
                font-family: SimSun;
            }
    
            /*设定纸张大小*/
            /* A4纸 */
            /* @page{size:210mm*297mm} */
            @page{size:a4}
    
            p {
                color: red;
            }
        </style>
    </head>
    <body>
        <table border="1px">
            <caption>我的标题</caption>
            <tbody>
            <tr>
                <th>班级</th>
                <th>学生数</th>
                <th>平均成绩</th>
                <th>班级</th>
                <th>学生数</th>
                <th>平均成绩</th>
                <th>班级</th>
                <th>学生数</th>
                <th>平均成绩</th>
            </tr>
            <tr>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
            </tr>
            <tr>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
            </tr>
            <tr>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
                <td>一班</td>
                <td>30</td>
                <td>89</td>
            </tr>
            </tbody>
        </table>
    
        <p>
            《侠客行》<br/>
            年代: 唐 作者: 李白<br/>
            赵客缦胡缨,吴钩霜雪明。银鞍照白马,飒沓如流星。
            十步杀一人,千里不留行。事了拂衣去,深藏身与名。
            闲过信陵饮,脱剑膝前横。将炙啖朱亥,持觞劝侯嬴。
            三杯吐然诺,五岳倒为轻。眼花耳热后,意气素霓生。
            救赵挥金槌,邯郸先震惊。千秋二壮士,煊赫大梁城。
            纵死侠骨香,不惭世上英。谁能书閤下,白首太玄经。
        </p>
    </body>
    </html>
    package com.lnjecit.util;
    
    import com.lowagie.text.pdf.BaseFont;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.ResourceUtils;
    import org.xhtmlrenderer.pdf.ITextFontResolver;
    import org.xhtmlrenderer.pdf.ITextRenderer;
    
    import java.io.*;
    import java.net.MalformedURLException;
    
    /**
     * Pdf处理工具类
     *
     * @author
    * @create 2017-12-18 21:25
     **/
    public class PdfUtil {
    
        protected static Logger logger = LoggerFactory.getLogger(PdfUtil.class);
    
        /**
         *
         * @param htmlFile html文件存储路径
         * @param pdfFile  生成的pdf文件存储路径
         * @param chineseFontPath 中文字体存储路径
         */
    public static void html2pdf(String htmlFile, String pdfFile, String chineseFontPath)  {
            // step 1
    String url;
            OutputStream os = null;
            try {
                url = new File(htmlFile).toURI().toURL().toString();
                os = new FileOutputStream(pdfFile);
                ITextRenderer renderer = new ITextRenderer();
                renderer.setDocument(url);
                // 解决中文不显示问题
    ITextFontResolver fontResolver = renderer.getFontResolver();
                fontResolver.addFont(chineseFontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    
                renderer.layout();
                renderer.createPDF(os);
            } catch (MalformedURLException e) {
                logger.warn(e.toString(), e);
            } catch (FileNotFoundException e) {
                logger.warn(e.toString(), e);
            } catch (com.lowagie.text.DocumentException e) {
                logger.warn(e.toString(), e);
            } catch (IOException e) {
                logger.warn(e.toString(), e);
            } finally {
                if(os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        logger.warn(e.toString(), e);
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            try {
                //html文件路径
    String htmlFilePath = "E:\projects\learn\spring-boot\springboot-learn\springboot-learn\springboot-poi\src\main\resources\templates\index.html";
                // 中文字体存储路径
    String chineseFontPath = "E:\projects\learn\spring-boot\springboot-learn\springboot-learn\springboot-poi\src\main\resources\Fonts\simsun.ttc";
                // html转pdf
    html2pdf(htmlFilePath,"E:\projects\learn\spring-boot\springboot-learn\springboot-learn\springboot-poi\src\main\resources\templates\index.pdf", chineseFontPath);
                System.out.println("转换成功!");
            } catch (Exception e) {
                logger.error("html转换为pdf失败", e);
            }
        }
    }

    转换前的html页面效果如下

    转换后的pdf文件效果如下:

  • 相关阅读:
    如何使用腾讯位置服务地图选点组件?
    vue使用腾讯位置服务获取当前位置示例
    腾讯位置服务地址搜索&marker标记demo
    如何优雅接入腾讯地图SDK公交路线规划2?
    如何优雅接入腾讯地图SDK公交路线规划?
    地图SDK自定义路况和字体示例
    腾讯地图SDK自定义地图和路况示例
    手把手教你实现3D地图的定时高亮和点击事件
    vue实现坐标拾取器功能demo
    jmeter之安装ant
  • 原文地址:https://www.cnblogs.com/zuidongfeng/p/8060301.html
Copyright © 2011-2022 走看看