java中springboot将html网页生成PDF文件的方法分享

书欣 SpringBoot 发布时间:2022-07-26 11:51:35 阅读数:10204 1
下文笔者讲述html网页生成pdf的方法分享,如下所示

pdf简介

PDF是可移植文档格式
 是一种电子文件格式 
  PDF文件格式可以将文字、字型、格式、颜色及独立于设备和分辨率的图形图像等放入一个文件中
  pdf文件包含超文本链接、声音和动态影像等电子信息
     支持特长文件,集成度和安全可靠性都较高
     在日常开发中,我们经常使用pdf文件作为合同文件打印 
---------------------------------------------------------------------
实现思路:
    1.引入相应的jar包
	2.生成相应的html文件
	3.输出相应的pdf文件
例:
SpringBoot框架实现HTML转PDF

引入jar包依赖

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

创建html模板pdftest_template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
    <style>
        body{font-family:SimSun;}
        .title{align-content: center;text-align: center;}
        .signature{float:right }
    </style>
</head>
<body>
<div>
    <h1 class="title">pdfTest</h1>
    <h4 class="title"> </h4>
    <span>当前时间: ${date_time} </span>
    <div class="signature">日期:${date}</div>
</div>
</body>
</html>
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class PdfUtilTest {
    /**
     * 获取模板内容
     * @param templateDirectory 模板文件夹
     * @param templateName      模板文件名
     * @param paramMap          模板参数
     * @return
     * @throws Exception
     */
    private static String getTemplateContent(String templateDirectory, String templateName, Map<String, Object> paramMap) throws Exception {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateDirectory));
        } catch (Exception e) {
            System.out.println("-- exception --");
        }

        Writer out = new StringWriter();
        Template template = configuration.getTemplate(templateName,"UTF-8");
        template.process(paramMap, out);
        out.flush();
        out.close();
        return out.toString();
    }
    public static void main(String[] args) throws Exception {
        Map<String, Object> paramMap = new HashMap<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
        paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));

        //获取html文件路径
		ClassLoader classLoader = PdfUtilTest.class.getClassLoader();
        URL resource = classLoader.getResource("templates");
        String templateDirectory  =resource.toURI().getPath();
        
		String templateContent = PdfUtilTest.getTemplateContent(templateDirectory, "pdftest_template.html", paramMap);
        System.out.println(templateContent);
    }
}

生成PDF文档

  
public static boolean html2Pdf(String content, String outPath) {
    try {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outPath));
        document.open();
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"));
        document.close();
    } catch (Exception e) {
        System.out.println("生成模板内容失败"+e.fillInStackTrace());
        return false;
    }
    return true;
}
/**
 * HTML 转 PDF
 * @param content html内容
 * @return PDF字节数组
 */
public static byte[] html2Pdf(String content) {
    ByteArrayOutputStream outputStream = null;
    try {
        Document document = new Document();
        outputStream = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new ByteArrayInputStream(content.getBytes()), null, Charset.forName("UTF-8"));
        document.close();
    } catch (Exception e) {
        System.out.println("------生成pdf失败-------");
    }
    return outputStream.toByteArray();
}
public static void main(String[] args) throws Exception {
    Map<String, Object> paramMap = new HashMap<>();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    paramMap.put("date_time", dateTimeFormatter.format(LocalDateTime.now()));
    paramMap.put("date", dateTimeFormatter.format(LocalDateTime.now()).substring(0, 10));
    String outPath = "D:\\Test.pdf";
    String templateDirectory = "D:\\";
    String templateContent = PdfUtilTest.getTemplateContent(templateDirectory, "pdftest_template.html", paramMap);
    PdfUtilTest.html2Pdf(templateContent, outPath);
    
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202207/4056.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者