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

相关推荐
不学能干嘛1 小时前
写大论文的word版本格式整理,实现自动生成目录、参考文献序号、公式序号、图表序号
word
菜鸟单飞12 小时前
介绍一款非常实用的PDF阅读软件!
windows·pdf·电脑
一川风絮千片雪14 小时前
【排版教程】如何在Word/WPS中优雅的插入参考文献
word·wps
杜大哥14 小时前
如何在WPS打开的word、excel文件中,使用AI?
人工智能·word·excel·wps
青涩小鱼16 小时前
在WPS中设置word的页码不从第一页开始,从指定页开始插入页码
word·wps
IDRSolutions_CN21 小时前
如何在 PDF 文件中嵌入自定义数据
java·经验分享·pdf·软件工程·团队开发
企鹅侠客1 天前
开源免费文档翻译工具 可支持pdf、word、excel、ppt
人工智能·pdf·word·excel·自动翻译
近冬的阳光2 天前
PDF文档管理系统V2.0
pdf
Driver_tu2 天前
在windows10上基于Python部署marker,实现PDF转markdown文件(保姆级)
pdf
黄铎彦2 天前
使用GDI+、文件和目录和打印API,批量将图片按文件名分组打包成PDF
c++·windows·pdf