SoFunction
Updated on 2025-04-14

Java implements adding QR codes to the specified location of Word template and generating PDF

In actual business scenarios, we often need to paste QR codes at the specified location of the Word template and convert them into PDF electronic credentials documents. Below we will introduce in detail how to accomplish this task using Java. We will use Apache POI to process Word documents, generate QR codes by ZXing, and convert Word documents into PDFs by Docx4J.

1. Introduce dependencies

If you use Maven to manage your project, add the following dependencies in :

<dependencies>
    <!-- Apache POI deal with Word document -->
    <dependency>
        <groupId></groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>
    <!-- ZXing Generate QR code -->
    <dependency>
        <groupId></groupId>
        <artifactId>core</artifactId>
        <version>3.4.1</version>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>javase</artifactId>
        <version>3.4.1</version>
    </dependency>
    <!-- Docx4J Will Word Convert to PDF -->
    <dependency>
        <groupId>org.docx4j</groupId>
        <artifactId>docx4j-JAXB-Internal</artifactId>
        <version>11.4.9</version>
    </dependency>
    <dependency>
        <groupId>org.docx4j</groupId>
        <artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
        <version>11.4.9</version>
    </dependency>
    <dependency>
        <groupId>org.docx4j</groupId>
        <artifactId>docx4j</artifactId>
        <version>11.4.9</version>
    </dependency>
    <dependency>
        <groupId>org.docx4j</groupId>
        <artifactId>docx4j-export-fo</artifactId>
        <version>11.4.9</version>
    </dependency>
</dependencies>

2. Generate QR code

The code for using the ZXing library to generate QR code is as follows:

import ;
import ;
import ;
import .;
import ;
import ;
import ;
 
import ;
import ;
import ;
 
public class QRCodeGenerator {
    public static BufferedImage generateQRCode(String text, int width, int height) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        (EncodeHintType.ERROR_CORRECTION, );
        (EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = (text, BarcodeFormat.QR_CODE, width, height, hints);
        return (bitMatrix);
    }
}

3. Insert QR code in the specified location of the Word template

Use Apache POI to insert QR codes at the specified location of the Word template, assuming that a specific placeholder is used in the template to mark the insertion position of the QR code.

import .*;
import ;
import ;
import .*;
 
public class WordQRCodeInserter {
    public static void insertQRCodeIntoWord(String templatePath, String outputPath, BufferedImage qrCodeImage, String placeholder) throws IOException {
        try (FileInputStream fis = new FileInputStream(templatePath);
             XWPFDocument document = new XWPFDocument(fis)) {
            for (XWPFParagraph paragraph : ()) {
                for (XWPFRun run : ()) {
                    String text = (0);
                    if (text != null &amp;&amp; (placeholder)) {
                        // Clear the placeholder text                        ("", 0);
                        // Insert QR code picture                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        (qrCodeImage, "png", byteArrayOutputStream);
                        byte[] imageBytes = ();
                        int pictureType = XWPFDocument.PICTURE_TYPE_PNG;
                        int width = ();
                        int height = ();
                        ().addPicture(new ByteArrayInputStream(imageBytes), pictureType, "", width * 20, height * 20);
                    }
                }
            }
            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                (fos);
            }
        }
    }
}

4. Convert Word documents to PDF

Use Docx4J to convert Word documents inserted into PDF.

import org.docx4j.Docx4J;
import org.;
import org.;
 
import .*;
 
public class WordToPdfConverter {
    public static void convertWordToPdf(String wordPath, String pdfPath) throws Exception {
        WordprocessingMLPackage wordMLPackage = (new File(wordPath));
        FOSettings foSettings = ();
        (wordMLPackage);
        try (OutputStream os = new FileOutputStream(pdfPath)) {
            (foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
        }
    }
}

5. Main program call example

import ;
 
import ;
 
public class Main {
    public static void main(String[] args) {
        try {
            // Contents to generate QR code            String qrCodeContent = "";
            // Generate QR code pictures            BufferedImage qrCodeImage = (qrCodeContent, 200, 200);
 
            // Word template file path            String templatePath = "path/to/your/";
            // Word file output path after inserting QR code            String wordOutputPath = "path/to/your/";
            // The final generated PDF file output path            String pdfOutputPath = "path/to/your/";
            // QR code placeholder in Word template            String placeholder = "{QR_CODE}";
 
            // Insert QR code in Word template            (templatePath, wordOutputPath, qrCodeImage, placeholder);
 
            // Convert Word documents inserted into QR code to PDF            (wordOutputPath, pdfOutputPath);
 
            ("PDF electronic voucher document was generated successfully!");
        } catch (WriterException | IOException | Exception e) {
            ();
        }
    }
}

6. Code explanation

1. Generate QR code

The QRCodeGenerator class uses the ZXing library to generate a BufferedImage object of the QR code based on the specified text content.

2. Insert QR code in Word template

The WordQRCodeInserter class traverses the paragraphs and run objects of the Word document, finds text containing placeholders, clears the placeholder text and inserts the QR code picture.

Convert PDF

The WordToPdfConverter class uses Docx4J to convert Word documents inserted into PDF files after QR codes.

4. Main program call

In the main method of the Main class, the method of generating a QR code, inserting a QR code in the Word template, and converting Word into PDF is called in sequence, and finally the PDF electronic credential document is generated.

7. Things to note

Make sure that the paths of the Word template file and the output file are correct and that the program has read and write permissions.

The size of the QR code and the content of the placeholder can be adjusted as needed.

When handling non-ASCII characters such as Chinese, make sure that the character encoding is set correctly.

Through the above steps, you can use Java to paste the QR code in the specified location of the Word template and generate it into a PDF electronic voucher document!

The above is the detailed content of Java implementation of adding QR codes to the specified location of the Word template and generating PDFs. For more information about adding QR codes to Java Word, please pay attention to my other related articles!