1.添加依赖
<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.示例代码
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。这种方法适合简单的文本和格式。