基于java技术实现word转pdf

前言:

       在现代工作环境中,文档的处理和共享是不可或缺的任务。而将Word文件转换为PDF格式,已经成为了许多工作场景中的常见需求。无论是在商务合同、报告、简历还是其他文档类型中,将其转换为PDF格式都具有诸多优势。

        首先,让我们了解一下为什么在工作中将Word文件转换为PDF格式如此重要。PDF格式具有跨平台、可靠性高、内容保护性强等诸多优势。通过将文档转换为PDF格式,您可以确保文档在不同操作系统和设备上的一致性显示,同时保护文档内容不被随意修改,加密等一系列操作。此外,PDF格式还具有良好的打印和共享性能,使得文档的传递和展示更加方便和专业。

在本文中,我们将使用Java编程语言来实现Word文件转换为PDF格式的功能。

基于java实现word转pdf主要常见的有三种方法(Apache POI,Aspose.Words,LibreOffice和OpenOffice)

下面将先介绍他们的优缺点

一、Apache POI

缺点:

  • 由于Word和PDF的结构和样式差异较大,转换可能存在一定的格式丢失或错误。
  • 对于复杂的Word文档,转换过程可能会比较耗时和复杂。

对于Apache POI这种在实现word转pdf时可能需要大量的代码去定义格式,本文将不在介绍(不推荐使用)

二、Aspose.Words

优点:

  • Aspose.Words是一个功能强大的商业库,具有丰富的特性和性能优化。
  • 它能够直接处理Word文档,支持较高程度的格式保留和准确性。
  • Aspose.Words提供了简单易用的API接口,可灵活地控制转换过程。

缺点:

  • Aspose.Words是商业库,商业用途,要付费购买证书。

三、LibreOffice和OpenOffice 

优点:

  • LibreOffice和OpenOffice是免费的开源软件,可以自由下载和使用。
  • 它们具有丰富的功能,能够处理包括Word在内的多种文档格式。
  • 由于使用成熟的开源项目,它们对于Word转PDF的功能已经被广泛测试和验证。

缺点:

  • LibreOffice和OpenOffice,其安装包较大,可能会占用一定的系统资源。
  • 需要单独启动,可能存在程序掉线问题,对于并发时,性能会有所下降

了解完这三种方法,那么现在就具体实现一下 基于Aspose.Words、libreoffice(openoffice)技术转pdf

 一、Aspose.Words 

依赖:

    <dependencies>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>版本自己选择</version>
        </dependency>
    </dependencies>

代码:

package com.atxinxin;

import com.aspose.words.Document;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @author weixinxin 2024-01-25
 **/

public class WordToPdf {

    /**
     * @param wordPath word路径
     * @param pdfPath pdf输出路径
     * @Description word转pdf
     * @Date 14:31 2024/01/25
     * @author weixinxin
     */
    public static void TextWordToPdf(String wordPath, String pdfPath) throws Exception {
//		if (!getLicense()) {
//			return;
//		}
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            File file = new File(pdfPath);
            os = new FileOutputStream(file);
            Document doc = new Document(wordPath);
            doc.save(os, com.aspose.words.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
        }finally {
            if(os!=null) {
                os.close();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String wordPath = "C:\\Users\\weixinxin_ext\\Desktop\\测试word转pdf.docx";
        String pdfPath = "C:\\Users\\weixinxin_ext\\Desktop\\测试word转pdf.pdf";
        TextWordToPdf(wordPath,pdfPath);
    }
}

效果:

结果:

看word转pdf耗时所用时间可以知道很快。

但是转成功的pdf文件内容有Evaluation Only. Created with Aspose.Words. Copyright 2003-2015 Aspose Pty Ltd. 这个其实也可以理解为水印,是因为没有验证证书

看一下验证证书的结果:

验证证书代码:

将上面word转pdf注掉的代码解开,调用此方法,这个license我放到了java文件中,也可以在xml中配置,需要购买证书,将下方代码有???的填上即可

private static boolean getLicense() throws Exception {
        boolean result = false;
        ByteArrayInputStream is =null;
        try {
            String licenseXml = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>????</SubscriptionExpiry><LicenseExpiry>????</LicenseExpiry><SerialNumber>?????</SerialNumber></Data><Signature>????</Signature></License>";
            is = new ByteArrayInputStream(licenseXml.getBytes());
            License license = new License();
            license.setLicense(is);
            is.close();
            result = true;
        }finally {
            if(is!=null) {
                is.close();
            }
        }
        return result;
    }

到此就基于Aspos.Words转pdf结束,很好用,简单便捷,但是需要钱

二、libreoffice

基于libreoffice转pdf,需要下载安装

libreoffice下载中文网:https://zh-cn.libreoffice.org/

本次下载是7.5.9版本,linux系统,可根据自己需求变

下载完成:

上传到Lunix系统解压:

tar -xvf LibreOffice_7.5.9_Linux_x86-64_rpm.tar.gz

进入RPMS文件中:

cd LibreOffice_7.5.9.2_Linux_x86-64_rpm/RPMS/
yum localinstall *.rpm

安装过程遇到选择,y,安装完成,会在opt文件目录下生成

启动命令:

nohup libreoffice7.5 --headless --accept="socket,host=0.0.0.0,port=1998;urp;" --nofirststartwizard &

查看进程:

ps -ef|grep office

以上libreoffice就安装完成,准备工作就完成了,下面上代码了

依赖:

       <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter-cli</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>juh</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>jurt</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.openoffice</groupId>
            <artifactId>ridl</artifactId>
            <version>4.1.2</version>
        </dependency>

代码:

/**
     * @param wordPath word路径
     * @param pdfPath  pdf输出路径
     * @Description libreoffice word转pdf
     * @Date 17:58 2024/01/25
     * @author weixinxin
     */
    public static void libreOfficeWordToPdf(String wordPath, String pdfPath) throws Exception {
        long startTime = System.currentTimeMillis();
        File inputFile = new File(wordPath);
        File outputFile = new File(pdfPath);
        OpenOfficeConnection connection = new SocketOpenOfficeConnection("libreoffice安装的系统ip", 1998);//启动指定的端口
        connection.connect();
        DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);

        System.out.println("time==" + (System.currentTimeMillis() - startTime));

        converter.convert(inputFile, outputFile);
        connection.disconnect();

        System.out.println("time==" + (System.currentTimeMillis() - startTime));

    }

    public static void main(String[] args) throws Exception {
        String wordPath = "C:\\Users\\weixinxin_ext\\Desktop\\测试word转pdf.docx";
        String pdfPath = "C:\\Users\\weixinxin_ext\\Desktop\\测试word转pdf.pdf";
//        textWordToPdf(wordPath,pdfPath);
        libreOfficeWordToPdf(wordPath, pdfPath);
    }

效果:

可能是本地连接的linux系统在连接时时间较长

结果: 

根据上图可以看到时间较长,但是文件没有任何水印,费时,但免费

  • 29
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 实现 Word PDF 的基本思路是:先将 Word 文档为 HTML 格式,然后使用 iText 库将 HTML PDF 格式。下面是基于 Apache POI 和 iText 库实现 Word PDF 的示例代码: ```java import java.io.*; import org.apache.poi.xwpf.converter.pdf.PdfConverter; import org.apache.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.xwpf.usermodel.XWPFDocument; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerHelper; public class WordToPdfConverter { public static void main(String[] args) { String inputWord = "input.docx"; String outputPdf = "output.pdf"; try { // 读取 Word 文档 InputStream in = new FileInputStream(inputWord); XWPFDocument document = new XWPFDocument(in); // 创建 PDF 选项 PdfOptions options = PdfOptions.create(); // 将 Word 为 HTML 格式 ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfConverter.getInstance().convert(document, baos, options); String html = new String(baos.toByteArray()); // 创建 PDF 文档 Document pdfDoc = new Document(PageSize.A4); PdfWriter writer = PdfWriter.getInstance(pdfDoc, new FileOutputStream(outputPdf)); pdfDoc.open(); // 将 HTML PDF 格式 XMLWorkerHelper.getInstance().parseXHtml(writer, pdfDoc, new ByteArrayInputStream(html.getBytes())); // 关闭 PDF 文档 pdfDoc.close(); writer.close(); System.out.println("换成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 需要注意的是,该示例代码需要引入以下依赖库: - poi-ooxml - poi-ooxml-schemas - itextpdf - itext-pdfa - xmlworker 另外,需要注意的是,由于 Word 文件格式比较复杂,换为 HTML 后可能会存在一些格式上的差异,因此换后的 PDF 文件可能会与原 Word 文件在排版、格式等方面略有不同。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值