如何使用POI将.doc / .docx转换为java中的pdf ..?

时间:2015-09-02 07:57:19

标签: java apache-poi ms-office

  

如何将ms-document转换为PDF,是否有任何示例请分享   和我一起..谢谢。

1 个答案:

答案 0 :(得分:1)

如果你被要求使用POI我想你应该看看org.apache.poi.hwpf.converter
我从来没有试过这个,但我想这至少值得一试。 您似乎可以使用WordToFoConverter将XWPFDocument转换为FO文件(example here)。
从那里你可以使用apach FOP将FO文件转换为这样的PDF:

// Step 1: Construct a FopFactory
// (reuse if you plan to render multiple documents!)
FopFactory fopFactory = FopFactory.newInstance();

// Step 2: Set up output stream.
// Note: Using BufferedOutputStream for performance reasons (helpful with FileOutputStreams).
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("C:/Temp/myfile.pdf")));

try {
  // Step 3: Construct fop with desired output format
  Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);

  // Step 4: Setup JAXP using identity transformer
  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer transformer = factory.newTransformer(); // identity transformer

  // Step 5: Setup input and output for XSLT transformation
  // Setup input stream
  Source src = new StreamSource(new File("C:/Temp/myfile.fo"));

  // Resulting SAX events (the generated FO) must be piped through to FOP
  Result res = new SAXResult(fop.getDefaultHandler());

  // Step 6: Start XSLT transformation and FOP processing
  transformer.transform(src, res);

} finally {
  //Clean-up
  out.close();
}

此代码取自https://xmlgraphics.apache.org/fop/0.95/embedding.html,如果您想了解有关此主题的更多信息。

相关问题