Java使用Aspose-Words實現Word轉換Pdf

一、在項目中引入Aspose-Words依賴

下載地址:http://pan.baidu.com/s/1nvbJwnv

建議將jar包下載下來並上傳到自己公司的私服裏去

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>15.8.0</version>
</dependency>

二、項目中基於Aspose-Words封裝工具類實現Word轉換Pdf

直接上示例代碼

package com.demo.utils;

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

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

/**
 * Word 轉 Pdf 幫助類
 *
 * 備註:需要引入 aspose-words-15.8.0-jdk16.jar
 */
public class PdfUtil {

    private static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param wordPath 需要被轉換的word全路徑帶文件名
     * @param pdfPath  轉換之後pdf的全路徑帶文件名
     */
    public static void doc2pdf(String wordPath, String pdfPath) {
        // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
        if (!getLicense()) {
            return;
        }
        try {
            long old = System.currentTimeMillis();
            //新建一個pdf文檔
            File file = new File(pdfPath);
            FileOutputStream os = new FileOutputStream(file);
            //Address是將要被轉化的word文檔
            Document doc = new Document(wordPath);
            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互轉換
            doc.save(os, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            os.close();
            //轉化用時
            System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以下是license.xml文件,需要放置在正確的相對路徑下

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

三、使用須知

當文檔中含有中文字符時,該段代碼的執行需要調用操作系統的本地字體庫支持,否則所有中文字符都將亂碼

該段代碼如果想要在Linux服務器上完美運行,需要給Linux服務器安裝中文字體庫

如何在Linux環境安裝Windows字體庫,將在本人的另一篇文章裏詳細講解
Java使用Spire.Pdf或Aspose-Words實現Word轉換Pdf在Linux服務器上的中文亂碼問題

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章