java 实现word转pdf,并且实现内容替换,乱码处理,去水印

1.引入依赖

aspose-words的包需要从官网下载

<dependency>
    <groupId>fakepath</groupId>
    <artifactId>aspose-words</artifactId>
    <version>21.6.0</version>
    <classifier>jdk17</classifier>
</dependency>

2. 这里需要下载21.6.0上传到自己公司的仓库,或者加入到依赖包,没有找到依赖包的可以私信我

3.word转pdf工具类

/**
 * @version 1.0
 * @date 2022/7/19 18:02
 */

import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import javassist.Modifier;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.gz.common.utils.DateUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
public class Word2PdfUtil {   
 public final static String fileUrl = "/home/server/overdue/";

    public final static String windowsFile = "C:\\home\\server\\overdue\\";



    /**
     *  方法说明: 将存在云盘的word文件,更具map 配置的key,value关键字替换word的文件类容
     *  将替换好的word文件转换为pdf,存放到本地文件目录
     * @param url word 网络文件存放地址
     * @param fileName 文件名称
     * @param map 需要替换 word 文件的内容
     * @return
     * @throws Exception
     */
    public static String wordToPdf(String url, String fileName, Map<String, String> map) throws Exception {
        FileOutputStream os = null;
        String osFile = "";
        //这里定义文件夹名称,可以按时间定义,自己实现下
        String dataStr = "20220722";
        try {
            String osUrl  = "";
            String osName = System.getProperties().getProperty("os.name");
            if (osName.indexOf("Windows")>=0) {
                osUrl = windowsFile.concat(dataStr).concat("/");
            }else{
                osUrl = fileUrl.concat(dataStr).concat("/");
            }
            //生成一个空的PDF文件
            String prefix = fileName.substring(0,fileName.indexOf("."));
            osFile = osUrl.concat(prefix).concat(".pdf");
            File file = new File(osFile);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdir();
            }
            os = new FileOutputStream(file);
            //要转换的word文件
            String docHome = osUrl.concat(fileName);
            try {
                FileUtils.copyURLToFile(new URL(url), new File(osUrl, fileName));
            }catch (Exception e){
                log.error("【下载模板失败】:{}",e);
            }
            log.info("【docHome】:{}",docHome);
            Document doc = new Document(docHome);
            for (Map.Entry<String, String> entry: map.entrySet()) {
                doc.getRange().replace(entry.getKey(), entry.getValue());
            }
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("【word转pdf异常】:{}",e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error("【word转pdf io异常】:{}",e);
                }
            }
        }
        return osFile;
    }
}

4.在Linux需要安装字体包 进入C:\Windows\Fonts,该文件夹下就存放相关字体打包成压缩包

/home/server/目录下增加overdue文件夹
给overdue文件夹 chmod 755 权限

需要在 linux系统配置字体包
安装步骤:

1./usr/share/fonts 目录下新增 my_fonts

给my_fonts文件 chmod 755 权限

2.在my_fonts解压字体包

3.进入 my_fonts  安装字体索引指令 yum install -y fontconfig mkfontscale

4.建立字体索引信息更新字体缓存 
进入 my_fonts 目录安装字体,建立索引更新缓存
mkfontscale && mkfontdir && fc-cache -fv

5.查看字体是否安装成功 fc-list :lang=zh

安装以后解决linux乱码问题

5.如果转出来的pdf带有水印,需要特殊处理


    public static void removeMark() {
        try {
            log.info("【开始加载去除水印】");
            Class<?> aClass = Class.forName("com.aspose.words.zzXyu");
            java.lang.reflect.Field zzYAC = aClass.getDeclaredField("zzZXG");
            zzYAC.setAccessible(true);

            java.lang.reflect.Field modifiersField = zzYAC.getClass().getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(zzYAC, zzYAC.getModifiers() & ~Modifier.FINAL);
            zzYAC.set(null, new byte[]{76, 73, 67, 69, 78, 83, 69, 68});
            log.info("【加载去除水印完成】");
        } catch (Exception e) {
            log.error("apose word :{}", e);
        }
    }

6.到此处理完成,真实接入过,如遇到问题可以私信,仅供学习参考,务做其他用途

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
根据提供的引用内容,可以得知在Linux下进行wordPDF时,可能会出现中文码的问题,原因是缺少一些字体。而Java作为一种跨平台的编程语言,同样也可能会出现这个问题。解决方法如下: 1.安装所需字体 在Linux系统中,可以通过以下命令安装中文字体: ```shell sudo apt-get install ttf-wqy-zenhei ``` 2.使用iText库进行换 iText是一个开源的Java PDF库,可以用于创建、修改和维护PDF文档。使用iText库进行wordPDF,可以避免中文码的问题。以下是一个简单的示例代码: ```java import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.PDFConverter; import org.apache.poi.hwpf.usermodel.Range; import java.io.*; public class WordToPdf { public static void main(String[] args) { String inputFile = "input.doc"; String outputFile = "output.pdf"; try { InputStream input = new FileInputStream(new File(inputFile)); HWPFDocument wordDocument = new HWPFDocument(input); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(outputFile)); document.open(); Range range = wordDocument.getRange(); document.add(new Paragraph(range.text())); document.close(); input.close(); System.out.println("换成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码使用Apache POI库读取word文档,然后使用iText库将其换为PDF文档。 3.使用JODConverter进行换 JODConverter是一个开源的Java库,可以将Office文档换为PDF、HTML、ODF等格式。以下是一个简单的示例代码: ```java import org.artofsolving.jodconverter.OfficeDocumentConverter; import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration; import org.artofsolving.jodconverter.office.OfficeManager; import java.io.File; public class WordToPdf { public static void main(String[] args) { String inputFile = "input.doc"; String outputFile = "output.pdf"; OfficeManager officeManager = null; try { officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager(); officeManager.start(); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager); converter.convert(new File(inputFile), new File(outputFile)); System.out.println("换成功!"); } catch (Exception e) { e.printStackTrace(); } finally { if (officeManager != null) { officeManager.stop(); } } } } ``` 以上代码使用JODConverter将word文档换为PDF文档。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值