JAVA生成pdf文件

一、简介

PDF文件格式可以将文字、字型、格式、颜色及独立于设备和分辨率的图形图像等封装在一个文件中。本文实现将html页面转PDF。

二、实操

生成pdf文件成功,但是文字对不上。当修改”GetHtmlContent“部分的编码之后,再次执行生成PDF文件即可完成正确的实现。
在这里插入图片描述
Edit Configurations
在这里插入图片描述

三、原理解析

从这几点深入剖析和总结这个小项目:

1.是什么?

该项目实现了解析一个模板html文件,将其转为pdf文件并输出到相应的目录中。

1.1.关键技术

freemarker,FreeMarker是模板引擎,一个Java类库。
itextpdf,iText是一种生成PDF报表的Java类库,可以将Xml,Html文件转化为PDF文件。
类 XMLWorkerHelper,(用于解析 XHTML/CSS 或 XML 流到 PDF 的帮助器类)。

2.怎么做?为什么?

相关依赖

<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>
    <version>2.1.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.28</version>
</dependency>

模板文件:generationpdf.html,所在目录为src/main/resources/templates/generationpdf.html

<!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">标题</h1>
    <h4 class="title">副标题</h4>
    <span>当前时间: ${date_time} </span>
    <div class="signature">日期:${date}</div>
</div>
</body>
</html>

GetHtmlContent.java:获取模板内容

import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class GetHtmlContent {
    /**
     * 获取模板内容
     * @param templateDirectory 模板文件夹
     * @param templateName      模板文件名
     * @param paramMap          模板参数
     * @return
     * @throws Exception
     */
    public 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));
        ClassLoader classLoader = GetHtmlContent.class.getClassLoader();
        URL resource = classLoader.getResource("templates");
        String templateDirectory  =resource.toURI().getPath();

        String templateContent = GetHtmlContent.getTemplateContent(templateDirectory, "generationpdf.html", paramMap);
        System.out.println(templateContent);
    }

}

生成pdf文件,将date_time和date存储到HashMap中,然后将数据输出到pdf中

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


public class GeneratePDF {
    /**
     * HTML 转 PDF
     * @param content html内容
     * @param outPath           输出pdf路径
     * @return 是否创建成功
     */
    public static boolean html2Pdf(String content, String outPath) {
        try {
            Document document = new Document(); //创建一个标准的A4纸文档
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outPath));//书写器与ducument文档关联
            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:\\A.pdf";
        String templateDirectory = "src/main/resources/templates";
        String templateContent = GetHtmlContent.getTemplateContent(templateDirectory, "generationpdf.html", paramMap);
        GeneratePDF.html2Pdf(templateContent, outPath);

    }

}

3.参考

java实现生成PDF文件_xhga的博客-CSDN博客_java pdf
什么是 FreeMarker? - FreeMarker 中文官方参考手册 (foofun.cn)
iText官方教程_番薯(Koali)的博客-CSDN博客_itext官方文档
XMLWorkerHelper (root 5.5.9-SNAPSHOT API) (itextpdf.com)

  • 10
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疯狂java杰尼龟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值