Word转pdf

1.添加依赖

XML 复制代码
<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.3</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext7-core</artifactId>
        <version>7.2.2</version>
    </dependency>
</dependencies>

2.示例代码

java 复制代码
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WordToPdfConverter {
    public static void main(String[] args) {
        String docFilePath = "input.docx"; // 输入的Word文件路径
        String pdfFilePath = "output.pdf"; // 输出的PDF文件路径

        try {
            convertWordToPdf(docFilePath, pdfFilePath);
            System.out.println("转换成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void convertWordToPdf(String docFilePath, String pdfFilePath) throws IOException {
        XWPFDocument document = new XWPFDocument(new FileInputStream(docFilePath));
        PdfWriter writer = new PdfWriter(new FileOutputStream(pdfFilePath));
        PdfDocument pdfDoc = new PdfDocument(writer);
        Document pdfDocument = new Document(pdfDoc);
// 设置中文字体
        PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", true);
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            pdfDocument.add(new Paragraph(paragraph.getText()).setFont(font));
        }

        pdfDocument.close();
        pdfDoc.close();
        document.close();
    }
}

Apache POI可以处理Word文档,但它不直接支持输出为PDF。因此,通常需要将Word内容提取出来,然后通过PDF生成工具(如Apache PDFBox)来生成PDF。这种方法适合简单的文本和格式。

相关推荐
FinelyYang4 小时前
uniapp使用kkfileview在线预览ppt,excel,word,pdf类型文件
pdf·uni-app·powerpoint
yivifu4 小时前
使用lxml操作 Word 的 OpenXML 底层
word·openxml·lxml
WORLDPO922617 小时前
QTE-020-01-L/F/C-D-A-K-TR_实物_数据手册PDF_国产替代
pdf
asdzx671 天前
C# 操作 PDF 元数据:从属性写入到字段提取的完整流程
前端·pdf·c#
WORLDPO92261 天前
SFSDT-10/15/20/25/35-28-G-19.69-SR_实物图_数据手册PDF_国产替代
pdf·pcb工艺·pcb
梦想出海-Phoebe1 天前
Gemini新增文件编辑功能:PDF、Word、Excel处理体验分享
pdf·word·excel
开开心心就好1 天前
网页图片批量下载工具,输入链接就保存
服务器·算法·leetcode·支持向量机·pdf·ocr·1024程序员节
汤姆宝库2 天前
法考历年真题及答案解析合集pdf版(2002-2025年)
pdf·法考
优化控制仿真模型2 天前
2026【英一】考研英语一历年真题及答案解析PDF电子版(1980-2025年)
考研·pdf
开开心心_Every3 天前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea