1. 程式人生 > 其它 >今日學習內容總結3.0

今日學習內容總結3.0

package cn.net.cobot.health.web.export.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.commons.lang3.StringUtils;
import org.apache.tika.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.PdfSaveOptions;
import com.aspose.words.SaveFormat;

import cn.net.cobot.health.web.util.report.AsposeUtil;

public class AsposeHelper { private static Logger logger = LoggerFactory.getLogger(AsposeHelper.class); /** * word轉pdf * * @param wordPath word檔案路徑-含副檔名 * @param pdfPath 轉換後pdf檔案儲存的路徑-含副檔名 * @param includeBookmark 轉換後的pdf檔案中是否包含目錄 * @return String<br> * 為null,成功<br> * 不是null,失敗資訊
*/ public static String convertWord2Pdf(String wordPath, String pdfPath, boolean includeBookmark) { try { getLicense(); } catch (Exception e) { //if (logger.isErrorEnabled()) { logger.error("aspose license無效", e); //} return
"aspose license無效"; } if (StringUtils.isBlank(wordPath) || StringUtils.isBlank(pdfPath)) { String err = "引數無效:請指定word檔名或者pdf檔名"; //if (logger.isErrorEnabled()) { logger.error(err); //} return err; } String ret = null; long st = System.currentTimeMillis(); File pdfFile = new File(pdfPath); Document asposeDoc = null; FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(pdfFile); asposeDoc = new Document(wordPath); PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); // 輸出pdf格式文件 pdfSaveOptions.setSaveFormat(SaveFormat.PDF); if (includeBookmark) { // 設定3級doc書籤需要儲存到pdf的heading中 pdfSaveOptions.getOutlineOptions().setHeadingsOutlineLevels(4); // 設定pdf中預設展開1級 pdfSaveOptions.getOutlineOptions().setExpandedOutlineLevels(1); } asposeDoc.save(outputStream, pdfSaveOptions); long end = System.currentTimeMillis(); if (logger.isInfoEnabled()) { logger.info("word轉pdf[{}目錄]:{},用時{}ms", (includeBookmark ? "" : "不含"), wordPath, (end - st)); } ret = null; } catch (Exception e) { //if (logger.isErrorEnabled()) { logger.info("word轉pdf異常[" + (includeBookmark ? "" : "不含") + "目錄]:" + wordPath, e); //} ret = "word轉pdf異常"; } finally { IOUtils.closeQuietly(outputStream); } return ret; } private static void getLicense() throws Exception { try (InputStream is = AsposeUtil.class.getClassLoader() .getResourceAsStream("Aspose.Total.Product.Family.lic")) { License license = new License(); license.setLicense(is); } } }