有時我們可能會遇到下圖這樣一種情況 — 我們需要的資料或教程被分成了幾部分存放在多個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(); } } } |
效果圖:
二、根據(jù)指定頁面范圍拆分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.
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/Yesi/p/5604166.html