我已经成功地使用Java将JPEG转换为Pdf,但不知道如何使用Java将Pdf转换为Word,转换JPEG到Pdf的代码如下所示。
谁能告诉我如何使用Java将Pdf转换为Word (.doc/ .docx)?
import java.io.FileOutputStream;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Document;
public class JpegToPDF {
public static void main(String[] args) {
try {
Document convertJpgToPdf = new Document();
PdfWriter.getInstance(convertJpgToPdf, new FileOutputStream(
"c:\\java\\ConvertImagetoPDF.pdf"));
convertJpgToPdf.open();
Image convertJpg = Image.getInstance("c:\\java\\test.jpg");
convertJpgToPdf.add(convertJpg);
convertJpgToPdf.close();
System.out.println("Successfully Converted JPG to PDF in iText");
} catch (Exception i1) {
i1.printStackTrace();
}
}
}发布于 2013-08-09 23:22:12
实际上,您需要两个库。这两个库都是开源的。第一个是iText,它用于从PDF文件中提取文本。第二个是POI,用于创建word文档。
代码非常简单:
//Create the word document
XWPFDocument doc = new XWPFDocument();
// Open the pdf file
String pdf = "myfile.pdf";
PdfReader reader = new PdfReader(pdf);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
// Read the PDF page by page
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
TextExtractionStrategy strategy = parser.processContent(i, new SimpleTextExtractionStrategy());
// Extract the text
String text=strategy.getResultantText();
// Create a new paragraph in the word document, adding the extracted text
XWPFParagraph p = doc.createParagraph();
XWPFRun run = p.createRun();
run.setText(text);
// Adding a page break
run.addBreak(BreakType.PAGE);
}
// Write the word document
FileOutputStream out = new FileOutputStream("myfile.docx");
doc.write(out);
// Close all open files
out.close();
reader.close();注意:使用提取策略时,您将丢失所有格式。但是您可以通过插入您自己的、更复杂的提取策略来解决这个问题。
发布于 2013-08-09 23:14:19
你可以使用7-pdf库
看看这个可能会有帮助:
http://www.7-pdf.de/sites/default/files/guide/manuals/library/index.html
PS:当给定的文件是非RGB图像时,itext有一些问题,试试这个!!
发布于 2016-07-20 01:03:49
尽管OpenOffice/LibreOfffice远不是一个纯Java解决方案,但它允许用户通过TCP端口连接到它;它可以用来转换文档。如果这看起来是一个可接受的解决方案,JODConverter可以帮助您。
https://stackoverflow.com/questions/18149857
复制相似问题