【发布时间】:2013-07-23 11:30:53
【问题描述】:
我正在尝试使用 Apache POI 将 doc 转换为 pdf,但生成的 pdf 文档仅包含文本,它没有任何格式,如图像、表格对齐等。
如何将具有表格、图像、对齐等所有格式的 doc 转换为 pdf?
这是我的代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class demo {
public static void main(String[] args) {
POIFSFileSystem fs = null;
Document document = new Document();
try {
System.out.println("Starting the test");
fs = new POIFSFileSystem(new FileInputStream("Resume.doc"));
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
OutputStream file = new FileOutputStream(new File("test.pdf"));
PdfWriter writer = PdfWriter.getInstance(document, file);
Range range = doc.getRange();
document.open();
writer.setPageEmpty(true);
document.newPage();
writer.setPageEmpty(true);
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");
System.out.println("Length:" + paragraphs[i].length());
System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());
// add the paragraph to the document
document.add(new Paragraph(paragraphs[i]));
}
System.out.println("Document testing completed");
} catch (Exception e) {
System.out.println("Exception during test");
e.printStackTrace();
} finally {
// close the document
document.close();
}
}
}
【问题讨论】:
-
生成的 pdf 文档仅包含文本,它没有任何格式,如图像、表格对齐方式 - 您只能获得文本,因为您只使用了
WordExtractor.getParagraphText输出.如果您想提取样式等,则需要考虑更多信息。查看WordToHtmlConverter了解如何提取您需要的所有数据。 -
谢谢你的链接,你能给我一个简单的例子吗?再次感谢。
-
您说您的任务是将 doc 转换为具有所有格式(如表格、图像、对齐方式)的 pdf。 为了进行如此完整的转换,一个示例基本上只能是另一个如此彻底的转换。如果您想要一个更简单的示例,请将您的任务缩减为本质上更简单的东西。不过,我会用更多的解释来回答这个问题。
标签: java pdf pdf-generation apache-poi doc