All source code and dependent resources of this project are linked at the top of the article. You can download and use them if necessary.
1. Requirement description
- Read a word template from the specified location
- Obtain business data and write it into the word template to generate a new word document
- Convert newly generated word document to pdf format
- add watermark to pdf document
2. Effect preview
- word template
- Watermarked pdf document
3. Implementation ideas
- Word template data writing: implemented using the
poi-tl
library - Word to pdf format:
aspose-words
library implementation - Add watermark to pdf:
aspose-pdf
library implementation
4. Implementation process
4.1 Dependent library preparation
poi-tl
can be downloaded directly from the central warehouse using maven, but aspose
cannot be downloaded. You need to download the jar package from the Internet and import it into the local warehouse.
-
poi-tl
<dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.12.1</version> </dependency>
-
aspose-word
Import the jar package into the local warehousemvn install:install-file \ -DgroupId="com.aspose" \ -DartifactId="aspose-words" \ -Dversion="15.8.0" \ -Dpackaging="jar" \ -Dfile="aspose-words-15.8.0-jdk16.jar"
Add dependencies to the project
<dependency> <groupId>com.aspose</groupId> <artifactId>aspose-words</artifactId> <version>15.8.0</version> </dependency>
-
aspose-pdf
Import the jar package into the local warehousemvn install:install-file \ -DgroupId="com.aspose" \ -DartifactId="aspose-pdf" \ -Dversion="17.8" \ -Dpackaging="jar" \ -Dfile="aspose.pdf-17.8.jar"
Add dependencies to the project
<dependency> <groupId>com.aspose</groupId> <artifactId>aspose-pdf</artifactId> <version>17.8</version> </dependency>
-
license.xml
Since theaspose
library is divided into a free version and a paid version, the documents exported by the free version have a trial watermark, solicense.xml
needs to be added. The copyright relationship is not stated in the article. If necessary, you can download the complete source code package linked at the top of the article.
4.2 Core implementation method
@SpringBootApplication public class Word2PDFApplication {<!-- --> public static void main(String[] args) {<!-- --> SpringApplication.run(Word2PDFApplication.class, args); // word template String wordTemplatePath = "src/main/resources/templates/resume template.docx"; // word after writing data String wordOutputPath = "src/main/resources/templates/resume template-output.docx"; // Convert word to pdf String pdfOutputPath = "src/main/resources/templates/resume template.pdf"; // Add watermark to pdf String pdfWithMarkerOutputPath = "src/main/resources/templates/resume template-marker.pdf"; // step 1: Encapsulate template data Map<String, Object> dataMap = getPersonDataMap(); // step 2: Write data into word template writeDataToWord(dataMap, wordTemplatePath, wordOutputPath); // step 3: Convert word to pdf convertWordToPdf(wordOutputPath, pdfOutputPath); // step 4: Add watermark to pdf addMarkerToPdf(pdfOutputPath, pdfWithMarkerOutputPath); } // Encapsulate business data and use it to fill in the corresponding placeholders of the template private static Map<String, Object> getPersonDataMap() {<!-- --> Map<String, Object> personDataMap = new HashMap<>(); personDataMap.put("name", "Zhang San"); personDataMap.put("sex", "male"); personDataMap.put("birthDate", "1998-12-02"); personDataMap.put("id", "420202199812020011"); personDataMap.put("phone", "18819297766"); personDataMap.put("skills", "java Spring MySQL ..."); return personDataMap; } //Write business data into word template and generate new word file private static void writeDataToWord(Map<String, Object> dataMap, String wordTemplatePath, String wordOutputPath) {<!-- --> XWPFTemplate render = XWPFTemplate.compile(wordTemplatePath).render(dataMap); File dest = new File(wordOutputPath); if (!dest.getParentFile().exists()) {<!-- --> dest.getParentFile().mkdirs(); } try {<!-- --> render.writeToFile(wordOutputPath); } catch (IOException e) {<!-- --> throw new RuntimeException(e); } } //Convert the newly generated word document with business data to pdf format private static void convertWordToPdf(String wordOutputPath, String pdfOutputPath) {<!-- --> // Verify License. If not verified, the converted pdf document will have a watermark. if (!getAsposeWordLicense()) {<!-- --> return; } FileOutputStream os = null; try {<!-- --> long old = System.currentTimeMillis(); File file = new File(pdfOutputPath); os = new FileOutputStream(file); Document doc = new Document(wordOutputPath); doc.save(os, SaveFormat.PDF); long now = System.currentTimeMillis(); System.out.println("pdf conversion successful, total time taken: " + ((now - old) / 1000.0) + "seconds"); } catch (Exception e) {<!-- --> e.printStackTrace(); } finally {<!-- --> if (os != null) {<!-- --> try {<!-- --> os.flush(); os.close(); } catch (IOException e) {<!-- --> e.printStackTrace(); } } } } //Add watermark effect to the converted pdf document private static void addMarkerToPdf(String pdfOutputPath, String pdfWithMarkerOutputPath) {<!-- --> // Verify License. If not verified, the pdf document after adding watermark will have trial watermark. boolean asposePdfLicense = getAsposePdfLicense(); if (!asposePdfLicense) {<!-- --> return; } com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document(pdfOutputPath); TextStamp textStamp = new TextStamp("watermark text"); textStamp.getTextState().setFontSize(14.0F); textStamp.getTextState().setFontStyle(FontStyles.Bold); textStamp.setRotateAngle(45); textStamp.setOpacity(0.2); //Set watermark spacing float xOffset = 100; float yOffset = 100; //Add watermark to each page for (Page page : pdfDocument.getPages()) {<!-- --> float xPosition = 0; float yPosition = 0; //Add watermark to the page until the page is covered while (yPosition < page.getRect().getHeight()) {<!-- --> textStamp.setXIndent(xPosition); textStamp.setYIndent(yPosition); page.addStamp(textStamp); xPosition + = xOffset; //If the watermark exceeds the page width, move it to the next line if (xPosition + textStamp.getWidth() > page.getRect().getWidth()) {<!-- --> xPosition = 0; yPosition + = yOffset; } } } //Save the modified document pdfDocument.save(pdfWithMarkerOutputPath); } //Verify the license, otherwise there will be a trial watermark private static boolean getAsposeWordLicense() {<!-- --> boolean result = false; InputStream is = null; try {<!-- --> ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:license.xml"); is = resources[0].getInputStream(); License asposeLic = new License(); asposeLic.setLicense(is); result = true; } catch (Exception e) {<!-- --> e.printStackTrace(); } finally {<!-- --> if (is != null) {<!-- --> try {<!-- --> is.close(); } catch (IOException e) {<!-- --> e.printStackTrace(); } } } return result; } //Verify the license, otherwise there will be a trial watermark private static boolean getAsposePdfLicense() {<!-- --> boolean result = false; InputStream is = null; try {<!-- --> ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); org.springframework.core.io.Resource[] resources = resolver.getResources("classpath:license.xml"); is = resources[0].getInputStream(); com.aspose.pdf.License asposeLic = new com.aspose.pdf.License(); asposeLic.setLicense(is); result = true; } catch (Exception e) {<!-- --> e.printStackTrace(); } finally {<!-- --> if (is != null) {<!-- --> try {<!-- --> is.close(); } catch (IOException e) {<!-- --> e.printStackTrace(); } } } return result; } }