poi实现docx转pdf
时间: 2023-08-14 09:06:24 浏览: 44
要实现docx转pdf,可以使用Apache POI和Apache PDFBox两个库。具体步骤如下:
1. 使用POI读取docx文件内容
```
XWPFDocument document = new XWPFDocument(new FileInputStream("example.docx"));
```
2. 将docx内容写入PDF文件
```
PDDocument pdfDoc = new PDDocument();
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPage page = new PDPage();
pdfDoc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page);
contentStream.beginText();
contentStream.setFont(font, 12);
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
contentStream.showText(text);
}
}
contentStream.endText();
contentStream.close();
```
3. 保存PDF文件
```
pdfDoc.save("example.pdf");
pdfDoc.close();
```
完整代码示例:
```
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class DocxToPdf {
public static void main(String[] args) throws IOException {
// Read docx file
XWPFDocument document = new XWPFDocument(new FileInputStream("example.docx"));
// Write pdf file
PDDocument pdfDoc = new PDDocument();
PDFont font = PDType1Font.HELVETICA_BOLD;
PDPage page = new PDPage();
pdfDoc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page);
contentStream.beginText();
contentStream.setFont(font, 12);
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
String text = run.getText(0);
contentStream.showText(text);
}
}
contentStream.endText();
contentStream.close();
// Save pdf file
pdfDoc.save("example.pdf");
pdfDoc.close();
}
}
```
阅读全文