2016-11-30 91 views
2

我在寻找到docx文件转换为Java中pdf的最佳方式,这是我已经试过:如何.docx文件转换为pdf在Java中

File wordFile = new File("wordFile.docx"), target = new File("target.pdf"); 
IConverter converter; 
Future<Boolean> conversion = converter.convert(wordFile) 
.as(DocumentType.MS_WORD) 
.to(target) 
.as(DocumentType.PDF) 
.prioritizeWith(1000) // optional 
.schedule(); 

的问题是,我在程序中找不到IConverter类...

回答

3

您明显正在使用documents4j,所以我建议您仔细阅读那里的文档。看来你没有在你的项目中包含documents4j库(你至少需要documents4j-api依赖,但我建议你看看documents4j-local)。

您可以直接使用Maven添加所需的库(仅添加下面的依赖关系)或直接获取jar

<dependency> 
<groupId>com.documents4j</groupId> 
<artifactId>documents4j-api</artifactId> 
<version>1.0.2</version> 
<type>pom</type> 
</dependency> 
+0

你可以给我链接下载documents4j jar文件吗? –

+0

我已经用所需的信息编辑了我的答案。 –

+0

这是什么:“DocumentType.MS_WORD”和“DocumentType.PDF”它不起作用 –

0

我想你试试这个代码,因为它给了我PDF转换器输出文件我不确定有关的准确性。

InputStream is = new FileInputStream(new File("your Docx PAth")); 
      WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage 
        .load(is); 
      List sections = wordMLPackage.getDocumentModel().getSections(); 
      for (int i = 0; i < sections.size(); i++) { 
       wordMLPackage.getDocumentModel().getSections().get(i) 
         .getPageDimensions(); 
      } 
      Mapper fontMapper = new IdentityPlusMapper(); 
      PhysicalFont font = PhysicalFonts.getPhysicalFonts().get(
        "Comic Sans MS");//set your desired font 
      fontMapper.getFontMappings().put("Algerian", font); 
      wordMLPackage.setFontMapper(fontMapper); 
      PdfSettings pdfSettings = new PdfSettings(); 
      org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
        wordMLPackage); 
      //To turn off logger 
      List<Logger> loggers = Collections.<Logger> list(LogManager 
        .getCurrentLoggers()); 
      loggers.add(LogManager.getRootLogger()); 
      for (Logger logger : loggers) { 
       logger.setLevel(Level.OFF); 
      } 
      OutputStream out = new FileOutputStream(new File("Your OutPut PDF path")); 
      conversion.output(out, pdfSettings); 
      System.out.println("DONE!!"); 

希望这个解决方案对你的问题会很好。 谢谢!

+0

我刚刚得到这个东西一旦阅读www.docx4java.org/,我希望你会在这里找到更多。 –

+0

使用docx4j jar和一些支持jar –