How can I convert a Word document to PDF?

前端 未结 11 694
深忆病人
深忆病人 2020-11-28 20:39

How can I convert a Word document to PDF where the document contains various things, such as tables. When trying to use iText, the original document looks different to the c

11条回答
  •  感情败类
    2020-11-28 21:11

    Using JACOB call Office Word is a 100% perfect solution. But it only supports on Windows platform because need Office Word installed.

    1. Download JACOB archive (the latest version is 1.19);
    2. Add jacob.jar to your project classpath;
    3. Add jacob-1.19-x32.dll or jacob-1.19-x64.dll (depends on your jdk version) to ...\Java\jdk1.x.x_xxx\jre\bin
    4. Using JACOB API call Office Word to convert doc/docx to pdf.

      public void convertDocx2pdf(String docxFilePath) {
      File docxFile = new File(docxFilePath);
      String pdfFile = docxFilePath.substring(0, docxFilePath.lastIndexOf(".docx")) + ".pdf";
      
      if (docxFile.exists()) {
          if (!docxFile.isDirectory()) { 
              ActiveXComponent app = null;
      
              long start = System.currentTimeMillis();
              try {
                  ComThread.InitMTA(true); 
                  app = new ActiveXComponent("Word.Application");
                  Dispatch documents = app.getProperty("Documents").toDispatch();
                  Dispatch document = Dispatch.call(documents, "Open", docxFilePath, false, true).toDispatch();
                  File target = new File(pdfFile);
                  if (target.exists()) {
                      target.delete();
                  }
                  Dispatch.call(document, "SaveAs", pdfFile, 17);
                  Dispatch.call(document, "Close", false);
                  long end = System.currentTimeMillis();
                  logger.info("============Convert Finished:" + (end - start) + "ms");
              } catch (Exception e) {
                  logger.error(e.getLocalizedMessage(), e);
                  throw new RuntimeException("pdf convert failed.");
              } finally {
                  if (app != null) {
                      app.invoke("Quit", new Variant[] {});
                  }
                  ComThread.Release();
              }
          }
      }
      

      }

提交回复
热议问题