当前位置: 首页 > news >正文

Java使用itextpdf7生成pdf文档

使用itextpdf7生成pdf文档,首先需要导入itextpdf7相关依赖:

<dependency><groupId>com.itextpdf</groupId><artifactId>kernel</artifactId><version>7.1.16</version>
</dependency>
<dependency><groupId>com.itextpdf</groupId><artifactId>io</artifactId><version>7.1.16</version>
</dependency>
<dependency><groupId>com.itextpdf</groupId><artifactId>layout</artifactId><version>7.1.16</version>
</dependency>

由于我们要在pdf文档中写入中文内容,因此,务必引入字体文件。本文都以宋体(simsun.ttf)为例,字体文件可在系统目录 C:\Windows\Fonts 中找到,或自行百度在免费字体网下载。
亲测:如果文档中写入纯英文内容,可以不引入字体文件,如果需要写入中文内容,务必引入字体文件。

在项目的根目录创建fonts目录,并将字体文件拷贝至该目录中。目录可根据自己的需要定义。

在这里插入图片描述

编写方法, 返回字体文件所在位置

/*** 返回字体文件所在位置* * @return*/
private String getFontPath() {// 获取当前工作目录String projectRoot = System.getProperty("user.dir");String fontPath = projectRoot + "/fonts/simsun.ttf";return fontPath;
}

案例一:生成带有段落的PDF文件

/*** 生成带有段落的pdf文件*/
public void generatePDFWithPara() {Document document = null;String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";String filePath = "D:/" + fileName;try {File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}PdfWriter writer = new PdfWriter(filePath);PdfDocument pdfDoc = new PdfDocument(writer);// 设置纸张大小pdfDoc.setDefaultPageSize(PageSize.A4);document = new Document(pdfDoc);// 加载中文字体(确保字体文件存在)String fontPath = getFontPath();PdfFont font = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);Paragraph paragraph = new Paragraph("这是一首简单的小情歌");paragraph.setFontSize(16f); // 字体大小paragraph.setFont(font);  // 字体类型document.add(paragraph);System.out.println("内容已写入文件:" + filePath);} catch (IOException e) {e.printStackTrace();throw new RuntimeException("生成PDF失败");} finally {if (document != null) {document.close();}}
}

案例二:生成带有表格的PDF文件

/*** 生成带有表格的pdf文件*/
public void generatePDFWithTable() {Document document = null;String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";String filePath = "D:/" + fileName;try {File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}PdfWriter writer = new PdfWriter(filePath);PdfDocument pdfDoc = new PdfDocument(writer);// 设置纸张大小pdfDoc.setDefaultPageSize(PageSize.A4);document = new Document(pdfDoc);// 加载中文字体(确保字体文件存在)String fontPath = getFontPath();PdfFont font = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);String[] ids = {"1001", "1002", "1003"};String[] names = {"张三", "李四", "王五"};String[] ages = {"18", "19", "20"};// 创建表格,3列Table table = new Table(UnitValue.createPercentArray(new float[]{2, 2, 2})).useAllAvailableWidth();table.setBorder(new SolidBorder(ColorConstants.BLACK, 2)); // 设置边框// 第一列 学号Cell cell1 = new Cell();cell1.setFont(font);for (String text : ids) {cell1.add(new Paragraph(text));}table.addCell(cell1);// 第二列 姓名Cell cell2 = new Cell();cell2.setFont(font);for (String text : names) {cell2.add(new Paragraph(text));}table.addCell(cell2);// 第三列 年龄Cell cell3 = new Cell();cell3.setFont(font);for (String text : ages) {cell3.add(new Paragraph(text));}table.addCell(cell3);document.add(table);System.out.println("内容已写入文件:" + filePath);} catch (IOException e) {e.printStackTrace();throw new RuntimeException("生成PDF失败");} finally {if (document != null) {document.close();}}
}

案例三:生成带有图片的PDF文件

/*** 生成带有图片的pdf文件*/
public void generatePDFWithImage() {Document document = null;String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";String filePath = "D:/" + fileName;try {File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}PdfWriter writer = new PdfWriter(filePath);PdfDocument pdfDoc = new PdfDocument(writer);// 设置纸张大小pdfDoc.setDefaultPageSize(PageSize.A4);document = new Document(pdfDoc);// 图片路径,确保真实存在String imagePath = "D:/flower.png";ImageData imageData = ImageDataFactory.create(imagePath);document.add(new Image(imageData));System.out.println("内容已写入文件:" + filePath);} catch (IOException e) {e.printStackTrace();throw new RuntimeException("生成PDF失败");} finally {if (document != null) {document.close();}}
}

案例四:生成带有二维码的PDF文件

该功能,需要引入第三方依赖,生成二维码,以Google官方提供的zxing为例。

<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.3</version>
</dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.3.3</version>
</dependency>

在工具类QrCodeUtils中,编写生成二维码的方法:

/*** 生成二维码** @param content* @return* @throws WriterException* @throws IOException*/
public static Image generateQRCode(String content) throws WriterException, IOException {int width = 200;int height = 200;String format = "png";Map<EncodeHintType, Object> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);ByteArrayOutputStream baos = new ByteArrayOutputStream();MatrixToImageWriter.writeToStream(bitMatrix, format, baos);// Convert QR code to iText image and add it to the PDFImage img = new Image(ImageDataFactory.create(baos.toByteArray()));img.setMarginTop(0F);img.setMarginRight(0F);return img;
}

生成带有二维码的PDF文件:

/*** 生成带有二维码的pdf文件*/
public void generatePDFWithQrcode() {Document document = null;String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";String filePath = "D:/" + fileName;try {File file = new File(filePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}PdfWriter writer = new PdfWriter(filePath);PdfDocument pdfDoc = new PdfDocument(writer);// 设置纸张大小pdfDoc.setDefaultPageSize(PageSize.A4);document = new Document(pdfDoc);// 二维码的内容,或url路径String urlContent = "https://blog.csdn.net/qq_35148205?spm=1000.2115.3001.10640";// 生成二维码Image image = QrCodeUtils.generateQRCode(urlContent);document.add(image);System.out.println("内容已写入文件:" + filePath);} catch (IOException | WriterException e) {e.printStackTrace();throw new RuntimeException("生成PDF失败");} finally {if (document != null) {document.close();}}
}

使用Java生成PDF文件的功能,在某些业务场景中经常会被使用。例如,MES系统的生产订单功能中,通常需要将带有标题、文本、表格、二维码的生产指示单,生成PDF文件,保存在服务器或OSS的某个路径下,前端通过访问该路径,预览并打印该PDF文件。开发人员可根据实际的业务需求,从数据库中查询对应的数据,根据指定的格式和排版,插入到需要生成的PDF文档中。


文章转载自:
http://antichloristic.wjrtg.cn
http://carbonylic.wjrtg.cn
http://burgher.wjrtg.cn
http://afforestation.wjrtg.cn
http://ambulacrum.wjrtg.cn
http://bata.wjrtg.cn
http://calamographer.wjrtg.cn
http://blutwurst.wjrtg.cn
http://basely.wjrtg.cn
http://asahigawa.wjrtg.cn
http://accompanier.wjrtg.cn
http://bekaa.wjrtg.cn
http://cabochon.wjrtg.cn
http://childminder.wjrtg.cn
http://camise.wjrtg.cn
http://affectionateness.wjrtg.cn
http://acgb.wjrtg.cn
http://acth.wjrtg.cn
http://byland.wjrtg.cn
http://balefire.wjrtg.cn
http://assiduous.wjrtg.cn
http://buoy.wjrtg.cn
http://bibliograph.wjrtg.cn
http://catlick.wjrtg.cn
http://bookstore.wjrtg.cn
http://choreograph.wjrtg.cn
http://chained.wjrtg.cn
http://allochthon.wjrtg.cn
http://cambria.wjrtg.cn
http://andesite.wjrtg.cn
http://www.dtcms.com/a/281554.html

相关文章:

  • GAMES101 lec1-计算机图形学概述
  • 前端-CSS-day4
  • 边缘计算中模型精度与推理速度的平衡策略及硬件选型
  • 实战长尾关键词SEO优化指南提升排名
  • Go语言调度器深度解析:sysmon的核心作用与实现原理
  • Web3.0 学习方案
  • ROS第十五梯:launch进阶用法——conda自启动和多终端多节点运行
  • Axios 和Express 区别对比
  • 前端打包自动压缩为zip--archiver
  • Bp神经网络公式导出方法
  • 【SpringBoot】实战-开发模式及环境搭建
  • 学习嵌入式的第二十八天-数据结构-(2025.7.15)进程和线程
  • For and While Loop
  • javaScript 基础知识(解决80%js面试问题)
  • 代码随想录算法训练营十六天|二叉树part06
  • 配置nodejs,若依
  • 【08】MFC入门到精通——MFC模态对话框 和 非模态对话框 解析 及 实例演示
  • Git未检测到文件更改
  • 密码协议的基本概念
  • bytetrack漏检补齐
  • Nginx配置反向代理
  • 【世纪龙科技】智能网联汽车环境感知系统教学软件
  • C# StringBuilder源码分析
  • Java大厂面试实录:从Spring Boot到AI微服务架构的层层递进
  • 华为OD 特异双端队列
  • 魔搭官方教程【快速开始】-swift 微调报错:`if v not in ALL_PARALLEL_STYLES`
  • [数据结构]#3 循环链表/双向链表
  • Spring AI Alibaba 1.0 vs Spring AI 深度对比
  • 信息学奥赛一本通 1552:【例 1】点的距离
  • 记一次POST请求中URL中文参数乱码问题的解决方案