在前面的文章中,我們已經知道如何合併、拆分多個PDF文件,在這篇文章中的合併、拆分PDF文檔主要是以方便文檔管理的目的來操作文檔,在文檔查閱、管理及存儲上很方便實用。但是我們如果想要合併多個文檔中的部分文檔頁的內容,該如何來做呢?可以參考接下來將要介紹的合併方法。
PS: 本篇文章是對Free Spire.PDF 的合併功能的進一步介紹,即如何合併多個PDF文檔中的指定頁(指定單頁、指定多頁)爲一個新文檔
使用工具:Free Spire.PDF for .NET
提示:下載安裝該組件後,注意在項目程序中添加引用Spire.PDF.dll文件
代碼細節可參考以下主要代碼段:
//初始化數組,數組元素爲需要合併的PDF文檔
string[] files = { "sample1.pdf", "sample2.pdf" };
PdfDocument[] docs = new PdfDocument[files.Length];
//遍歷PDF文檔
for (int i = 0; i < files.Length; i++)
{
docs[i] = new PdfDocument();
docs[i].LoadFromFile(files[i]);
}
//創建一個新的PDF文檔並插入從原文檔選取的指定頁
PdfDocument doc = new PdfDocument();
doc.InsertPage(docs[0], 0);//指定單頁(文檔1的第1頁)
doc.InsertPageRange(docs[1], 0, 1);//指定多頁 (文檔2的第1頁和第2頁)
//保存並命名合併後的文檔,同時運行文檔
doc.SaveToFile("Result.pdf");
Process.Start("Result.pdf");
合併前:
合併後:
全部代碼
C#
using Spire.Pdf;
using System.Diagnostics;
namespace MergeSelectedPDFpages
{
class Program
{
static void Main(string[] args)
{
string[] files = { "sample1.pdf", "sample2.pdf" };
PdfDocument[] docs = new PdfDocument[files.Length];
for (int i = 0; i < files.Length; i++)
{
docs[i] = new PdfDocument();
docs[i].LoadFromFile(files[i]);
}
PdfDocument doc = new PdfDocument();
doc.InsertPage(docs[0], 0);
doc.InsertPageRange(docs[1], 0, 1);
doc.SaveToFile("Result.pdf");
Process.Start("Result.pdf");
}
}
}
VB.NET
Imports Spire.Pdf
Imports System.Diagnostics
Namespace MergeSelectedPDFpages
Class Program
Private Shared Sub Main(ByVal args() As String)
Dim files() As String = New String() {"sample1.pdf", "sample2.pdf"}
Dim docs() As PdfDocument = New PdfDocument((files.Length) - 1) {}
Dim i As Integer = 0
Do While (i < files.Length)
docs(i) = New PdfDocument
docs(i).LoadFromFile(files(i))
i = (i + 1)
Loop
Dim doc As PdfDocument = New PdfDocument
doc.InsertPage(docs(0), 0)
doc.InsertPageRange(docs(1), 0, 1)
doc.SaveToFile("Result.pdf")
Process.Start("Result.pdf")
End Sub
End Class
End Namespace
以上內容是本次關於“如何合併PDF文檔指定頁”的全部介紹,如果喜歡,歡迎轉載(轉載請註明出處)
感謝閱讀!