2016-11-30 33 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 –