栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA WORD转PDF

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA WORD转PDF

在项目中有时候需要将 Word 文件转换为 PDF 下面是我根据这几天在网上搜索的相关资料得出的总结
名称说明
aspose

该插件需要付费,功能强大支满足绝大部分业务场景持跨平台使用方便

官网地址:File Format APIs for Word Excel PDF Email PowerPoint Barcode Images OCR Note & 3D

jacob

未使用可参考下面地址

采用jacob实现word转pdf - QiaoZhi - 博客园

Docx4j

该插件开源,使用起来复杂。在Word转PDF时会出现转换错误

官网地址:docx4j

GitHub地址:https://github.com/plutext/docx4j

Itext

可以用使用 IText5 将 Word 转成 html 在由 html 转成 PDF,过程复杂且转出的 PDF不能保证格式正确

目前 IText 已经升级到 IText7 转为收费,部分插件开源

官网地址:The Leading PDF Library for Developers | iText

xdocreport

自己找到的资源较少,通过测试发现转换PDF也会存在格式出错

GitHub地址:

zGitHub - opensagres/xdocreport: XDocReport means XML Document reporting. It's Java API to merge XML document created with MS Office (docx) or OpenOffice (odt), LibreOffice (odt) with a Java model to generate report and convert it if you need to another format (PDF, XHTML...).

文档转换说明地址:https://github.com/opensagres/xdocreport/wiki/Converters

documents4j

目前正在使用的方法,需要安装在 Windows 下且电脑需要安装 Office 

官网地址首页有就相关 Word 转 PDF 的方法

官网地址:documents4j - A document format converter for Java

下面是使用 documents4j 将 Word 转 PDF 的代码
<-- pom.xml -->

    com.documents4j
    documents4j-local
    1.1.0



    com.documents4j
    documents4j-transformer-msoffice-word
    1.1.0

package com.converter;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import java.io.*;


public class ConverterPDF {

    
    public static String WordToPDF(String fileName, String inDir, String outDir) {

        InputStream doc = null;
        OutputStream pdf = null;

        //构建转换器
        IConverter converter = null;

        // word 文件路径
        String docPath = inDir + '/' + fileName + ".docx";

        // pdf 文件路径
        String pdfPath = outDir + '/' + fileName + ".pdf";

        try {

            doc = new FileInputStream(docPath);
            pdf = new FileOutputStream(pdfPath);

            converter = LocalConverter.builder().build();
            //执行文件转换
            converter.convert(doc).as(DocumentType.DOCX).to(pdf).as(DocumentType.PDF).execute();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                if (doc != null) {
                    doc.close();
                }
                if (pdf != null) {
                    pdf.close();
                }
                //关闭转换器
                if (converter != null) {
                    converter.shutDown();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return pdfPath;
    }


}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/930315.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号