itext5 生成pdf

2023-05-16

最近项目中有需求,需要生成一些打印的pdf数据;经过调研发现使用itext生成的pdf的速度最快。下面讲解一下使用itext5+thymeleaf生成pdf的方法;

首先需要引入itext5相关的包,以及动态生成html的模版引擎thymeleaf

         <!--模版引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--html模版pdf生成-->
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf-itext5</artifactId>
            <version>9.1.5</version>
        </dependency>
        <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>

动态生成html方法如下

 public String generateHtml() {
    List<DataEntity> dataEntities = buildData();
    Map<String, Object> templateValues = ImmutableMap.<String, Object>builder()
        .put("dataList", dataEntities).build();
    Context context = new Context();
    context.setVariables(templateValues);
    String html = templateEngine.process("foobar_pdf.html", context);
    return html;

  }

生成pdf并存储起来

@Autowired
  private SpringTemplateEngine templateEngine;

  public void generatePdf() {
    String html = generateHtml();
    try (OutputStream outputStream = new FileOutputStream(
        "/Users/yangfan/tools/wkhtmltox/9999.pdf")) {

      ITextRenderer renderer = new ITextRenderer();
      ITextFontResolver fontResolver = renderer.getFontResolver();
      fontResolver.addFont("/font/AlibabaPuHuiTi-2-55-Regular.ttf", "AlibabaPuHuiTi-Regular",
          "Identity-H", false, (String) null);
      //html转pdf
      renderer.setDocumentFromString(html);
      renderer.layout();

      renderer.createPDF(outputStream, false);

      renderer.finishPDF();
    } catch (IOException var6) {
      log.error("PdfUtil.generatePdfFromTemplate---生成pdf异常", var6);
    } catch (DocumentException var7) {
      var7.printStackTrace();
    }
  }

在项目的resource目录下新建一个html模板,内容如下

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8"/>
    <title>pdf-100*100</title>
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"/>
    <style type="text/css">

        @page {
            size: 150mm 100mm;
            margin: 0mm;
            padding: 0mm;
        }

        * {
            margin: 0;
            padding: 0;
            font-family: AlibabaPuHuiTi-Regular;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            word-break: break-all;
            border-spacing: 0;
        }

        table td {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }

        .paper {
            padding: 4mm;
            height: 52.01mm;
            width: 92mm;
            overflow: hidden;
            page-break-after: always;
        }

        .content {
            height: 52mm;
            width: 92mm;
            overflow: hidden;
        }

        .head {
            height: 8.5mm;
            width: 100%;
            border-bottom: 0.5mm black solid;
        }

        .summary {
            height: 13mm;
            width: 90mm;
            padding: 1mm;
        }

        .banner {
            height: 4.5mm;
            width: 100%;
            background-color: black;
        }

        .barcode-container {
            height: 16mm;
            width: 86mm;
            padding: 2mm 3mm 0 3mm;
        }

        .footer {
            height: 4.5mm;
            line-height: 4.5mm;
            width: 100%;
            text-align: right;
            font-size: 9px;
        }

        .head .title {
            font-weight: bold;
            font-size: larger;
            height: 8.5mm;
            line-height: 8.5mm;
            text-align: left;
        }

        .head .order-part {
            font-size: medium;
            height: 8.5mm;
            line-height: 8.5mm;
            text-align: right;
        }

        .summary .part-tr {
            height: 6.5mm;
        }

        .summary .part-tr td {
            font-size: 13px;
        }

        .summary .tr-title {
            height: 6.5mm;
            line-height: 6.5mm;
            text-align: left;
        }

        .summary .tr-value {
            height: 6.5mm;
            line-height: 6.5mm;
            text-align: left;
        }

        .banner .banner-left {
            text-align: left;
            width: 60%;
            padding-left: 1mm;
        }

        .banner .banner-right {
            text-align: right;
            padding-right: 1mm;
        }

        .banner td {
            line-height: 4mm;
            color: white;
            font-size: smaller;
        }

        .barcode-container .barcode {
            height: 13mm;
        }

        .barcode-container .qrcode {
            height: 13mm;
            width: 18mm;
            text-align: left;
        }

        .barcode-container .code {
            height: 3mm;
            width: 68mm;
            text-align: center;
            font-size: smaller;
            vertical-align: top;
        }

        .barcode-container .barcode img {
            height: 13mm;
            width: 60mm;
            display: block;
            border: none;
            margin: auto;
        }

        .barcode-container .qrcode img {
            height: 13mm;
            width: 13mm;
            display: block;
            border: none;
        }
    </style>
</head>

<body>
<div class="paper" th:each="data,boxmarkStat:${dataList}">
    <div class="content">
        <div class="head">
            <table>
                <tr>
                    <td class="title">Inbound</td>
                    <td class="order-part" th:text="'Box '+${data.part} +' of '+ ${data.total}">1 of 3</td>
                </tr>
            </table>
        </div>
        <div class="summary">
            <div class="part-tr">
                <table>
                    <tr>
                        <td width="24%" class="tr-title">Warehouse:</td>
                        <td width="50%" class="tr-value">
                            <div class="tr-value" style="display: inline-block;max-width: 18mm;overflow: hidden" th:text="${data.stockName}"></div>
                            <div class="tr-value" style="display: inline-block;max-width: 36mm;overflow: hidden" th:text="${data.stockCode}"></div>
                        </td>
                        <td width="12%" class="tr-title">SKUs:</td>
                        <td class="tr-value" th:text="${data.sku}">3</td>
                    </tr>
                </table>
            </div>
            <div class="part-tr">
                <table>
                    <tr>
                        <td width="14%" class="tr-title">Client:</td>
                        <td width="60%" class="tr-value" th:text="${data.client}">Xiaomi (1001001)</td>
                        <td width="12%" class="tr-title">PCS:</td>
                        <td class="tr-value" th:text="${data.totalNum}">400</td>
                    </tr>
                </table>
            </div>
        </div>
        <div class="banner">
            <table>
                <tr>
                    <td class="banner-left" th:text="${data.billNo}">IB46178321OBA</td>
                    <td class="banner-right" th:text="${data.createTime}">2021-09-26 16:01</td>
                </tr>
            </table>
        </div>
        <div class="barcode-container">
            <table>
                <tr>
                    <td class="barcode"><img th:src="${data.barcode}"/></td>
                    <td class="qrcode"><img th:src="${data.qrcode}"/></td>
                </tr>
                <tr>
                    <td class="code" th:text="${data.serialNum}">IB46178321OBA</td>
                </tr>
            </table>
        </div>
        <div class="footer" th:text="${data.madeInChina}?'MADE IN CHINA':''">MADE IN CHINA</div>
    </div>
</div>
</body>

</html>

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

itext5 生成pdf 的相关文章

  • 将超链接添加到 PDF 文档中

    我目前正在扩展我们的自定义 PDF 编写器 以便能够编写网站链接 但是 我遇到了一个问题 因为我无法找到如何将链接放入 PDF 的任何地方 这是打印文本的内容 BT 70 50 TD F1 12 Tf visit my website Tj
  • 在 Android 中使用 PhoneGap 打开 PDF

    我需要打开一个位于 url 中的 PDF 文件 我需要用 PDF 查看器打开它 有可能的 谢谢大家 此致 我建议使用儿童浏览器插件 https build phonegap com blog childbrowser plugin并使用 G
  • 禁用右键单击嵌入元素内的 pdf

    我有一个embed我在其中提供路径的元素pdf文件 我想阻止它被下载 但是当我右键单击该 t 时 我会看到保存和打印 pdf 的选项 我想阻止这些选项 I tried 但它禁用除 PDF 之外的整个页面上的右键单击 一种不受 CORS 或
  • 使用 iText 和 Batik 生成 PDF

    我正在尝试将文本和 SVG 图形导出为 PDF 我发现 iText 和 batik 可以做到这一点 所以我尝试这样做 但每次我放入图表时 它都会变得非常小 我认为这可能与我的代码有关 所以我想我应该尝试 Vaadin 的示例代码 publi
  • 以编程方式更改 PDF 文件中黑框的颜色?

    我有一个由 Microsoft Word 生成的 PDF 文件 用户指定了黑色的 突出显示 颜色 使文本看起来像一个黑框 并使文本看起来像是经过编辑的 我想将黑框更改为黄色 以便突出显示文本 理想情况下 我想用 Python 来完成此操作
  • 查看pdf字节流而不将其保存在Android中

    Ref 如何在 Android 中渲染 PDF https stackoverflow com questions 2883355 how to render pdf in android 我有一个包含 PDF 内容的字节流 并希望在我的
  • 使用 javascript 在 IFrame 中打印 PDF 文件仅获取一页

    这是我打印 pdf 文件的代码 在这里 在打印时我只得到一页 我需要一个解决方案 function printPdf var ifr document getElementById frame1 PDF is completely load
  • Python - 将 XLSX 转换为 PDF

    我一直用win32com我的开发服务器中的模块可以轻松转换xlsx to pdf o win32com client Dispatch Excel Application o Visible False o DisplayAlerts Fa
  • R 在设置宽度和高度的 PDF 中缩放绘图元素

    尽管发送到 PDF 的 R 图可以在插图或页面布局软件中随意重新缩放 但科学期刊通常坚持提供的图具有特定的尺寸 是否可以直接在 R 中在给定 PDF 大小内缩放所有绘图元素的大小 require ggplot2 p lt qplot dat
  • 如何直观地检查 PDF 的结构以对其进行逆向工程? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 如何检查 PDF 文件的结构 用例 我正在尝试以编程方式生成 PDF 文件 使用 iText 我在实现
  • 合并两个 Jasper 报告

    我有一个带有下拉菜单的网络应用程序 用户可以从中选择报告可视化的类型 报告 1 报告 2 报告 3 等 根据所选的报告 Jasper 报告将在服务器上编译并以 PDF 格式的弹出窗口打开 在服务器端 我使用下面的代码以单独的方法实现每个报告
  • 如何将 pdf 文档显示到 Webview 中?

    我想在 webview 上显示 pdf 内容 这是我的代码 WebView webview new WebView this setContentView webview webview getSettings setJavaScriptE
  • 使用 ApacheFOP 从 Java 中的 XML 生成 PDF

    我正在尝试从 Java 对象生成即时 PDF 报告 我找不到很多这方面的例子 所以我一直在关注这个例子 http svn apache org viewvc xmlgraphics fop trunk examples embedding
  • 隐藏嵌入的 pdf 周围的工具栏?

    虽然我认为答案可能在这另一个问题 https stackoverflow com questions 770949 how to disable the default toolbar of pdf page关于pdf规范的回答 是否可以不
  • 从图像创建 PDF 时设置文档名称

    我使用以下代码从 jpg 图像创建 pdf im new Imagick im gt readImage image jpg im gt setImageFormat pdf im gt writeImage images pdf imag
  • 在 Swift 中从 UIScrollView 创建 PDF 文件

    我想从 UIScrollView 的内容创建一个 PDF 文件 func createPdfFromView aView UIView saveToDocumentsWithFileName fileName String let pdfD
  • 将 SignedHash 插入 PDF 中以进行外部签名过程 -workingSample

    遵循电子书第 4 3 3 节 PDF 文档的数字签名 https jira nuxeo com secure attachment 49931 digitalsignatures20130304 pdf 我正在尝试创建一个工作示例 其中 客
  • 使用 PHP/linux 将文件合并为单个 PDF

    我正在研究如何将多个 PDF 合并为一个 PDF 我正在寻找一个图书馆可靠且坚固尽可能 最好有一个库可以保留书签 鬼脚本 http pages cs wisc edu ghost 可以在保存书签的位置进行连接 但我遇到了麻烦 在一种情况下它
  • 使用 Django 从标准输出返回 pdf 响应

    我正在使用 wkhtmltopdf 创建 PDF 文件 但是我不知道如何正确返回它们 所以我必须将它们写入我的媒体文件夹 然后重定向到刚刚创建的文件 编辑 Ian 的建议是写入 STDOUT 因此我更改了 wkhtmltopdf 命令来执行
  • 使用 PDFBox 在 PDF 上绘制矢量图像

    我想使用 Apache PDFBox 在 PDF 上绘制矢量图像 这是我用来绘制常规图像的代码 PDPage page PDPage document getDocumentCatalog getAllPages get 1 PDPageC

随机推荐

  • Zynq-7000系列之linux开发学习笔记:PS和PL端的GPIO使用(三)

    开发板 xff1a Zynq7030数据采集板 PC平台 xff1a Ubuntu 18 04 43 MobaXterm 开发环境 xff1a Xilinx Vivado 43 SDK 18 3 学习目标 xff1a PS通过 EMIO A
  • 人工智能革命(上):通往超级智能之路

    导读 xff1a 本系列文章讲述了人工智能革命的爆发以及人类未来的出路 xff0c 由于篇幅较长分为上下两篇 xff0c 原英文载于神奇的网站 WaitButWhy com xff0c 作者Tim Urban还写过一篇有关脑机接口的文章 N
  • kubelet源码分析

    做个笔记记录k8s中赫赫有名的LIST amp WATCH 其实之前的文章中都有过watch的身影了 分别是informer篇和configCh篇这两篇其实都共用了client go包中的LIST amp WATCH方法 这篇内容详细讲一下
  • Li‘s 核磁共振影像数据处理-20-FSL数学工具fslmaths

    讲解视频内容请移步Bilibili xff1a https space bilibili com 542601735 入群讨论请加v hochzeitstorte 请注明 核磁共振学习 公众号 xff1a 美好事物中转站 FSLeyes F
  • CentOS7 防火墙(firewalld、iptables)-端口相关问题

    firewalld Centos7默认安装了firewalld xff0c 如果没有安装的话 xff0c 可以使用 yum install firewalld firewalld config进行安装 1 启动防火墙 systemctl s
  • centos 7.5 安装桌面环境及报错

    一 查看运行级别 xff0c 输入命令 xff1a runlevel 二 查看centos7 5系统中没有是否安装过桌面环境工具 xff0c 输入命令 xff1a yum grouplist more 注 xff1a 此命令还显示了系统安装
  • Seata(一) 服务配置以及启动

    文章目录 Seata 介绍Seata 简介Seata 演进历史Seata 设计理念Seata 的三大组件seata 实现的 2PC 与传统 2PC 的区别 Seata Server 安装Seata Server 下载Seata Server
  • 新手入门:PyCharm 的使用

    初次接触 pycharm 不要怕 xff0c 这篇文章帮你快速入门 xff0c 点击收藏不迷路 相关文章 xff1a Windows 10 同时安装 Python 2 和 Python 3 推荐一个视频 xff1a pycharm使用教程
  • EntityFrameworkCore 运行时数据迁移

    EntityFrameworkCore 以后简称EFCore 是 net core的一个orm框架 xff0c 以前在 net framework中使用时候利用code first可以在程序运行的时候自动迁移数据库 xff0c 更新数据库表
  • query.unwrap(SQLQuery.class).setResultTransformer弃用

    替换为 query unwrap span class token punctuation span NativeQueryImpl class span class token punctuation span setResultTran
  • pyinstaller报错AttributeError: type object ‘Callable‘ has no attribute ‘_abc_registry‘

    遇到问题 xff1a pyinstaller 打包文件时失败 xff0c 报错 xff1a AttributeError type object Callable has no attribute abc registry 解决方法 xff
  • Mysql数据库完全备份与恢复

    一 数据备份的重要性 在生产环境中 xff0c 数据的安全性是至关重要的 xff0c 任何数据的丢失都可能产生严重的后果 造成数据丢失的原因如下 程序错误人为错误计算机失败磁盘失败灾难 如火灾 地震 和盗窃 二 数据库备份的分类 1 从物理
  • [sourcetree] rebase的使用

    相关问题 最近写自己的辣鸡代码使用git时 xff0c 因为个人不大熟悉git又是个强迫症 xff0c 被来回不同的版本折腾来折腾去的 xff0c 十分不爽 xff0c 于是在此小结下sourcetree怎么使用变基 变基rebase这个操
  • mac下word有何无格式粘贴快捷键设置为默认方法

    补充说明 xff1a 后来使用发现可能是默认的快捷键 xff1a Command 43 V 粘贴无格式文本 xff1b control 43 V 粘贴格式文本 mac word 16 3之前的版本 xff0c 粘贴有Bug xff0c 只能
  • JVM内存管理

    一 物理内存与虚拟内存 xff1a 1 物理内存即RAM 随机存储器 2 寄存器 xff0c 用于存储计算单元指令 xff08 如浮点 xff0c 整数等运算 xff09 3 地址总线 xff1a 连接处理器和RAM 4 虚拟内存使得多个进
  • mongo

    mongo分页操作 与mysql数据库不同 xff0c mongo数据库是一种NoSQL数据库 xff0c 它的存储方式是以文档的形式进行存储的 本文主要记录了在开发过程中遇到的索引问题及数据库分页查询问题 常见的分页查询方式 1 使用li
  • RocketMQ本地环境搭建

    官网下载源码 建议到官网去下载 xff0c 本文使用的rocket的版本是基于4 7 1 xff0c 点击这里开始下载 导入idea rocketMQ是以maven的形式进行构建的 xff0c 因此直接使用ideaopen打开即可 xff0
  • 分布式事务-seata

    记录基于seata官网本地搭建seata的过程 下载seata软件报 Releases seata seata GitHub 将其解压缩 启动seata服务 sh seata server sh p 8091 h 127 0 0 1 m f
  • WKHtmltoPdf

    踩过的坑 请一定要使用下面的这种方式获取系统的可执行命令 xff0c 否则会报一堆的找不到目录等错误 xff01 xff01 xff01 String osname 61 System getProperty 34 os name 34 t
  • itext5 生成pdf

    最近项目中有需求 xff0c 需要生成一些打印的pdf数据 xff1b 经过调研发现使用itext生成的pdf的速度最快 下面讲解一下使用itext5 43 thymeleaf生成pdf的方法 xff1b 首先需要引入itext5相关的包