当前位置: 首页 > 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://www.lryc.cn/news/588684.html

相关文章:

  • 【开源】一款基于 .NET 和 Vue3 开源(Apache)的MES管理系统,您的新一代工厂管理助手!
  • 【雅思播客016】New Year Resolution 新年决心
  • Luban配置教程
  • CSS :root伪类详解:实现动态主题切换的关键所在
  • 从浏览器到服务器:TCP 段的网络传输之旅
  • 建筑兔零基础人工智能自学记录109|LangChain简单翻译应用-19
  • Linux 基础 IO
  • 手机当路由,连接机器人和电脑
  • Java实现word、pdf转html保留格式
  • JavaScript与Vue:现代前端开发的完美组合
  • Spark Expression codegen
  • Swift实现股票图:从基础到高级
  • 线程(一) linux
  • 使用Dify+fastmcp 实现mcp服务,内含详细步骤与源码
  • Mac IDEA启动报错:Error occurred during initialization of VM
  • Twisted study notes[1]
  • [附源码+数据库+毕业论文+开题报告]基于Spring+MyBatis+MySQL+Maven+jsp实现的车辆运输管理系统,推荐!
  • etcd自动压缩清理
  • easy-ui中的相对路径和绝对路径问题
  • 现代CSS实战:用变量与嵌套重构可维护的前端样式
  • 【GPIO】从STM32F103入门GPIO寄存器
  • 腿姐政治笔记唯物辩证法(2)(12356)
  • 面试遇到的问题
  • 使用JS编写用户信息采集表单
  • 利用android studio,对图片资源进行二次压缩
  • 网络编程-epoll模型/udp通信
  • Node.js 中http 和 http/2 是两个不同模块对比
  • AutoGPT vs BabyAGI:自主任务执行框架对比与选型深度分析
  • python的形成性考核管理系统
  • 1.easypan-登录注册