import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class PdfToWordExample {
public static void main(String[] args) throws IOException {
// 创建PDF文件对象
File file = new File("example.pdf");
PDDocument document = PDDocument.load(file);
// 创建PDF文本剥离器
PDFTextStripper stripper = new PDFTextStripper();
// 将PDF内容提取为字符串
String text = stripper.getText(document);
// 创建Word文档对象
HWPFDocument wordDocument = new HWPFDocument();
// 创建段落对象
Paragraph para = wordDocument.createParagraph();
// 循环遍历PDF文本内容,每读取到一个换行符就创建一个新的段落
for (String line : text.split("\\r?\\n")) {
CharacterRun run = para.createRun();
run.setText(line);
run.addCarriageReturn();
}
// 输出Word文档文件
FileOutputStream out = new FileOutputStream("example.doc");
wordDocument.write(out);
out.close();
// 关闭对象
wordDocument.close();
document.close();
}
}
使用 Java 将 PDF 转换为 Word 文档需要使用第三方工具或 API 实现。 但是可以读取PDF后利用 Apache POI 中的 HWPF 对 Word 文档进行写入,上代码
于 2023-03-23 15:07:45 首次发布