利用Java将word文件转成pdf文件

说明:使用本方法计算机中必须含有office

一.准备工作

1.准备如图三个文件:

2.将第二个文件复制到C:\Windows\System32,将第三个文件复制到C:\Windows\SysWOW64,

然后将这两个文件复制到jdk,jre里面的bin文件夹

二.开始编译

1.项目导入第一个文件的jar包

2.代码如图所示:

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;

import java.io.File;

public class Test {
        static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。
        static final int wdFormatPDF = 17;// PDF 格式

        public static void wordToPdf(String wordpath, String pdfpath) {

            System.out.println("启动Word...");
            long start = System.currentTimeMillis();
            ActiveXComponent app = null;
            try {
                //打开word应用程序
                app = new ActiveXComponent("Word.Application");
                设置应用操作是文档不在明面上显示,只在后台静默处理。
                app.setProperty("Visible", false);
                //获得文档集合,用来操作我们需要处理的文档.
                Dispatch docs = app.getProperty("Documents").toDispatch();
                System.out.println("打开文档..." + wordpath);
                //打开word文档
                Dispatch doc = Dispatch.call(docs,//
                        "Open", //
                        wordpath,// FileName
                        false,// ConfirmConversions
                        true // ReadOnly
                ).toDispatch();

                System.out.println("转换文档到PDF..." + pdfpath);
                File tofile = new File(pdfpath);
                //创建存放pdf的文件夹
                if (tofile.exists()) {
                    tofile.delete();
                }
                //将word另存为pdf
                Dispatch.call(doc,//
                        "SaveAs", //
                        pdfpath, // FileName
                        wdFormatPDF);
                //关闭word文档
                Dispatch.call(doc, "Close", false);
                long end = System.currentTimeMillis();
                System.out.println("转换完成..用时:" + (end - start) + "ms.");
            } catch (Exception e) {
                System.out.println("========Error:文档转换失败:" + e.getMessage());
            } finally {
                if (app != null)
                    app.invoke("Quit", wdDoNotSaveChanges);
            }
        }

        public static void main(String[] args) {
            wordToPdf("C:\\Users\\wukefan\\Desktop\\test.doc","C:\\Users\\wukefan\\Desktop\\test.pdf");
        }
}

三.运行项目

1.运行成功,项目结果如图所示:

2.如图所示桌面,桌面多了个pdf文件:

在Linux环境下,Java可以借助第三方库来实现Word文档(.doc或.docx)到PDF换。最常用的库是Apache POI(针对Microsoft Office文件,包括Word)和iText或Flying Saucer(用于处理HTML和CSS,适合将基于Web的内容换为PDF)。以下是一个简单的步骤概述: 1. **添加依赖**: - 对于Apache POI,你需要将其添加到你的Maven项目中,通过`<dependency>`标签在pom.xml文件中引入: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>最新版本号</version> </dependency> ``` - iText或Flying Saucer也需要相应版本的依赖。 2. **读取Word文档**: 使用POI的XWPFDocument类打开Word文档,然后获取需要的数据。 3. **处理数据**: 将Word内容解析成HTML格式,这通常涉及到文本提取、样式处理等操作。 4. **生成PDF**: - iText库提供了一个叫做PdfWriter的工具,可以创建新的PDF文档并写入HTML内容。 - Flying Saucer利用Servlet API或JSP直接渲染HTML为PDF。 5. **保存PDF**: 创建完成后的PDF文件,你可以选择存储到本地或网络上。 示例代码(简化版)可能会看起来像这样: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import com.itextpdf.text.Document; import com.itextpdf.text.Paragraph; public void convertDocToPdf(String wordFilePath, String pdfFilePath) { // Step 1 & 2: Open and read Word file XWPFDocument document = new XWPFDocument(new FileInputStream(wordFilePath)); // Step 3: Process the content (not shown here) List<String> paragraphs = processWordContent(document); // Step 4: Generate PDF using iText Document pdf = new Document(); try { PdfWriter.getInstance(pdf, new FileOutputStream(pdfFilePath)); pdf.open(); for (String paragraph : paragraphs) { pdf.add(new Paragraph(paragraph)); } pdf.close(); } catch (Exception e) { e.printStackTrace(); } } ```
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吴名氏.

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值