1. 程式人生 > >Java word轉換pdf格式

Java word轉換pdf格式

Java 基於aspose將word轉換pdf格式

網上有很多將word文件轉換成pdf格式的例子,如windows平臺安裝外掛,或者linux伺服器上安裝外掛,或者JDK中加入dll等方式,我個人感覺侷限性比較大。如何說?

是不是我在另一個電腦上操作轉換,我就必須安裝一個什麼外掛?是不是我的JDK也必須安裝外掛,換另一臺伺服器是不是也必須要換?

太複雜了,其實有一個JAR包,只要引入,幾句程式碼就能搞定,但是不好的是這個JAR是收費的,並且maven倉庫上不好找到,但是自然會有人出來破解的

JAR包位置:https://pan.baidu.com/s/1oFVzcChH1R_p9SrYHuLzfA

準備工作

建立專案

用IDEA建立一個普通maven專案,pom檔案中做好準備工作,如編譯版本,打包外掛等,後續可以把轉換寫成一個工具,被其他專案引入jar方式使用

 <groupId>com.wordToPdf</groupId>
    <artifactId>converter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>converter</
name
>
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <maven.compiler.source>
1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.6</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>Main</mainClass> </manifest> <!-- 新增本地的jar --> <manifestEntries> <Class-Path>lib/aspose-words-16.8.0-jdk16.jar</Class-Path> <!-- 這個>lib/class-util-1.0.jar 路徑是已經被打包到target/lib裡的,多個包用空格隔開就可以了 --> </manifestEntries> </archive> </configuration> </plugin> </plugins> <resources> <resource> <targetPath>lib/</targetPath> <directory>lib/</directory> <includes> <include>**/aspose-words-16.8.0-jdk16.jar</include> </includes> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.ftl</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> <include>**/*.ftl</include> </includes> <filtering>false</filtering> </resource> </resources> </build>

打包外掛中有兩個特殊的地方,用於將本地jar依賴一起打包,一個是includes標籤,一個是manifestEntries標籤

引入jar包

在專案根目錄(src同級)建立一個資料夾,取名叫lib,將下載好的依賴放進去,滑鼠點選右鍵jar,有個Add as Library選項,點選之後將jar依賴入專案中,右鍵點選lib目錄,有個Mark Directory as選項,滑鼠放上去會跳出二級選單,選擇Resources Root,將資料夾設定為資源路徑

src/main/resource目錄下建立一個XML檔案,取名叫license.xml,主要作用是去除水印以及破解jar包收費限制

<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>

寫轉換的工具類

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

import java.io.*;

/**
 * @Author: ChenBin
 * @Date: 2018/10/17/0017 22:09
 */
public class WordToPdf {

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

    public static void converter(String resource, String targer){
        // 驗證License
        if (!getLicense()) {
            return;
        }

        try {
            long old = System.currentTimeMillis();
            File inputFile = new File(resource);
            InputStream inputStream = new FileInputStream(inputFile);
            Document doc = new Document(inputStream);
            File outPut = new File(targer);
            OutputStream outputStream = new FileOutputStream(outPut);
            doc.save(outputStream, SaveFormat.PDF);
            long now = System.currentTimeMillis();
            System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒");
            System.out.println("檔案儲存在:" + outPut.getPath());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

這麼一個簡單的程式就完成了檔案轉換,重要是利用Java IO流,將檔案目標讀取,再進行轉換,再利用流寫出

實際運用到專案中

以上只是完成了一個準備,做了一個轉換工具,但是實際執行到專案中的時候,就滿足不了需求,這個時候就要再寫一個Java類,用於擴充套件

public class Converter {
    //系統臨時路徑,用於儲存word檔案和pdf檔案
    private static String CONVERT_FILE_DIR = System.getProperty("java.io.tmpdir");

    private static FileManagerClient fileManagerClient = new DefaultFileManagerClient(false);

    private byte[] download(String path){
        byte[] data = null;
        Result<byte[]> result = fileManagerClient.download(path);
        if (result.getData() != null){
            data = result.getData();
        }
        return data;
    }

    private String upload(byte[] data, String fileName){
        String path = "";
        Result<FileItem> result = fileManagerClient.upload(data, fileName);
        if (result.getData() != null){
            path = result.getData().getVirtualPath();
        }
        return path;
    }
    
	//外部引入呼叫此方法進行轉換以及獲取上傳後的路徑地址
    public String startConverter(String path) {
        //傳入下載地址,下載檔案並用流寫入臨時資料夾
        byte[] downData = this.download(path);
        //儲存到本地的絕對路徑(系統臨時路徑 + 檔名)
        String srcFilePath = CONVERT_FILE_DIR.concat(File.separator).concat(fileName) ;
        File srcFile = new File(srcFilePath);
        OutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(srcFile);
            fileOutputStream.write(downData) ;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                fileOutputStream.flush();
                fileOutputStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //寫入完成後定義轉換後的檔案路徑
        //開始轉換並上傳伺服器返回上傳後的路徑
        String outFilePath = srcFilePath.substring(0, srcFilePath.lastIndexOf(".")).concat(".pdf");
        //轉換
        WordToPdf.converter(srcFilePath, outFilePath);
        String uploadFileName = fileName.substring(0, fileName.lastIndexOf(".")).concat(".pdf");
        byte[] uploadBytes = null;
        try {
            InputStream in = new FileInputStream(outFilePath);
            uploadBytes = toByteArray(in);
            in.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        String uploadPath = this.upload(uploadBytes, uploadFileName);
        return uploadPath;
    }

    private byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }
}

檔案上傳下載的工具類大家自行補充,主要是傳入一個檔案下載地址,將檔案下載並且寫入到本地臨時資料夾中,因為轉換工具類中需要兩個引數,一個原始檔路徑和轉換後文件路徑。再通過剛寫好的轉換工具類,將下載好的檔案通用IO讀取,轉換成pdf後被儲存到指定路徑,由於我上傳的工具類是需要傳入位元組陣列,所以將轉換後的檔案用IO讀取,利用ByteArrayOutputStream轉換成byte陣列,再上傳到伺服器,返回上傳後的路徑地址。