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

相关推荐
开开心心_Every13 小时前
家常菜谱软件推荐:分类齐全无广告步骤详细
linux·运维·服务器·华为od·edge·pdf·华为云
开开心心就好13 小时前
键盘映射工具改键位,绿色版设置后重启生效
网络·windows·tcp/ip·pdf·计算机外设·电脑·excel
cuber膜拜13 小时前
Marp CLI快速入门
pdf·npm·markdown·ppt·marp
reasonsummer14 小时前
【办公类-53-09】20260131Python模仿制作2025学年第二学期校历(excel+pdf)
python·pdf
心语星光15 小时前
用python语言的pyautogui库实现伪批量将xdf文件打印为pdf文件
开发语言·python·pdf·自动化
iReachers15 小时前
PDF一机一码加密大师1.1.0更新至2026最新版, 强力加密PDF, 无需额外安装阅读器, 附CSDN下载地址
pdf
GiantGo1 天前
一键导出PPT备注到Word
word·powerpoint·导出备注
初九之潜龙勿用1 天前
C# 操作Word模拟解析HTML标记之背景色
开发语言·c#·word·.net·office
web打印社区1 天前
前端开发实现PDF打印需求:从基础方案到专业解决方案
前端·vue.js·react.js·electron·pdf
Kratzdisteln1 天前
【MCM】(x= (N_A),y=(N_G),z=(p))RGB=T*
pdf