还在为HTML转PDF发愁?再介绍两款工具,为你保驾护航!

关注我的公众号:【编程朝花夕拾】,可获取首发内容。

01 引言

在之前专门写了一篇文章《SpringBoot集成:5分钟实现HTMLPDF功能》,介绍三款HtmlPDF的工具。这不,又发现了两款类似的工具,整理一下分享给大家。

02 itext-pdfhtml-java

2.1 简介

iText pdfHTMLiText7套件的一个附加组件,专门用于将HTMLCSS内容转换为PDF文档。它基于iText核心PDF生成引擎,提供了高质量的HTMLPDF转换功能。性能表现非常优异。

主要特性:

  • 完整的HTML5CSS3支持:能够处理现代网页布局和样式
  • 字体嵌入:自动处理Web字体和系统字体
  • 响应式设计:支持媒体查询和响应式布局
  • 高保真转换:保持HTML内容的视觉保真度
  • Java原生:专为Java生态系统设计

GitHub地址:github.com/itext/itext...

官方地址:itextpdf.com/products/co...

2.2 案例

使用起来也非常简单,下面官方的案例:

Maven依赖

xml 复制代码
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>html2pdf</artifactId>
    <version>6.2.1</version>
</dependency>

实践代码

java 复制代码
@RequestMapping("index6")
public void index6(Model model, HttpServletResponse response) throws IOException {
    List<Map<String, Object>> list = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        Map<String, Object> item = new HashMap<>();
        item.put("image1", "http://example.com/2eb97.jpg");
        item.put("image2", "http://example.com/2f9c3.jpg");
        item.put("vehicleName", "路虎Defender[卫士](进口)2023款Defender130 48V[卫士 130 48V] 3.0T手自-体P400 HSE");
        item.put("brandName", "路虎");
        item.put("seriesName", "Defender[卫士]");
        item.put("modelYear", "2023款");
        item.put("licenseYear", SDF.format(new Date()));
        item.put("displayMileage", DF.format(new BigDecimal("9657")));
        item.put("dealDate", SDF.format(new Date()));
        item.put("dealPrice", DF.format(new BigDecimal("702400")));

        item.put("licenseCode", "沪A952714");

        list.add(item);
    }
    model.addAttribute("list", list);
    Map<String, Object> map = new HashMap<>();
    map.put("list", list);

    Context context = new Context(Locale.getDefault(), map);
    String htmlContent = templateEngine.process("index", context);
    System.out.println(htmlContent);

    // ---------------------------------------------------
    /*itext-html2pdf*/
    ConverterProperties properties = new ConverterProperties();

    FontProvider fontProvider = new FontProvider();
    fontProvider.addSystemFonts();
//        fontProvider.addFont("C:\\Windows\\Fonts\\simhei.ttf");
    // 添加系统字体
    properties.setFontProvider(fontProvider);

    HtmlConverter.convertToPdf(htmlContent, response.getOutputStream(), properties);
}

同样默认是不支持中文的,需要通过FontProvider添加指定的字体。fontProvider.addSystemFonts();直接添加系统字体,也可以通过addFont()添加自定义字体。页面必须声明字体,否则会出现乱码。

03 x-easypdf

3.1 简介

x-easypdf是一个java语言简化处理pdf的框架,包含fop模块与pdfbox模块,fop模块以创建功能为主,基于xsl-fo模板生成pdf文档,以数据源的方式进行模板渲染;pdfbox模块以编辑功能为主,对标准的pdfbox进行扩展,添加了成吨的功能。

HtmlPdfpdfbox模块下的一个转化器的功能,是基于 playwright 实现的。而playwright的依赖需要手动引入。Playwright是一个跨语言的浏览器自动化库,由Microsoft开发。虽然主要用于端到端测试,但其强大的PDF生成功能也使其成为HTMLPDF的优秀工具。

Gitee地址:gitee.com/dromara/x-e...

官网地址:x-easypdf.cn/

3.2 案例

x-easypdf是对playwrigh的功能做了一层包装,使用起来更方便。

Maven依赖

xml 复制代码
<dependency>
    <groupId>org.dromara</groupId>
    <artifactId>x-easypdf</artifactId>
    <version>3.4.7</version>
</dependency>
<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.53.0</version>
</dependency>

实践代码01

java 复制代码
@RequestMapping("index10")
public void index10(HttpServletResponse response) throws IOException {
    // 获取html转换器
    HtmlConvertor convertor = PdfHandler.getDocumentConvertor().getHtmlConvertor();
    Document pdf = convertor.toPdf("http://127.0.0.1:8080/page/index");
    pdf.save(response.getOutputStream());
}

注意事项

playwrigh是基于浏览器引擎的,首次调用会下载默认的浏览器,下载完成之后,后续的使用就流畅了。而且默认支持中文,因为使用浏览器引擎,所以对于HtmlCss支持较好。但是消耗资源较高。

但是这里convertor.toPdf()目前支持传入地址和文件。不支持直接html内容直接转化的。但是playwrigh本身是支持的。

小编已经给x-easypdf作者提了issuesgitee.com/dromara/x-e...

**注意:**截止发稿,官方已经在3.5.0版本支持了html内容转Pdf

实战代码02

使用模板引擎的方式:

官网地址:x-easypdf.cn/guide/pdfbo...

依然是建立在playwrigh基础之上。

java 复制代码
@RequestMapping("index12")
public void index12(HttpServletResponse response) throws IOException {
    List<Map<String, Object>> list = new ArrayList<>();
    for (int i = 0; i < 3; i++) {
        Map<String, Object> item = new HashMap<>();
        item.put("image1", "http://example.com/2eb97.jpg");
        item.put("image2", "http://example.com/2f9c3.jpg");
        item.put("vehicleName", "路虎Defender[卫士](进口)2023款Defender130 48V[卫士 130 48V] 3.0T手自-体P400 HSE");
        item.put("brandName", "路虎");
        item.put("seriesName", "Defender[卫士]");
        item.put("modelYear", "2023款");
        item.put("licenseYear", SDF.format(new Date()));
        item.put("displayMileage", DF.format(new BigDecimal("9657")));
        item.put("dealDate", SDF.format(new Date()));
        item.put("dealPrice", DF.format(new BigDecimal("702400")));

        item.put("licenseCode", "沪A952714");

        list.add(item);
    }
    Map<String, Object> map = new HashMap<>();
    map.put("list", list);

    ThymeleafTemplater templater = PdfHandler.getDocumentTemplater().getThymeleafTemplater();
    templater.setTemplatePath("templates");
    templater.setTemplateName("index.html");
    templater.setTemplateData(map);

    // 获取 html 内容
    String content = templater.getHtmlContent();
    System.out.println(content);

    // 转换文档
    Document document = templater.transform();
    document.save(response.getOutputStream());
}

这里需要说明的是:由于x-easypdf自行解析了Thymeleaf模版,所以无法使用spring-boot-starter-thymeleaf的配置。templatePathtemplateName都需要写完整。templatePathclasspath下的路径。

模板引擎可能会出现nested exception is java.lang.NoClassDefFoundError: ognl/PropertyAccessor的错误,需要引入ognl,且版本不能超过3.2。从 3.2 开始,会报java.lang.NoClassDefFoundError: ognl/DefaultMemberAccess。有效版本:

xml 复制代码
<dependency>
	<groupId>ognl</groupId>
	<artifactId>ognl</artifactId>
	<version>3.1.28</version>
</dependency>

边距可以通过打印样式控制:

css 复制代码
@page {
    size: A4;
    margin: 20px;
}

3.3 playwrigh原生写法

java 复制代码
@RequestMapping("index11")
public void index11(HttpServletResponse response) throws IOException {
    try (Playwright playwright = Playwright.create();
         Browser browser = playwright.chromium().launch()) {
        BrowserContext context = browser.newContext();
        Page page = context.newPage();

        // 从HTML内容生成PDF
        page.setContent("<h1>Hello, Playwright!</h1>");
        byte[] pdf = page.pdf();

        ByteArrayInputStream bais = new ByteArrayInputStream(pdf);
        IOUtils.copy(bais, response.getOutputStream());
    }
}

04 小结

iText pdfHTML内存占用低,转换速度快,适合服务器端批量处理。而Playwright需要更多资源,但渲染质量极高,适合对视觉保真度要求高的场景,所以x-easypdf也是一样的。如果只是针对HtmlPdf的服务端转化的场景iText pdfHTML的优势更明显一下,关键它快!

也有粉丝朋友留言说jasperreports也很好用,小编也试了一下。jasperreports需要加载特定的模板,也许是因为不是很熟悉,用起来感觉有点别扭。这里就不推荐了,有兴趣的可以去试试!

相关推荐
创码小奇客2 小时前
Spring Boot依赖排坑指南:冲突、循环依赖全解析+实操方案
后端·面试·架构
龙泉寺天下行走2 小时前
[Powershell入门教程]第4天:模块、脚本编写、错误处理与 .NET 集成
java·服务器·前端
aniden2 小时前
Swagger从入门到实战
java·开发语言·spring
泥嚎泥嚎2 小时前
【Android】给App添加启动画面——SplashScreen
android·java
Java天梯之路2 小时前
09 Java 异常处理
java·后端
玖剹2 小时前
多线程编程:从日志到单例模式全解析
java·linux·c语言·c++·ubuntu·单例模式·策略模式
Penge6662 小时前
Go 通道引用与 close 操作
后端
一 乐2 小时前
社区养老保障|智慧养老|基于springboot+小程序社区养老保障系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·小程序
程序员爱钓鱼2 小时前
Python编程实战 - Python实用工具与库 - 操作Word:python-docx
后端·python