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文档中。