使用JAVA将PDF转WORD

  • Post author:
  • Post category:java


添加依赖


        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.22</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.0.0</version>
        </dependency>

代码

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PdfToWordConverter {

    public static void main(String[] args) throws IOException {
        File file = new File("./input.pdf");
        convertToWord(file, new File("./output.docx"));
    }

    public static String extractTextFromPdf(File file) throws IOException {
        PDDocument document = PDDocument.load(file);
        PDFTextStripper stripper = new PDFTextStripper();
        String text = stripper.getText(document);
        document.close();
        return text;
    }
    
    public static void convertToWord(File pdf, File docx) throws IOException {
        String text = extractTextFromPdf(pdf);
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        FileOutputStream out = new FileOutputStream(docx);
        document.write(out);
        out.close();
        document.close();
    }

}



版权声明:本文为qianzhitu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。