利用Docx4j插件将文件word转pdf添加水印

发布时间 2023-04-26 17:48:39作者: 茫无所知

 

public void testWordToPDF(HttpServletResponse response) throws Exception {
        String FILE_NAME = "E:\\1111.docx";
        InputStream inputStream = new FileInputStream(FILE_NAME);
        InputStream is = DocxToPdf.docToPdf(inputStream);
        InputStream aa = PdfWaterMark.addWaterMark(is, "admin", 10);
        //将XWPFDocument文件变为MultipartFile
        String reportName = "企业123";
        MultipartFile multipartFile = inputStreamToCommonsMultipartFile(aa, reportName + ".pdf");
    
        String fileName = multipartFile.getOriginalFilename();
        File file = new File("E:\\"+fileName);
        OutputStream out = null;
        try{
            //获取文件流,以文件流的方式输出到新文件
            out = new FileOutputStream(file);
            byte[] ss = multipartFile.getBytes();
            for(int i = 0; i < ss.length; i++){
                out.write(ss[i]);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 

/**
     *
     * @param is 输入流
     * @return
     */
    public static InputStream docToPdf(InputStream is) {
        try {
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(is);
            Mapper fontMapper = new IdentityPlusMapper();
            if(PhysicalFonts.get("SimSun") == null){
                PhysicalFonts.addPhysicalFonts("SimSun", WordUtils.class.getResource("/simsun.ttc"));
            }
            fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
            fontMapper.put("宋体", PhysicalFonts.get("SimSun"));
            fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei"));
            fontMapper.put("黑体", PhysicalFonts.get("SimHei"));
            fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));
            fontMapper.put("新宋体", PhysicalFonts.get("NSimSun"));
            fontMapper.put("仿宋", PhysicalFonts.get("FangSong"));
            fontMapper.put("幼圆", PhysicalFonts.get("YouYuan"));
            fontMapper.put("方正小标宋简体", PhysicalFonts.get("SimHei"));
            fontMapper.put("仿宋_GB2312", PhysicalFonts.get("SimHei"));
            wordMLPackage.setFontMapper(fontMapper);
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            FOSettings foSettings = Docx4J.createFOSettings();
            foSettings.setWmlPackage(wordMLPackage);

            Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);
            return os.getInputStream();
        } catch (Exception e) {
            log.error("word转pdf失败==", e);
            throw new RuntimeException("word转pdf失败");
        }
    }
/**
     * pdf生成水印
     * @param is    字节输入流
     * @param WaterMarkContent  水印文案
     * @param numberOfPage      每页需要插入的条数
     * @throws Exception
     */
    public static InputStream addWaterMark(InputStream is, String WaterMarkContent, int numberOfPage)throws Exception {
        PdfReader reader = new PdfReader(is);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        PdfStamper stamper = new PdfStamper(reader, os);
        PdfGState gs = new PdfGState();

        //设置字体
        BaseFont font =  BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        // 设置透明度
        gs.setFillOpacity(0.4f);

        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        for (int i = 1; i < total; i++) {
            content = stamper.getOverContent(i);
            content.beginText();
            content.setGState(gs);
            //水印颜色
            content.setColorFill(BaseColor.LIGHT_GRAY);
            //水印字体样式和大小
            content.setFontAndSize(font, 35);
            //插入水印  循环每页插入的条数
            for (int j = 0; j < numberOfPage; j++) {
                content.showTextAligned(Element.ALIGN_CENTER, WaterMarkContent, 300, 200 * (j + 1), 30);
            }
            content.endText();
        }
        stamper.close();
        return os.getInputStream();
    }

 

<!--word 转 pdf -->
        <dependency>
            <groupId>org.docx4j</groupId>
            <artifactId>docx4j</artifactId>
            <version>${docx4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.docx4j</groupId>
            <artifactId>docx4j-export-fo</artifactId>
            <version>${export.fo.version}</version>
        </dependency>

 

 

 

参考链接:
https://blog.csdn.net/qq_26772309/article/details/127018051