Java 建立PDF檔案包的2種方法

iceblue發表於2021-07-06

1. 概述

PDF檔案包可方便在僅開啟一個視窗的情況下閱讀多個文件,通過將多個PDF文件或其他非PDF文件封裝在一起,開啟檔案包後可以隨意切換檢視檔案包中的文件,在需要編輯更改的情況,也可以開啟文字包中的文件進行編輯。下面,通過Java程式來演示如何來建立PDF檔案包。這裡分以下兩種情況來新增,方法類似。

(1)建立檔案包,新增資料夾(父/子資料夾),並新增文件到檔案包

(2)建立檔案包,新增多個文件到檔案包

 

2. 本次執行環境

  • 程式碼編譯環境:IntelliJ IDEA
  • JDK版本:1.8.0
  • PDF jar包工具:Free Spire.PDF for Java(免費版)
  • 測試使用的文件包括:Word文件(.docx2013)、Excel文件(.xlsx2013)、PPT文件(.pptx2013)、PDF文件、txt文件、png圖片等

【Jar包匯入參考步驟】

①. 手動匯入:Project Structure(Shift+Ctrl+Alt+S)開啟的介面中選擇【Modules】—【Dependencies】,點選“+”,【JARs or directories…】,選擇本地路徑中的jar包,新增後,勾選,點選“OK”。

②.  Maven匯入:在pom.xml檔案中配置maven倉庫路徑並指定free spire.pdf.jar 的依賴,然後匯入。具體配置內容如下:

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf.free</artifactId>
        <version>4.4.1</version>
    </dependency>
</dependencies>

 

3. 示例

Java示例程式碼1-建立檔案包時,建立父級/子資料夾,並新增文件到資料夾

 

Java示例程式碼2-建立檔案包,新增多個文件到檔案包

import com.spire.pdf.*;

public class Portfolio2 {
    public static void main(String[] args) {
        String[] files = new String[] { "sample.pdf", "sample.docx", "sample.xlsx","sample.pptx","sample.txt","sample.png" };

        //建立PdfDocument例項
        PdfDocument pdf = new PdfDocument();

        for (int i = 0; i < files.length; i++)
        {
            //建立PDF檔案包並新增檔案
            pdf.getCollection().addFile(files[i]);
        }

        //儲存文件
        pdf.saveToFile("PortfolioWithFiles.pdf", FileFormat.PDF);
        pdf.dispose();
    }
}

 

—End—

 

相關文章