添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

秀's Home

生于忧患 死于安乐

HTML转换PDF

HTML转换PDF

添加maven依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<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>

转换环境准备

  1. 输入的HTML页面必须是标准的HTML
    1
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
  2. 语法必须是标准的HTML语法:所有标签都必须闭合
  3. CSS中必须指定字体,然后在java代码中设置相应的字体

    代码实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    package com.fine.demo.util;

    import com.google.common.base.Throwables;
    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.pdf.BaseFont;
    import lombok.extern.slf4j.Slf4j;
    import org.xhtmlrenderer.pdf.ITextFontResolver;
    import org.xhtmlrenderer.pdf.ITextRenderer;

    import javax.annotation.PostConstruct;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    /**
    * Copyright (c) 2020 杭州***有限公司
    * Date: 2020/9/29
    * Time: 下午1:35
    *
    * @author 2020年 <a href="mailto:[email protected]">秀</a>
    */
    @Slf4j
    public class FileTypeConvertUtil {

    public static String pdfPath;
    public static String fontPath;

    /**
    * 将HTML转成PDF格式的文件
    * html文件的格式比较严格
    *
    * @param htmlFilePath html文件路径
    * @param pdfFilePath pdf文件路径
    */
    public static void html2pdf(String htmlFilePath, String pdfFilePath) {
    try {
    log.info("FileTypeConvertUtil[]html2pdf[]start! htmlFilePath:{}, pdfFilePath:{}", htmlFilePath, pdfFilePath);
    // step 1
    String url = new File(htmlFilePath).toURI().toURL().toString();

    // step 2
    OutputStream os = new FileOutputStream(pdfFilePath);
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(url);

    // step 3 解决中文支持
    String fontPath = "";
    ITextFontResolver fontResolver = renderer.getFontResolver();
    fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

    renderer.layout();
    renderer.createPDF(os);
    os.close();
    log.info("FileTypeConvertUtil[]html2pdf[]success!");
    } catch (Exception e) {
    log.error("FileTypeConvertUtil[]html2pdf[]error! cause:{}", Throwables.getStackTraceAsString(e));
    }
    }

    /**
    * 【maven项目打jar包,无法获取font路径】
    * 解决方案:将文件提取到jar包通路径
    */
    @PostConstruct
    public void init() {
    try {
    // 构造jar包外部的pdf文件夹+字体文件
    log.info("FileTypeConvertUtil[]init[]make[]contractFile[]start!");
    pathInit();

    // 创建pdf文件夹
    log.info("FileTypeConvertUtil[]init[]createPdfFile[]pdfPath:{}", pdfPath);
    createPdfFile();

    // 初始化字体文件
    log.info("FileTypeConvertUtil[]init[]createFontFile[]fontPath:{}", fontPath);
    createFontFile();

    log.info("FileTypeConvertUtil[]init[]success!");
    } catch (IOException e) {
    log.error("FileTypeConvertUtil[]init[]error! cause:{}", Throwables.getStackTraceAsString(e));

    }
    }

    private void createFontFile() throws IOException {
    InputStream fontIs = this.getClass().getResourceAsStream("/pdf/simsun.ttf");
    OutputStream outputStream = new FileOutputStream(new File(fontPath));

    int byteCount = 0;
    byte[] bytes = new byte[1024];
    while ((byteCount = fontIs.read(bytes)) != -1) {
    outputStream.write(bytes, 0, byteCount);
    }
    fontIs.close();
    outputStream.close();
    }


    private void createPdfFile() {
    File contractFile = new File(pdfPath);
    if (!contractFile.exists()) {
    contractFile.mkdir();
    }
    }

    private void pathInit() {
    // 项目路径
    String jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    // 项目名称
    String itemName = "***.jar";
    if (jarPath.contains(itemName)) {
    // jarPath路径需自己调试
    jarPath = jarPath.substring(6, jarPath.indexOf(itemName));
    }
    pdfPath = jarPath + "pdf";
    fontPath = pdfPath + "/simsun.ttf";
    }
    }

    常见问题

中文不显示问题 :
body加上任意中文字体,如宋体:SimSun

1
<body style="font-family: SimSun">

本文标题: HTML转换PDF

文章作者:

发布时间: 2020年09月29日 - 16:02:18

最后更新: 2020年10月12日 - 09:26:11

原始链接: https://www.finedemo.cn/198480456/

许可协议: 转载请保留原文链接及作者。