java word转换pdf(先自定义添加水印 后转换pdf)通过 aspose-words

 这种方式比较吃内存(容易内存泄漏),而且转换比较慢, 不推荐  , 而且这种方法会有水印,需要破解去水印添加xml配置

引入依赖jar 在文章最下面获取

在resource目录下载创建 License.xml 配置文件

破解去除自带的水印需要的xml文件内容

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

读取(水印)xml配置文件

 /**
 * @program: Backend
 * @author: xlk
 * @create: 2022-06-02 17:52
 */
public class AsposeUtil { 
    public static void getLicense() {
        try (InputStream is = AsposeUtil.class.getClassLoader().getResourceAsStream("License.xml")) {
            License license = new License();
            license.setLicense(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
}

 

package com.anchoremc.electric.consumer.util;

import com.aspose.words.SaveFormat;
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ShapeLineStyle;
import com.spire.doc.documents.ShapeType;
import com.spire.doc.fields.ShapeObject;
import java.awt.*;
import java.io.*;


/**
 * @program: Backend
 * @author: xlk
 * @create: 2022-06-02 15:44
 */
public class TestWordToPdf2 {


    public static void main(String[] args) throws Exception {

        // 读取模板
        String docxPath = "C:\\Users\\admin-xu\\Desktop\\11\\test.docx";
        File file = new File(docxPath);
        InputStream inputStream = new FileInputStream(file);

        // 先给word添加水印
        Document doc = new Document();
        //加载示例文档
        doc.loadFromStream(inputStream, FileFormat.Docx);
        //添加艺术字并设置大小
        ShapeObject shape = new ShapeObject(doc, ShapeType.Text_Plain_Text);
        shape.setWidth(120);
        shape.setHeight(20);
        //设置艺术字文本内容、位置及样式
        //shape.setVerticalPosition(25);
        //shape.setHorizontalPosition(25);
        shape.setRotation(-25);//旋转角度
        shape.getWordArt().setFontFamily("宋体");//字体
        shape.getWordArt().setText("机密文件");//文字
        shape.setFillColor(Color.LIGHT_GRAY);   //颜色   浅灰色
        shape.setLineStyle(ShapeLineStyle.Single);
        shape.setStrokeColor(new Color(192, 192, 192, 1));   //new Color(red,green,blue,alpha-透明度)   alpha - 透明度
        shape.setStrokeWeight(1);


        Section section;
        HeaderFooter header;
        for (int n = 0; n < doc.getSections().getCount(); n++) {
            section = doc.getSections().get(n);
            //获取section的页眉
            header = section.getHeadersFooters().getHeader();
            Paragraph paragraph;
            if (header.getParagraphs().getCount() > 0) {
                paragraph = header.getParagraphs().get(0);
            } else {
                paragraph = header.addParagraph();
            }
            // 多少 行
            for (int i = 0; i < 6; i++) {
                //添加段落到页眉
                paragraph = header.addParagraph();
                //复制艺术字并设置多行多列位置 ( 设置几排  )  //  多少列
                for (int j = 0; j < 5; j++) {
                    shape = (ShapeObject) shape.deepClone();
                    shape.setVerticalPosition(120 + 170 * i);//纵坐标  200  第一个开始值(距离顶部的位置)   300 * i 下一个出现的位置
                    shape.setHorizontalPosition(170 * j);//横坐标  200 距离左侧的位置    160 * j   下一个的 横坐标 位置
                    paragraph.getChildObjects().add(shape);
                }
            }
        }

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //保存文档(将添加水印的word添加到 ) 输出流 ByteArrayOutputStream
        doc.saveToFile(outStream, FileFormat.Docx);
        byte[] docBytes = outStream.toByteArray();
        // 得到添加水印的word
        InputStream docInputStream = new ByteArrayInputStream(docBytes);

        // 如果是浏览器下载 通过  HttpServletResponse  response
          /*  response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(  data.getOutFileName()+".pdf", "UTF-8"));
            OutputStream out = response.getOutputStream();*/

        // 文件输出路径
        OutputStream out = new FileOutputStream("C:\\Users\\admin-xu\\Desktop\\11\\test01.pdf");

        // 这种方式比较吃内存(容易内存泄漏),而且转换比较慢, 不推荐  , 而且这种方法会有水印,需要破解去水印添加xml配置
        AsposeUtil.getLicense();
         com.aspose.words.Document document = new com.aspose.words.Document(docInputStream);

        long  a1   =  System.currentTimeMillis();
        document.save(out, SaveFormat.PDF);
        long  a2   =  System.currentTimeMillis();
        System.out.println("共计用时: " + ((a2 - a1) ) + "毫秒");
        out.flush();
        outStream.close();
        inputStream.close();
        doc.close();
        docInputStream.close();

    }
}


仅仅一个转换就耗时六七秒,放入项目中实际测试大概的20-30秒左右,因为这么慢,所以需要优化,为此提供了另外一种方法,看最底部

 word 截图

转换后的pdf 截图

 

jar包下载地址

百度云链接:https://pan.baidu.com/s/1dlsWglXNpgfxXLuIO6pZ-w 
提取码:1234

另外一中方法: java word转pdf (添加水印)通过poi等组件实现_My--Style的博客-CSDN博客

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值