百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT知识 > 正文

Spring Boot集成itext实现html生成PDF功能

liuian 2024-12-04 13:46 57 浏览

1.itext介绍

iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件

iText 的特点

以下是 iText 库的显着特点 ?

  • Interactive ? iText 为你提供类(API)来生成交互式 PDF 文档。使用这些,你可以创建地图和书籍。
  • Adding bookmarks, page numbers, etc ? 使用 iText,你可以添加书签、页码和水印。
  • Split & Merge ? 使用 iText,你可以将现有的 PDF 拆分为多个 PDF,还可以向其中添加/连接其他页面。
  • Fill Forms ? 使用 iText,你可以在 PDF 文档中填写交互式表单。
  • Save as Image ? 使用 iText,你可以将 PDF 保存为图像文件,例如 PNG 或 JPEG。
  • Canvas ? iText 库为您提供了一个 Canvas 类,你可以使用它在 PDF 文档上绘制各种几何形状,如圆形、线条等。
  • Create PDFs ? 使用 iText,你可以从 Java 程序创建新的 PDF 文件。你也可以包含图像和字体。

2.代码工程

实验目标:将thymeleaf 的views生成成PDF

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>itextpdf</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>7.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

application.yaml

server:
  port: 8088
spring:
  thymeleaf:
    cache: false

DemoApplication

package com.et.itextpdf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@ServletComponentScan
@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

controller

converterProperties.setBaseUri 很重要。 否则,像 /main.css 这样的静态资源将无法找到

package com.et.itextpdf.controller;

import com.et.itextpdf.pojo.Order;
import com.et.itextpdf.util.OrderHelper;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
@RequestMapping("/orders")
public class PDFController {


    @Autowired
    ServletContext servletContext;

    private final TemplateEngine templateEngine;

    public PDFController(TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    @RequestMapping(path = "/")
    public String getOrderPage(Model model) {
        Order order = OrderHelper.getOrder();
        model.addAttribute("orderEntry", order);
        return "order";
    }

    @RequestMapping(path = "/pdf")
    public ResponseEntity<?> getPDF(HttpServletRequest request, HttpServletResponse response) throws IOException {

        /* Do Business Logic*/

        Order order = OrderHelper.getOrder();

        /* Create HTML using Thymeleaf template Engine */

        WebContext context = new WebContext(request, response, servletContext);
        context.setVariable("orderEntry", order);
        String orderHtml = templateEngine.process("order", context);

        /* Setup Source and target I/O streams */

        ByteArrayOutputStream target = new ByteArrayOutputStream();
        ConverterProperties converterProperties = new ConverterProperties();
        converterProperties.setBaseUri("http://localhost:8088");
        /* Call convert method */
        HtmlConverter.convertToPdf(orderHtml, target, converterProperties);

        /* extract output as bytes */
        byte[] bytes = target.toByteArray();


        /* Send the response as downloadable PDF */

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=order.pdf")
                .contentType(MediaType.APPLICATION_PDF)
                .body(bytes);

    }

}

view

Spring MVC 带有模板引擎,可以提供动态的 HTML 内容。 我们可以通过以下方法轻松将这些回复转换为 PDF 格式。 在本例中,我导入了 spring-boot-starter-web 和 spring-boot-starter-thymeleaf 来为我的 spring boot 项目提供 MVC 和 thymeleaf 支持。 您可以使用自己选择的模板引擎。 看看下面这个thymeleaf模板内容。 主要展示订单详细信息。 另外,通过 OrderHelper 的辅助方法来生成一些虚拟订单内容。

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
          name="viewport">
    <meta content="ie=edge" http-equiv="X-UA-Compatible">
    <title>Spring Boot - Thymeleaf</title>
    <link th:href="@{/main.css}" rel="stylesheet"/>
</head>
<body class="flex items-center justify-center h-screen">
<div class="rounded-lg border shadow-lg p-10 w-3/5">
    <div class="flex flex-row justify-between pb-4">
        <div>
            <h2 class="text-xl font-bold">Order #<span class="text-green-600" th:text="${orderEntry.orderId}"></span>
            </h2>
        </div>
        <div>
            <div class="text-xl font-bold" th:text="${orderEntry.date}"></div>
        </div>
    </div>
    <div class="flex flex-col pb-8">
        <div class="pb-2">
            <h2 class="text-xl font-bold">Delivery Address</h2>
        </div>
        <div th:text="${orderEntry.account.address.street}"></div>
        <div th:text="${orderEntry.account.address.city}"></div>
        <div th:text="${orderEntry.account.address.state}"></div>
        <div th:text="${orderEntry.account.address.zipCode}"></div>

    </div>
    <table class="table-fixed w-full text-right border rounded">
        <thead class="bg-gray-100">
        <tr>
            <th class="text-left pl-4">Product</th>
            <th>Qty</th>
            <th>Price</th>
            <th class="pr-4">Total</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="item : ${orderEntry.items}">
            <td class="pl-4 text-left" th:text="${item.name}"></td>
            <td th:text="${item.quantity}"></td>
            <td th:text="${item.price}"></td>
            <td class="pr-4" th:text="${item.price * item.quantity}"></td>
        </tr>
        </tbody>
    </table>
    <div class="flex flex-row-reverse p-5">
        <h2 class="font-medium  bg-gray-200 p-2 rounded">
            Grand Total: <span class="text-green-600" th:text="${orderEntry.payment.amount}"></span>
        </h2>
    </div>
    <h2 class="text-xl font-bold">Payment Details</h2>
    <table class="table-fixed text-left w-2/6 border">
        <tr>
            <th class="text-green-600">Card Number</th>
            <td th:text="${orderEntry.payment.cardNumber}"></td>
        </tr>
        <tr>
            <th class="text-green-600">CVV</th>
            <td th:text="${orderEntry.payment.cvv}"></td>
        </tr>
        <tr>
            <th class="text-green-600">Expires (MM/YYYY)</th>
            <td th:text="${orderEntry.payment.month +'/'+ orderEntry.payment.year}"></td>
        </tr>
    </table>
</div>
</body>
</html>

POJO

package com.et.itextpdf.pojo;

import lombok.Data;

@Data
public class Account {
    private String name;
    private String phoneNumber;
    private String email;
    private Address address;


}
package com.et.itextpdf.pojo;

import lombok.Data;

@Data
public class Address {
    private String street;
    private String city;
    private String state;
    private String zipCode;
}
package com.et.itextpdf.pojo;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class Item {
    private String sku;
    private String name;
    private Integer quantity;
    private BigDecimal price;
}
package com.et.itextpdf.pojo;

import lombok.Data;

import java.util.List;

@Data
public class Order {
    private Integer orderId;
    private String date;
    private Account account;
    private Payment payment;
    private List<Item> items;
}
package com.et.itextpdf.pojo;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class Payment {
    private BigDecimal amount;
    private String cardNumber;
    private String cvv;
    private String month;
    private String year;
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • https://github.com/Harries/springboot-demo

3.测试

  • 启动spring boot应用
  • 访问http://127.0.0.1:8088/orders/
  • 访问http://127.0.0.1:8088/orders/pdf,生成pdf并下载

4.引用

  • https://springhow.com/spring-boot-pdf-generation/
  • https://kb.itextpdf.com/itext/ebooks
  • http://www.liuhaihua.cn/archives/710362.html

相关推荐

国产操作系统概念股(国产操作系统概念股票)

  那么怎么构建该系统呢?一般情况下都是从以下几个方面:   第一、选股方法。虽然靠着均线能选股,靠着指标也能选股,但是系统性的选股方法则是要结合宏观经济整体运行位置和环境,行业发展现状和前...

电脑主机开机没反应(电脑主机开机没反应电源灯亮)

操作方法01第一种情况是电脑完全没有反应,那么就可能是电源没有连接上,检查插线板和机箱插头,重新插好就好了。?02还有是电脑机箱已经开启,但是显示屏还是黑的,那么这种情况就有可能是显示屏的电源没有连接...

cad激活码2010(cad激活码和序列号)

1.首先激活码出现问题,需要进行激活确认。首先需要的中进入电脑C盘。2.可以先点击组织设置隐藏文件夹显示。3.勾选显示隐藏文件夹。4.找到C:\ProgramData文件夹,打开找到CAD文件夹。5....

联想windows7笔记本怎么连接网络

检查笔记本的无线网卡驱动1.右键我的电脑,点击“属性”,选择左侧“设备管理器”2.点击“网络适配器”,如果方框内没有驱动,请下载驱动精灵万能网卡版安装网卡驱动 二、若发现驱动前面是感叹号的&...

iphone自动关机设置方法(iphone如何设自动关机)
  • iphone自动关机设置方法(iphone如何设自动关机)
  • iphone自动关机设置方法(iphone如何设自动关机)
  • iphone自动关机设置方法(iphone如何设自动关机)
  • iphone自动关机设置方法(iphone如何设自动关机)
淘宝电脑版网页入口(淘宝网电脑版网页官方)

网站地址:https://www.taobao.com/网站链接:进入网站服务器IP:116.253.191.241网站描述:淘宝网首页,淘宝网-亚洲最大、最安全的网上交易平台,提供各类服饰、美容...

大学生用哪个牌子的笔记本电脑好

荣耀MagicBook14英寸轻薄窄边框笔记本电脑(AMD锐龙58G512GFHDIPS正版Office)冰河银这款的性价比较高。也可以根据自己的预算选同系列其他型号。...

苹果怎么查询手机激活时间(苹果手机如何查询手机激活时间)
  • 苹果怎么查询手机激活时间(苹果手机如何查询手机激活时间)
  • 苹果怎么查询手机激活时间(苹果手机如何查询手机激活时间)
  • 苹果怎么查询手机激活时间(苹果手机如何查询手机激活时间)
  • 苹果怎么查询手机激活时间(苹果手机如何查询手机激活时间)
免费手机模拟器(免费手机模拟器下载)

目前能成功在电脑上模拟苹果系统的iOS模拟器,对比市面上常见的安卓模拟器少太多了,主要原因还是iOS系统比较封闭,难于开发。虽然前面说开发很困难,但是国内还是有一些厉害的IT小组成功推出了iOS模拟器...

免费主题商店app下载(免费主题商店app下载苹果)
  • 免费主题商店app下载(免费主题商店app下载苹果)
  • 免费主题商店app下载(免费主题商店app下载苹果)
  • 免费主题商店app下载(免费主题商店app下载苹果)
  • 免费主题商店app下载(免费主题商店app下载苹果)
新手怎么制作word表格(工作表格制作)

步骤如下:1、本次演示使用的软件为word文字处理软件,软件版本为Microsoftoffice家庭和学生版2016。2、首先打开Excel电子表格,根据问题描述,我们在word中插入两页表格。3、...

电脑开机启动进不了系统怎么办
电脑开机启动进不了系统怎么办

一、修复错误如果频繁无法正常进入系统,则开机后马上按F8,看能否进入安全模式或最后一次配置正确模式,如能则进入后会自动修复注册表,并回忆前几次出现不正常现象时进行了什么操作,并根据怀疑是某个应用软件导致问题产生,将其卸载,然后正常退出,...

2026-01-02 13:05 liuian

win11任务栏隐藏不了(win11任务栏怎么隐藏)

方法/步骤:  1、打开电脑桌面,双击我的计算机。  2、打开控制面板。  3、点击类别切换到大图标或小图标。  4、找到通知区域图标打开。  5、选择显示图标或隐藏图标也可以仅显示通知,选好以后点击...

win10怎么打开系统更新(怎么开启windows10更新)
  • win10怎么打开系统更新(怎么开启windows10更新)
  • win10怎么打开系统更新(怎么开启windows10更新)
  • win10怎么打开系统更新(怎么开启windows10更新)
  • win10怎么打开系统更新(怎么开启windows10更新)
笔记本注册表编辑器怎么打开

你好,要打开注册表编辑器,可以按照以下步骤进行操作:1.打开“运行”对话框。可以通过按下Win+R键组合,或者在开始菜单中搜索“运行”来打开。2.在“运行”对话框中,输入“regedit”并点...