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

相关推荐
小*-^-*九12 小时前
php 使用html 生成pdf word wkhtmltopdf 系列2
pdf·html·php
千册16 小时前
pyside6 的pdf显示测试 -- 01
开发语言·python·pdf
qq_1728055919 小时前
Go 语言 PDF 生成库综合比较与实践指南
开发语言·golang·pdf
E_ICEBLUE1 天前
如何使用 OCR 提取扫描件 PDF 的文本(Python 实现)
java·数据库·pdf
FlYFlOWERANDLEAF1 天前
DevExpress中Word Processing Document API学习记录
学习·c#·word
AnySpaceOne1 天前
PDF转Word在线转换教程:多种实用方法分享
学习·pdf·word
勘察加熊人2 天前
python将pdf转txt,并切割ai
数据库·python·pdf
@小匠2 天前
iText与OpenPDF使用差异及中文处理完全指南
java·pdf
ks胤墨2 天前
Stirling PDF与cpolar:居家办公的云端PDF处理解决方案
pdf
sc_yhsheng2 天前
18j621-3通风天窗图集pdf(免费高清版)
windows·pdf