java pdf转成word
时间: 2024-04-19 12:22:46 浏览: 181
在Java中,将PDF文件转换为Word文件可以使用第三方库Apache PDFBox和Apache POI来实现。下面是一个简单的示例代码:
```java
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.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class PdfToWordConverter {
public static void main(String[] args) {
String pdfFilePath = "path/to/input.pdf";
String wordFilePath = "path/to/output.docx";
try {
PDDocument document = PDDocument.load(new File(pdfFilePath));
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
XWPFDocument wordDocument = new XWPFDocument();
XWPFParagraph paragraph = wordDocument.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText(text);
FileOutputStream out = new FileOutputStream(wordFilePath);
wordDocument.write(out);
out.close();
System.out.println("PDF转换为Word成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码使用Apache PDFBox库将PDF文件中的文本提取出来,然后使用Apache POI库创建一个Word文档,并将提取的文本写入到Word文档中。请确保已经将相关的依赖库添加到项目中。
阅读全文