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

相关推荐
复园电子13 小时前
跨平台PDF签名解析器设计:多方签署与自签名证书(野鸡CA)过滤
pdf·电子合同
zavoryn16 小时前
Word 图片如何进入 RAG:Apache POI、MinIO 与 URL 映射
word·agent·rag
AI导出鸭PC端16 小时前
预览即导出:告别AI文档格式崩塌,网页预览效果1:1落地Word
人工智能·pdf·word·流程图·豆包·ai导出鸭
hu556679816 小时前
小规模纳税人财务报表报送后如何导出报送pdf
pdf
__zRainy__16 小时前
基于计数信号量(Counting Semaphore)的 PDF 渲染并发控制方案
pdf
工具派19 小时前
从 git commit 到交付 PDF:我的一条在线工具流实录
git·elasticsearch·pdf
Li Ming&1 天前
Python办公自动化:利用Python批量将PDF转换为图片文件
python·pdf·pip
asdzx671 天前
使用 Python 精准操控 Word 字体:获取与替换方案
python·c#·word
ji_shuke1 天前
Vue3 前端批量打印 PDF/图片踩坑记:跨域、合并打印、对话框闪退与按钮一直 loading
前端·pdf·状态模式·pdf打印
Am-Chestnuts1 天前
Mermaid流程图怎么导出Word/PDF?DS随心转批量保存AI多轮修改与源码
pdf·aigc·word·流程图