美文网首页
word生成及word转pdf

word生成及word转pdf

作者: 张前峰 | 来源:发表于2022-04-06 16:48 被阅读0次

    生成word文档

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

    着重poi-tl

    Poi-tl

    引入依赖

           <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>4.1.2</version>
            </dependency>
          <dependency>
                <groupId>com.deepoove</groupId>
                <artifactId>poi-tl</artifactId>
                <version>1.9.1</version>
          </dependency>
    

    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<String, Object> 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<String, Object> 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

    引入依赖

            <dependency>
                <groupId>com.aspose</groupId>
                <artifactId>aspose-words</artifactId>
                <version>21.1.0</version>
            </dependency>
    

    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

          本文链接:https://www.haomeiwen.com/subject/jxzrsrtx.html