/**
  * Returns the format for the file passed as a parameter.
  *
  * <p>We will ask the mimetype registry service to sniff its mimetype.
  *
  * @return DocumentFormat for the given file
  */
 private static DocumentFormat getSourceFormat(
     OfficeDocumentConverter documentConverter, File file) {
   MimetypeRegistry mimetypeRegistry = Framework.getService(MimetypeRegistry.class);
   String mimetypeStr = mimetypeRegistry.getMimetypeFromFile(file);
   DocumentFormat format = documentConverter.getFormatRegistry().getFormatByMediaType(mimetypeStr);
   return format;
 }
 private boolean commonOfficeDoc2Pdf(File inputFile, File outputFile) {
   try {
     DocumentFormat opf = converter.getFormatRegistry().getFormatByExtension("pdf");
     logger.info("start converting...");
     converter.convert(inputFile, outputFile, opf);
     return true;
   } catch (Exception cex) {
     cex.printStackTrace();
     return false;
   } finally {
     // close the connection
     if (officeManager != null) {
       logger.info("converting processing has done: " + inputFile.getName());
       // officeManager.stop();
     }
   }
 }
  @Override
  public void startConvertion() {

    OfficeDocumentConverter converter =
        new OfficeDocumentConverter(ConverterFactoryOffice.getOfficeManager());
    _logger.debug("Start converting " + source.getName());
    long startTime = System.currentTimeMillis();
    try {
      converter.convert(source, target);
      setModificationDate();
      target.copyTo(target.replaceExtention(Constants.TXT));
      target.deleteOnExit();
      success = true;
    } catch (OfficeException e) {
      close();
      _logger.error(e.getMessage());
    }
    _logger.debug("convertion time: " + (System.currentTimeMillis() - startTime) + " ms");
  }
 /**
  * Returns the destination format for the given plugin.
  *
  * <p>It takes the actual destination mimetype from the plugin configuration.
  *
  * @param sourceFormat the source format
  * @param pdfa1 true if PDF/A-1 is required
  */
 protected DocumentFormat getDestinationFormat(
     OfficeDocumentConverter documentConverter, DocumentFormat sourceFormat, boolean pdfa1) {
   String mimeType = getDestinationMimeType();
   DocumentFormat destinationFormat =
       documentConverter.getFormatRegistry().getFormatByMediaType(mimeType);
   if ("application/pdf".equals(mimeType)) {
     destinationFormat = extendPDFFormat(sourceFormat, destinationFormat, pdfa1);
   }
   return destinationFormat;
 }
  /**
   * 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice
   *
   * @param sourceFile 源文件,绝对路径. 可以是Office2003-2007全部格式的文档, Office2010的没测试. 包括.doc, .docx, .xls,
   *     .xlsx, .ppt, .pptx等.
   * @param destFile 目标文件.绝对路径.
   */
  public static void word2pdf(String inputFilePath) {
    DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();

    String officeHome = getOfficeHome();
    config.setOfficeHome(officeHome);

    OfficeManager officeManager = config.buildOfficeManager();
    officeManager.start();

    OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
    String outputFilePath = getOutputFilePath(inputFilePath);
    File inputFile = new File(inputFilePath);
    if (inputFile.exists()) { // 找不到源文件, 则返回
      File outputFile = new File(outputFilePath);
      if (!outputFile.getParentFile().exists()) { // 假如目标路径不存在, 则新建该路径
        outputFile.getParentFile().mkdirs();
      }
      converter.convert(inputFile, outputFile);
    }

    officeManager.stop();
  }
  @Override
  public void afterPropertiesSet() throws Exception {
    System.out.println("******************");
    // 启动libreoffice进程 Windows平台需要启动,linux不需要启动
    if (PlatformUtils.isWindows()) {
      String command =
          "cmd /c soffice --headless --accept=\"socket,host=127.0.0.1,port=8100;urp\" --nofirststartwizard";
      Runtime runtime = Runtime.getRuntime();
      runtime.exec(command);
    }

    officeManager = configuration.buildOfficeManager();
    converter = new OfficeDocumentConverter(officeManager);
    customDocumentFormatRegistry = (SimpleDocumentFormatRegistry) converter.getFormatRegistry();

    /*
     * // TODO:这里可以增加OpenOffice支持的文件类型 异常json
     * customDocumentFormatRegistry.addFormat(new
     * DocumentFormat("OpenOffice.org 1.0 Template", "sxd",
     * "application/vnd.sun.xml.draw"));
     * customDocumentFormatRegistry.addFormat(new
     * DocumentFormat("OpenOffice.org 1.0 Template", "odf",
     * "application/vnd.oasis.opendocument.formula"));
     */
    DocumentFormat txt = new DocumentFormat("Java", "java", "text/plain");
    txt.setInputFamily(DocumentFamily.TEXT);
    Map<String, Object> txtLoadAndStoreProperties = new LinkedHashMap<String, Object>();
    txtLoadAndStoreProperties.put("FilterName", "Text (encoded)");
    txtLoadAndStoreProperties.put("FilterOptions", "utf8");
    txt.setLoadProperties(txtLoadAndStoreProperties);
    txt.setStoreProperties(DocumentFamily.TEXT, txtLoadAndStoreProperties);
    customDocumentFormatRegistry.addFormat(txt);

    // 添加wps格式
    customDocumentFormatRegistry.addFormat(
        new DocumentFormat("wps文字", "wps", "application/msword")); // wps文字
    customDocumentFormatRegistry.addFormat(
        new DocumentFormat("wps表格", "et", "application/msword")); // wps表格
    customDocumentFormatRegistry.addFormat(
        new DocumentFormat("wps演示", "dps", "application/msword")); // wps演示
    // 启动officeManager,保持在Bean的生命周期中一直在启动状态
    officeManager.start();
  }
  @Override
  public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters)
      throws ConversionException {
    blobHolder = new UTF8CharsetConverter().convert(blobHolder, parameters);
    Blob inputBlob = blobHolder.getBlob();
    String blobPath = blobHolder.getFilePath();
    if (inputBlob == null) {
      return null;
    }

    OfficeDocumentConverter documentConverter = newDocumentConverter();
    // This plugin do deal only with one input source.
    String sourceMimetype = inputBlob.getMimeType();

    boolean pdfa1 = parameters != null && Boolean.TRUE.equals(parameters.get(PDFA1_PARAM));

    File sourceFile = null;
    File outFile = null;
    File[] files = null;
    try {

      // If the input blob has the HTML mime type, make sure the
      // charset meta is present, add it if not
      if ("text/html".equals(sourceMimetype)) {
        inputBlob = checkCharsetMeta(inputBlob);
      }

      // Get original file extension
      String ext = inputBlob.getFilename();
      int dotPosition = ext.lastIndexOf('.');
      if (dotPosition == -1) {
        ext = ".bin";
      } else {
        ext = ext.substring(dotPosition);
      }
      // Copy in a file to be able to read it several time
      sourceFile = Framework.createTempFile("NXJOOoConverterDocumentIn", ext);
      InputStream stream = inputBlob.getStream();
      FileUtils.copyToFile(stream, sourceFile);
      stream.close();

      DocumentFormat sourceFormat = null;
      if (sourceMimetype != null) {
        // Try to fetch it from the registry.
        sourceFormat = getSourceFormat(documentConverter, sourceMimetype);
      }
      // If not found in the registry or not given as a parameter.
      // Try to sniff ! What does that smell ? :)
      if (sourceFormat == null) {
        sourceFormat = getSourceFormat(documentConverter, sourceFile);
      }

      // From plugin settings because we know the destination
      // mimetype.
      DocumentFormat destinationFormat =
          getDestinationFormat(documentConverter, sourceFormat, pdfa1);

      // allow HTML2PDF filtering

      List<Blob> blobs = new ArrayList<>();

      if (descriptor.getDestinationMimeType().equals("text/html")) {
        String tmpDirPath = getTmpDirectory();
        File myTmpDir = new File(tmpDirPath + "/JODConv_" + System.currentTimeMillis());
        boolean created = myTmpDir.mkdir();
        if (!created) {
          throw new IOException("Unable to create temp dir");
        }

        outFile =
            new File(
                myTmpDir.getAbsolutePath()
                    + "/"
                    + "NXJOOoConverterDocumentOut."
                    + destinationFormat.getExtension());

        created = outFile.createNewFile();
        if (!created) {
          throw new IOException("Unable to create temp file");
        }

        log.debug("Input File = " + outFile.getAbsolutePath());
        // Perform the actual conversion.
        documentConverter.convert(sourceFile, outFile, destinationFormat);

        files = myTmpDir.listFiles();
        for (File file : files) {
          // copy the files to a new tmp location, as we'll delete them
          Blob blob;
          try (FileInputStream in = new FileInputStream(file)) {
            blob = Blobs.createBlob(in);
          }
          blob.setFilename(file.getName());
          blobs.add(blob);
          // add a blob for the index
          if (file.getName().equals(outFile.getName())) {
            Blob indexBlob;
            try (FileInputStream in = new FileInputStream(file)) {
              indexBlob = Blobs.createBlob(in);
            }
            indexBlob.setFilename("index.html");
            blobs.add(0, indexBlob);
          }
        }

      } else {
        outFile =
            Framework.createTempFile(
                "NXJOOoConverterDocumentOut", '.' + destinationFormat.getExtension());

        // Perform the actual conversion.
        documentConverter.convert(sourceFile, outFile, destinationFormat, parameters);

        Blob blob;
        try (FileInputStream in = new FileInputStream(outFile)) {
          blob = Blobs.createBlob(in, getDestinationMimeType());
        }
        blobs.add(blob);
      }
      return new SimpleCachableBlobHolder(blobs);
    } catch (IOException e) {
      String msg =
          String.format(
              "An error occurred trying to convert file %s to from %s to %s",
              blobPath, sourceMimetype, getDestinationMimeType());
      throw new ConversionException(msg, e);
    } finally {
      if (sourceFile != null) {
        sourceFile.delete();
      }
      if (outFile != null) {
        outFile.delete();
      }

      if (files != null) {
        for (File file : files) {
          if (file.exists()) {
            file.delete();
          }
        }
      }
    }
  }
 /**
  * Returns the DocumentFormat for the given mimetype.
  *
  * @return DocumentFormat for the given mimetype
  */
 private static DocumentFormat getSourceFormat(
     OfficeDocumentConverter documentConverter, String mimetype) {
   return documentConverter.getFormatRegistry().getFormatByMediaType(mimetype);
 }