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—