1

我正在使用以下代码使用以下代码片段将 PDF 文件转换为 MS Word 文档。

import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.SimpleTextExtractionStrategy;
import com.itextpdf.text.pdf.parser.TextExtractionStrategy;

public class PdfToDoc {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        //Create the word document
        XWPFDocument doc = new XWPFDocument();
        // Open the pdf file
        String pdf = "D:\\Payment.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("D:\\myfile.doc");
        doc.write(out);
        // Close all open files
        out.close();
        reader.close();
    }
}

但是所有格式都在生成的文档中丢失。谁能建议我保留原始文本格式的方式。

4

0 回答 0