Java 实现:在 Word 模板指定位置贴二维码并生成 PDF 电子凭据文档 ...

梦应逍遥  金牌会员 | 2025-2-13 00:22:40 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 574|帖子 574|积分 1722

在现实业务场景中,我们常常必要在 Word 模板的指定位置贴上二维码,然后将其转换为 PDF 电子凭据文档。下面将详细先容如何使用 Java 完成这一任务,我们会借助 Apache POI 处置惩罚 Word 文档,ZXing 生成二维码,以及 Docx4J 将 Word 文档转换为 PDF。

1. 引入依赖

如果你使用 Maven 管理项目,在 pom.xml 中添加以下依赖:
  1. [/code] [code]<dependencies>
  2.     <!-- Apache POI 处理 Word 文档 -->
  3.     <dependency>
  4.         <groupId>org.apache.poi</groupId>
  5.         <artifactId>poi-ooxml</artifactId>
  6.         <version>5.2.3</version>
  7.     </dependency>
  8.     <!-- ZXing 生成二维码 -->
  9.     <dependency>
  10.         <groupId>com.google.zxing</groupId>
  11.         <artifactId>core</artifactId>
  12.         <version>3.4.1</version>
  13.     </dependency>
  14.     <dependency>
  15.         <groupId>com.google.zxing</groupId>
  16.         <artifactId>javase</artifactId>
  17.         <version>3.4.1</version>
  18.     </dependency>
  19.     <!-- Docx4J 将 Word 转换为 PDF -->
  20.     <dependency>
  21.         <groupId>org.docx4j</groupId>
  22.         <artifactId>docx4j-JAXB-Internal</artifactId>
  23.         <version>11.4.9</version>
  24.     </dependency>
  25.     <dependency>
  26.         <groupId>org.docx4j</groupId>
  27.         <artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
  28.         <version>11.4.9</version>
  29.     </dependency>
  30.     <dependency>
  31.         <groupId>org.docx4j</groupId>
  32.         <artifactId>docx4j</artifactId>
  33.         <version>11.4.9</version>
  34.     </dependency>
  35.     <dependency>
  36.         <groupId>org.docx4j</groupId>
  37.         <artifactId>docx4j-export-fo</artifactId>
  38.         <version>11.4.9</version>
  39.     </dependency>
  40. </dependencies>
复制代码


2. 生成二维码

使用 ZXing 库生成二维码的代码如下:
  1. [/code] [code]import com.google.zxing.BarcodeFormat;
  2. import com.google.zxing.EncodeHintType;
  3. import com.google.zxing.WriterException;
  4. import com.google.zxing.client.j2se.MatrixToImageWriter;
  5. import com.google.zxing.common.BitMatrix;
  6. import com.google.zxing.qrcode.QRCodeWriter;
  7. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  8. import java.awt.image.BufferedImage;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. public class QRCodeGenerator {
  12.     public static BufferedImage generateQRCode(String text, int width, int height) throws WriterException {
  13.         QRCodeWriter qrCodeWriter = new QRCodeWriter();
  14.         Map<EncodeHintType, Object> hints = new HashMap<>();
  15.         hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
  16.         hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
  17.         BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
  18.         return MatrixToImageWriter.toBufferedImage(bitMatrix);
  19.     }
  20. }
复制代码


3. 在 Word 模板指定位置插入二维码

使用 Apache POI 在 Word 模板的指定位置插入二维码,这里假设模板中使用特定占位符来标志二维码的插入位置。
  1. [/code] [code]import org.apache.poi.xwpf.usermodel.*;
  2. import javax.imageio.ImageIO;
  3. import java.awt.image.BufferedImage;
  4. import java.io.*;
  5. public class WordQRCodeInserter {
  6.     public static void insertQRCodeIntoWord(String templatePath, String outputPath, BufferedImage qrCodeImage, String placeholder) throws IOException {
  7.         try (FileInputStream fis = new FileInputStream(templatePath);
  8.              XWPFDocument document = new XWPFDocument(fis)) {
  9.             for (XWPFParagraph paragraph : document.getParagraphs()) {
  10.                 for (XWPFRun run : paragraph.getRuns()) {
  11.                     String text = run.getText(0);
  12.                     if (text != null && text.contains(placeholder)) {
  13.                         // 清除占位符文本
  14.                         run.setText("", 0);
  15.                         // 插入二维码图片
  16.                         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  17.                         ImageIO.write(qrCodeImage, "png", byteArrayOutputStream);
  18.                         byte[] imageBytes = byteArrayOutputStream.toByteArray();
  19.                         int pictureType = XWPFDocument.PICTURE_TYPE_PNG;
  20.                         int width = qrCodeImage.getWidth();
  21.                         int height = qrCodeImage.getHeight();
  22.                         paragraph.createRun().addPicture(new ByteArrayInputStream(imageBytes), pictureType, "qrcode.png", width * 20, height * 20);
  23.                     }
  24.                 }
  25.             }
  26.             try (FileOutputStream fos = new FileOutputStream(outputPath)) {
  27.                 document.write(fos);
  28.             }
  29.         }
  30.     }
  31. }
复制代码


4. 将 Word 文档转换为 PDF

使用 Docx4J 将插入二维码后的 Word 文档转换为 PDF。
  1. [/code] [code]import org.docx4j.Docx4J;
  2. import org.docx4j.convert.out.FOSettings;
  3. import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
  4. import java.io.*;
  5. public class WordToPdfConverter {
  6.     public static void convertWordToPdf(String wordPath, String pdfPath) throws Exception {
  7.         WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(wordPath));
  8.         FOSettings foSettings = Docx4J.createFOSettings();
  9.         foSettings.setWmlPackage(wordMLPackage);
  10.         try (OutputStream os = new FileOutputStream(pdfPath)) {
  11.             Docx4J.toPDF(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
  12.         }
  13.     }
  14. }
复制代码


5. 主程序调用示例

  1. [/code] [code]import java.io.IOException;
  2. import com.google.zxing.WriterException;
  3. public class Main {
  4.     public static void main(String[] args) {
  5.         try {
  6.             // 要生成二维码的内容
  7.             String qrCodeContent = "https://www.example.com";
  8.             // 生成二维码图片
  9.             BufferedImage qrCodeImage = QRCodeGenerator.generateQRCode(qrCodeContent, 200, 200);
  10.             // Word 模板文件路径
  11.             String templatePath = "path/to/your/template.docx";
  12.             // 插入二维码后的 Word 文件输出路径
  13.             String wordOutputPath = "path/to/your/output.docx";
  14.             // 最终生成的 PDF 文件输出路径
  15.             String pdfOutputPath = "path/to/your/output.pdf";
  16.             // Word 模板中的二维码占位符
  17.             String placeholder = "{QR_CODE}";
  18.             // 在 Word 模板中插入二维码
  19.             WordQRCodeInserter.insertQRCodeIntoWord(templatePath, wordOutputPath, qrCodeImage, placeholder);
  20.             // 将插入二维码后的 Word 文档转换为 PDF
  21.             WordToPdfConverter.convertWordToPdf(wordOutputPath, pdfOutputPath);
  22.             System.out.println("PDF 电子凭证文档生成成功!");
  23.         } catch (WriterException | IOException | Exception e) {
  24.             e.printStackTrace();
  25.         }
  26.     }
  27. }
复制代码


6. 代码表明

生成二维码

QRCodeGenerator 类使用 ZXing 库根据指定的文本内容生成二维码的 BufferedImage 对象。

在 Word 模板插入二维码

WordQRCodeInserter 类遍历 Word 文档的段落和运行对象,查找包含占位符的文本,清除占位符文本后插入二维码图片。

Word 转 PDF

WordToPdfConverter 类使用 Docx4J 将插入二维码后的 Word 文档转换为 PDF 文件。

主程序调用

在 Main 类的 main 方法中,依次调用生成二维码、在 Word 模板插入二维码、将 Word 转换为 PDF 的方法,最终生成 PDF 电子凭据文档。

7. 留意事项



  • 确保 Word 模板文件和输出文件的路径精确,并且程序有读写权限。
  • 可以根据必要调整二维码的巨细和占位符的内容。
  • 处置惩罚中文等非 ASCII 字符时,要确保字符编码设置精确。

通过以上步骤,你就可以使用 Java 在 Word 模板指定位置贴上二维码,并将其生成为 PDF 电子凭据文档啦!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

梦应逍遥

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表