C# 合併及拆分PDF檔案
阿新 • • 發佈:2020-06-28
謝大哥
https://www.cnblogs.com/Yesi/p/5604166.html
免費版http://www.e-iceblue.com/Introduce/free-pdf-component.html
C#合併及拆分PDF檔案
有時我們可能會遇到下圖這樣一種情況 — 我們需要的資料或教程被分成了幾部分存放在多個PDF檔案中,不管是閱讀還是儲存都不是很方便,這時我們肯定想要把這些PDF檔案合併為一個PDF檔案。相對應的,有時候我們也需要拆分一個大的PDF檔案,來從中獲取我們需要的那一部分資料。這篇文章主要分享如何使用C#來將多個PDF檔案合併為一個PDF檔案以及將一個PDF檔案拆分為多個PDF檔案。
合併PDF檔案
合併PDF檔案的程式碼很簡單,主要分為三步,首先獲取需要合併的PDF檔案,然後呼叫public static PdfDocumentBase MergeFiles(string[] InputFiles)方法,將這些PDF檔案合併,然後儲存檔案。
程式碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System;
using Spire.Pdf;
namespace 合併PDF檔案
{
class Program
{
static void Main( string [] args)
{
String[] files = new String[] { "檔案1.pdf" , "檔案2.pdf" , "檔案3.pdf" };
string outputFile = "輸出.pdf" ;
PdfDocumentBase doc = PdfDocument.MergeFiles(files);
doc.Save(outputFile, FileFormat.PDF);
System.Diagnostics.Process.Start(outputFile);
}
}
}
|
合併前:
合併後:
拆分PDF檔案
在拆分PDF檔案時,我們可以選擇將檔案的每一頁單獨拆分為一個PDF檔案,還可以設定頁碼範圍,將其拆分為多個PDF檔案。下面將分兩個部分來介紹。
一、將PDF檔案的每一頁拆分為一個單獨的PDF檔案
在上一個部分中,合併後的PDF檔案一共有4頁,這裡我將它的每一頁拆分為一個單獨的PDF檔案。
程式碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System;
using Spire.Pdf;
namespace 拆分PDF檔案1
{
class Program
{
static void Main( string [] args)
{
PdfDocument doc = new PdfDocument( "輸出.pdf" );
String pattern = "拆分-{0}.pdf" ;
doc.Split(pattern);
doc.Close();
}
}
}
|
效果圖:
二、根據指定頁面範圍拆分PDF檔案
這裡我將一個18頁的PDF檔案的前10頁拆分為一個PDF檔案,後8頁拆分為另一個PDF檔案。
程式碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace 拆分PDF檔案2
{
class Program
{
static void Main( string [] args)
{
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile( "各種點心的做法.pdf" );
PdfDocument pdf1 = new PdfDocument();
PdfPageBase page;
for ( int i = 0; i < 10; i++)
{
page = pdf1.Pages.Add(pdf.Pages[i].Size, new PdfMargins(0));
pdf.Pages[i].CreateTemplate().Draw(page, new PointF(0, 0));
}
pdf1.SaveToFile( "DOC_1.pdf" );
PdfDocument pdf2 = new PdfDocument();
for ( int i = 10; i < 18; i++)
{
page = pdf2.Pages.Add(pdf.Pages[i].Size, new PdfMargins(0));
pdf.Pages[i].CreateTemplate().Draw(page, new PointF(0, 0));
}
pdf2.SaveToFile( "DOC_2.pdf" );
}
}
}
|
拆分前:
拆分後:
Note:這裡我使用了一個PDF元件Spire.PDF.