Convert DOC to PDF in Java: Easy Guide

There are many ways to convert a doc to a pdf in Java, here is one of them.

  1. Read the content of a .doc file using Apache POI library.
  2. Use the iText library to write the content read from a doc file to a pdf file.

Here is a simple example code:

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class DocToPdfConverter {
    public static void main(String[] args) {
        try {
            // 读取doc文件
            FileInputStream fis = new FileInputStream("input.doc");
            HWPFDocument doc = new HWPFDocument(fis);
            WordExtractor extractor = new WordExtractor(doc);
            String text = extractor.getText();
            fis.close();

            // 写入pdf文件
            Document pdfDoc = new Document();
            PdfWriter.getInstance(pdfDoc, new FileOutputStream("output.pdf"));
            pdfDoc.open();
            pdfDoc.add(new Paragraph(text));
            pdfDoc.close();

            System.out.println("转换成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

In this example, we start by using the Apache POI library to read the contents of a doc file, and then use the iText library to write the read content to a pdf file. It is important to note that the relevant dependencies of Apache POI and iText need to be included in the project.

bannerAds