How to convert docx into pdf with Java? (#14273)

This commit is contained in:
Michael Olayemi 2023-06-23 14:08:20 +00:00 committed by GitHub
parent 0db9d92596
commit 0c017b4b0e
3 changed files with 35 additions and 0 deletions

BIN
pdf/input.docx Normal file

Binary file not shown.

BIN
pdf/output.pdf Normal file

Binary file not shown.

View File

@ -0,0 +1,35 @@
package com.baeldung.pdf;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
public class DocxToPDFExample {
public static void main(String[] args) throws IOException, DocumentException {
InputStream docxInputStream = new FileInputStream("input.docx");
try (XWPFDocument document = new XWPFDocument(docxInputStream);
OutputStream pdfOutputStream = new FileOutputStream("output.pdf");) {
Document pdfDocument = new Document();
PdfWriter.getInstance(pdfDocument, pdfOutputStream);
pdfDocument.open();
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
pdfDocument.add(new Paragraph(paragraph.getText()));
}
pdfDocument.close();
}
}
}