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。这种方法适合简单的文本和格式。

相关推荐
Array*1 小时前
java实现word中插入附件(支持所有文件格式)
java·开发语言·word·poi·ole
非凡ghost3 小时前
Xournal++(PDF文档注释工具) 中文绿色版
学习·pdf·生活·软件需求
MonkeyKing_sunyuhua3 小时前
使用ARQ做PDF OCR和 图片OCR的任务的方案
pdf·ocr
艾上编程4 小时前
第一章——办公自动化之Word报告自动生成:解放双手,高效创作
word
2501_930707784 小时前
如何使用C#代码在 PDF 中添加或删除附件
pdf
m5655bj4 小时前
如何使用 Python 调整 PDF 页面顺序?
python·pdf
YuanYWRS6 小时前
办公基础:实现PDF中表单不改变格式的情况下转成excel
pdf·excel
E_ICEBLUE1 天前
PDF vs PDF/A:区别、场景与常用转换方法(2025 全面解读)
python·pdf
TextIn智能文档云平台1 天前
从散乱资料到智能知识库:基于TextIn与Coze的RAG实战
人工智能·pdf·知识库·rag·coze·文档解析
leoufung1 天前
题目介绍:LeetCode 79. Word Search
leetcode·word·深度优先