word生成及word转pdf

生成word文档

  1. word模板转xml ,字符串替换。复杂不可维护。(不推荐)
  2. Poi-tl 。Word模板引擎,基于Apache POI,提供更友好的API,低代码,准备文档模板和数据即可。(推荐)

着重poi-tl

Poi-tl

引入依赖

       
            org.apache.poi
            poi-ooxml
            4.1.2
        
      
            com.deepoove
            poi-tl
            1.9.1
      

word模板

image.png

JAVA代码

package com.yiliu.core.util;


import com.deepoove.poi.XWPFTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * word模板生成
 *
 * @author 张前峰
 * @date 2022-04-06 15:36
 */
public class WordTemplateUtil {


    /**
     * word通过模板生成文件
     *
     * @param templateFile
     * @param data
     * @param targetPath
     * @param fileName
     * @throws IOException
     */
    public static void generateWord(String templateFile, Map data, String targetPath, String fileName) throws IOException {
        if (!fileName.toLowerCase(Locale.ROOT).endsWith(".docx")) {
            fileName += ".docx";
        }
        XWPFTemplate template = XWPFTemplate.compile(templateFile).render(data);
        File dir = new File(targetPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        template.writeAndClose(new FileOutputStream(targetPath + fileName));
    }

    public static void main(String[] args) {
        Map data = new HashMap<>();
        data.put("name", "yiliu");
        try {
            generateWord("D:\\data\\test\\template.docx", data,
                    "D:\\data\\test\\", "test.docx");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

效果

image.png

转pdf

采用 aspose-words

aspose-words

引入依赖

        
            com.aspose
            aspose-words
            21.1.0
        

JAVA代码

package com.yiliu.core.util;

import com.aspose.words.Shape;
import com.aspose.words.*;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * docx格式转pad
 *
 * @author Administrator
 */
@Slf4j
public class Docx2PdfUtil {
    /**
     * doxc to pdf
     *
     * @param inPath  docx文件的路径
     * @param outPath pdf文件的路径
     */
    public static void doc2pdf(String inPath, String outPath) {

        if (!getLicense()) {
            return;
        }
        FileOutputStream os = null;
        try {
            File file = new File(outPath);
            os = new FileOutputStream(file);
            Document doc = new Document(inPath);
            insertWatermarkText(doc, "水印测试!");
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private static void insertWatermarkText(Document doc, String watermarkText) throws Exception {
        Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);
        // 水印内容
        watermark.getTextPath().setText(watermarkText);
        // 水印字体
        watermark.getTextPath().setFontFamily("宋体");
        // 水印宽度
        watermark.setWidth(500);
        // 水印高度
        watermark.setHeight(100);
        // 旋转水印
        watermark.setRotation(-40);
        // 水印颜色
        watermark.getFill().setColor(Color.lightGray);
        watermark.setStrokeColor(Color.lightGray);
        watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);
        watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);
        watermark.setWrapType(WrapType.NONE);
        watermark.setVerticalAlignment(VerticalAlignment.CENTER);
        watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);
        Paragraph watermarkPara = new Paragraph(doc);
        watermarkPara.appendChild(watermark);
        for (Section sect : doc.getSections()) {
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);
            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);
        }
        System.out.println("Watermark Set");
    }

    private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception {
        HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);
        if (header == null) {
            header = new HeaderFooter(sect.getDocument(), headerType);
            sect.getHeadersFooters().add(header);
        }
        header.appendChild(watermarkPara.deepClone(true));
    }

    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = Docx2PdfUtil.class.getClassLoader().getResourceAsStream("aspose/license2021.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.error("获取license失败!", e);
        }
        return result;
    }


    public static void main(String[] args) {
        doc2pdf("D:\\data\\test\\test.docx",
                "D:\\data\\test\\test.pdf");
    }
}


效果

image.png

你可能感兴趣的:(word生成及word转pdf)