C#實(shí)現(xiàn)一鍵批量合并PDF文檔
前言
由于項(xiàng)目需要編寫大量的材料,以及各種簽字表格、文書等,最后以PDF作為材料交付的文檔格式,過程文檔時(shí)有變化或補(bǔ)充,故此處理PDF文檔已經(jīng)成為日常工作的一部分。
網(wǎng)上有各種PDF處理工具,總是感覺用得不跟手。
最后回顧自己的需求總結(jié)為以下幾項(xiàng):
1、可以便捷、快速的對(duì)多份PDF進(jìn)行合并。
2、可以從源PDF選取指定頁碼進(jìn)行合并。
3、可以從單個(gè)PDF提取特定頁碼(拆分PDF)。
4、對(duì)多個(gè)PDF分組,合并作為最終PDF的導(dǎo)航書簽,可快速定位。
5、統(tǒng)一合成后PDF頁面尺寸,如統(tǒng)一為A4幅面。
6、操作盡量簡(jiǎn)便,支持文件拖放,不需要花巧的東西。
效果展示
首先,我們看看最終成品:

1、可以批量添加多個(gè)PDF到列表框中,也可以資料管理器將文件批量拖進(jìn)來實(shí)現(xiàn)添加。
2、[可選]定義分組標(biāo)題對(duì)文件進(jìn)行分組,也作為合并后PDF的書簽。
3、將列表中PDF批量合并到一個(gè)文件中。如果只有PDF,而且定義了頁碼范圍,則轉(zhuǎn)換為拆分功能。
4、顯示PDF總頁數(shù),如果只需提取部分內(nèi)容,可以定義頁碼范圍。
5、可以更改合并后PDF頁面的尺寸,統(tǒng)一為A4、B4或A5幅面。
功能實(shí)現(xiàn)
搜索發(fā)現(xiàn)github有個(gè)開源的
github.com/schourode/pdfbinder
比較接近想要的效果,本著能省即省、成本最低、能效更高的原則,直接以此為基礎(chǔ)進(jìn)行擴(kuò)展,開發(fā)自身所需的功能。
1、添加文件
這個(gè)比較簡(jiǎn)單,點(diǎn)擊按鈕后彈出選擇對(duì)話框,將選擇的文件逐一加到ListBox中。
private void addFileButton_Click(object sender, EventArgs e)
{
if (addFileDialog.ShowDialog() == DialogResult.OK)
{
foreach (string file in addFileDialog.FileNames)
{
AddInputFile(file);
}
UpdateUI();
}
}
其中AddInputFile函數(shù)單獨(dú)編寫是為了在拖放事件中復(fù)用。
public void AddInputFile(string file)
{
int Pages = 0;
switch (Combiner.TestSourceFile(file, out Pages))
{
case Combiner.SourceTestResult.Unreadable:
MessageBox.Show(string.Format(resources.GetString("Error.Unreadable.Text"), file), resources.GetString("Error.Unreadable.Title"), MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case Combiner.SourceTestResult.Protected:
MessageBox.Show(string.Format(resources.GetString("Error.Protected.Text"), file), resources.GetString("Error.Protected.Title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
break;
case Combiner.SourceTestResult.Ok:
FileListBox.Items.Add(new PdfInfo() { Fullname = file, Filename = Path.GetFileName(file), Ranges = "", TotalPages = Pages });
break;
}
}
這里對(duì)PDF文件有效性進(jìn)行了檢查,而且添加到ListBox的是PdfInfo對(duì)象,它還記錄了總頁數(shù)、提取的頁面范圍等信息。
文件拖放的實(shí)現(xiàn):
private void FileListBox_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop, false) ? DragDropEffects.All : DragDropEffects.None;
}
private void FileListBox_DragDrop(object sender, DragEventArgs e)
{
var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
Array.Sort(fileNames);
foreach (var file in fileNames)
{
AddInputFile(file);
}
UpdateUI();
}
2、文件分組(書簽)
using BookmarkName = System.String;
private void addBookmarkButton_Click(object sender, EventArgs e)
{
//未添加文件不處理
if (FileListBox.SelectedIndex < 0) return;
//如果選擇的書簽(組名),讀取名稱供修改
BookmarkName bookmark = "";
if (FileListBox.SelectedItem is BookmarkName)
bookmark = (BookmarkName)FileListBox.SelectedItem;
else
{
//如果選擇的是文件,提取文件名作默認(rèn)值
bookmark = ((PdfInfo)FileListBox.SelectedItem).Filename;
if (bookmark.Contains("."))
bookmark = bookmark.Substring(0, bookmark.LastIndexOf("."));
}
//如果輸入有效,添加書簽(組名)
BookmarkName newName = Interaction.InputBox(resources.GetString("SetBookmark.Prompt"), resources.GetString("SetBookmark.Title"), bookmark);
if (newName != "")
{
if (FileListBox.SelectedItem is BookmarkName)
FileListBox.Items[FileListBox.SelectedIndex] = newName;
else
{
FileListBox.Items.Insert(FileListBox.SelectedIndex, newName);
BookmarkCounter++;
}
}
}
3、定義頁碼范圍
沒有定義頁碼范圍表示整個(gè)PDF進(jìn)行合并。定義了頁面范圍,合并時(shí)只提取相應(yīng)的頁面進(jìn)行合并。
頁碼范圍的格式與常見的打印功能的頁碼定義相一致,如:1,2,3,6-9。
這個(gè)操作放在右鍵彈出菜單中實(shí)現(xiàn)。
private void mnuSetPageRange_Click(object sender, EventArgs e)
{
PdfInfo item = ((PdfInfo)FileListBox.SelectedItem);
string range = Interaction.InputBox(resources.GetString("SetPageRange.Prompt"), resources.GetString("SetPageRange.Title"), item.Ranges);
//內(nèi)容未變更的不用處理
if (range != item.Ranges)
{
if (range == "")
{
((PdfInfo)FileListBox.Items[FileListBox.SelectedIndex]).Ranges = "";
return;
}
//針對(duì)逗號(hào)和空格做處理
string[] arr = range.Replace(",", ",").Replace(" ", "").Split(',');
range = "";
for (int i = 0; i < arr.Length; i++)
{
//用正則表達(dá)式判斷有效性
if ("" == arr[i]) continue;
if (Regex.IsMatch(arr[i], @"^\d+$") || Regex.IsMatch(arr[i], @"^\d+-\d+$"))
range += ("" == range ? "" : ",") + arr[i];
else
{
MessageBox.Show(resources.GetString("Error.RangeValid"));
return;
}
}
//輸入有效,更新
((PdfInfo)FileListBox.Items[FileListBox.SelectedIndex]).Ranges = range;
UpdateUI();
}
}
4、自定義顯示
為了在ListBox中顯示書簽、總頁數(shù)和提取頁碼范圍,需要接管ListBox的繪制事件。
private void FileListBox_DrawItem(object sender, DrawItemEventArgs e)
{
...
StringFormat Formater = new StringFormat();
Formater.Alignment = StringAlignment.Near;
Formater.LineAlignment = StringAlignment.Center;
Formater.Trimming = StringTrimming.EllipsisPath;
Formater.FormatFlags = StringFormatFlags.NoWrap;
//繪制書簽(分組名)
if (FileListBox.Items[e.Index] is BookmarkName)
{
//繪書簽(分組名)圖標(biāo)
e.Graphics.DrawImage(addBookmarkButton.Image, e.Bounds.X, e.Bounds.Y + ((e.Bounds.Height - addBookmarkButton.Image.Height) /2));
//繪書簽(分組名)
e.Graphics.DrawString((BookmarkName)FileListBox.Items[e.Index], e.Font, Brushes.Black
, new Rectangle(e.Bounds.X + addBookmarkButton.Image.Width, e.Bounds.Y, e.Bounds.Width - RIGHT_MARGIN, e.Bounds.Height), Formater);
return;
}
//繪制PDF文件名
PdfInfo item = (PdfInfo)FileListBox.Items[e.Index];
e.Graphics.DrawString(showNameButton.Checked ? item.Fullname : item.Filename, e.Font, Brushes.Black
, new Rectangle(e.Bounds.X + (BookmarkCounter > 0 ? (int)(addBookmarkButton.Image.Width * 1.5) : 0), e.Bounds.Y, e.Bounds.Width - RIGHT_MARGIN, e.Bounds.Height), Formater);
//繪制頁碼
Formater.Alignment = StringAlignment.Far;
e.Graphics.DrawString((item.Ranges == "" ? "" : item.Ranges + " | ")
+ string.Format(item.TotalPages>1 ? resources.GetString("Pages"): resources.GetString("Page"), item.TotalPages)
, e.Font, Brushes.Gray, e.Bounds, Formater);
}
5、定義頁面尺寸
默認(rèn)是原始尺寸(不做調(diào)整),可根據(jù)需要選擇為A4、A5、B4。
private void OnPageSizeChanged(object sender, EventArgs e)
{
PageSizeButton.Tag = ((ToolStripMenuItem)sender).Tag;
mnuPageSize_Original.Checked = sender == mnuPageSize_Original;
mnuPageSize_A4.Checked = sender == mnuPageSize_A4;
mnuPageSize_A5.Checked = sender == mnuPageSize_A5;
mnuPageSize_B4.Checked = sender == mnuPageSize_B4;
if (mnuPageSize_Original.Checked)
PageSizeButton.Text = resources.GetString("PageSizeButton.Text");
else
PageSizeButton.Text = resources.GetString("PageSizeButton.Text") + ":" + ((ToolStripMenuItem)sender).Text;
}
6、PDF批量合并
這個(gè)比較長(zhǎng),有興趣的可以到github.com/kacarton/PDFBinder2下載源碼自己看,以下摘錄核心部分。
private void combineButton_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
using (var combiner = new Combiner(saveFileDialog.FileName, (PDFBinder.PageSize)PageSizeButton.Tag))
{
progressBar.Visible = true;
this.Enabled = false;
for (int i = 0; i < FileListBox.Items.Count; i++)
{
if (FileListBox.Items[i] is BookmarkName)
combiner.AddBookmark((string)FileListBox.Items[i]);
else
combiner.AddFile(((PdfInfo)FileListBox.Items[i]).Fullname, ((PdfInfo)FileListBox.Items[i]).Ranges);
//刷新進(jìn)度
progressBar.Value = (int)(((i + 1) / (double)FileListBox.Items.Count) * 100);
}
this.Enabled = true;
progressBar.Visible = false;
}
System.Diagnostics.Process.Start(saveFileDialog.FileName);
}
}
class Combiner : IDisposable
{
public void AddFile(string fileName, string range)
{
var reader = new PdfReader(fileName);
....
_document.NewPage();
//添加書簽
if (!string.IsNullOrEmpty(this.BookMarkName))
{
Chapter _chapter = new Chapter("", 1);
_chapter.BookmarkTitle = this.BookMarkName;
_chapter.BookmarkOpen = true;
_document.Add(_chapter);
this.BookMarkName = null;
}
if (_newPageSize == PageSize.Original)
{
var page = _pdfCopy.GetImportedPage(reader, i);
_pdfCopy.AddPage(page);
}
else
{
var page = _writer.GetImportedPage(reader, i);
_document.Add(iTextSharp.text.Image.GetInstance(page));
}
reader.Close();
}
}
7、其他
UI同步、文件移除、上移、下移、排序、多語言支持這些比較簡(jiǎn)單就不展開了。
方法補(bǔ)充
C#使用Spire.PDF for .NET合并PDF
為什么選擇Spire.PDF for .NET
Spire.PDF for .NET 是一款功能全面、性能卓越的PDF處理庫,專為.NET平臺(tái)設(shè)計(jì)。它允許開發(fā)者在C#、VB.NET等語言中輕松創(chuàng)建、編輯、轉(zhuǎn)換、打印和查看PDF文檔,而無需安裝Adobe Acrobat等第三方軟件。
選擇Spire.PDF for .NET進(jìn)行PDF合并的主要原因包括:
- 功能全面: 除了合并,它還支持PDF的拆分、加密、解密、內(nèi)容提取、文本替換、添加水印、數(shù)字簽名等多種操作。
- 性能優(yōu)異: 在處理大量或復(fù)雜的PDF文檔時(shí),Spire.PDF for .NET展現(xiàn)出卓越的穩(wěn)定性和處理速度,有效提升開發(fā)效率。
- 易于集成: 作為一個(gè)純.NET組件,它可以無縫集成到各種.NET應(yīng)用中,如Windows Forms、ASP.NET、WPF以及.NET Core項(xiàng)目。
- 兼容性強(qiáng): 支持從.NET Framework 2.0到.NET 5.0+的多個(gè)版本,并能處理從PDF 1.2到1.7的各種PDF版本。
- 開發(fā)者友好: 提供清晰的API接口和豐富的示例,大大降低了學(xué)習(xí)曲線。
環(huán)境準(zhǔn)備:安裝Spire.PDF for .NET
在使用Spire.PDF for .NET之前,我們需要將其添加到項(xiàng)目中。最簡(jiǎn)便的方式是通過NuGet包管理器在Visual Studio中進(jìn)行安裝。
安裝步驟:
- 打開Visual Studio。
- 在“解決方案資源管理器”中,右鍵點(diǎn)擊您的項(xiàng)目,選擇“管理NuGet程序包...”。
- 在“瀏覽”選項(xiàng)卡中,搜索“Spire.PDF”。
- 找到“Spire.PDF”包,點(diǎn)擊“安裝”。
您也可以通過NuGet包管理器控制臺(tái)運(yùn)行以下命令:
Install-Package Spire.PDF
安裝完成后,Spire.PDF for .NET的引用將自動(dòng)添加到您的項(xiàng)目中。
核心實(shí)現(xiàn):使用C#合并PDF文檔的步驟與代碼
Spire.PDF for .NET 提供了簡(jiǎn)潔而強(qiáng)大的方法來合并PDF文檔。以下是詳細(xì)的步驟和示例代碼:
步驟列表:
- 準(zhǔn)備源PDF文件路徑: 確定您要合并的所有PDF文件的完整路徑。
- 創(chuàng)建字符串?dāng)?shù)組: 將所有源PDF文件的路徑存儲(chǔ)在一個(gè)字符串?dāng)?shù)組中。
- 調(diào)用 PdfDocument.MergeFiles 方法: 使用 PdfDocument.MergeFiles(string[] filePaths, string destFile) 靜態(tài)方法一次性合并所有文件。這個(gè)方法會(huì)直接將合并后的PDF保存到指定的目標(biāo)路徑。
示例代碼塊:
using System;
using Spire.Pdf;
namespace MergePdfDocuments
{
class Program
{
static void Main(string[] args)
{
// 1. 定義源PDF文件路徑數(shù)組
// 請(qǐng)將 "Document1.pdf", "Document2.pdf", "Document3.pdf" 替換為您的實(shí)際文件路徑
string[] sourceFiles = new string[]
{
"C:\Users\YourUser\Desktop\Document1.pdf",
"C:\Users\YourUser\Desktop\Document2.pdf",
"C:\Users\YourUser\Desktop\Document3.pdf"
};
// 2. 定義合并后PDF文檔的輸出路徑
string outputFile = "C:\Users\YourUser\Desktop\MergedDocument.pdf";
try
{
// 3. 使用Spire.Pdf.PdfDocument.MergeFiles方法合并PDF文檔
// 這個(gè)方法是靜態(tài)的,可以直接調(diào)用,它會(huì)處理所有的合并邏輯并將結(jié)果保存到指定文件
PdfDocument.MergeFiles(sourceFiles, outputFile);
Console.WriteLine($"PDF文檔已成功合并到:{outputFile}");
}
catch (Exception ex)
{
Console.WriteLine($"合并PDF文檔時(shí)發(fā)生錯(cuò)誤:{ex.Message}");
}
Console.ReadKey();
}
}
}
代碼解釋:
- using Spire.Pdf; 導(dǎo)入了Spire.PDF庫的命名空間,以便訪問其提供的類和方法。
- string[] sourceFiles 數(shù)組包含了所有待合并的PDF文件的完整路徑。您可以根據(jù)需要添加或刪除文件。
- string outputFile 定義了合并后新PDF文檔的保存路徑和文件名。
- PdfDocument.MergeFiles(sourceFiles, outputFile) 是核心方法。它接收一個(gè)字符串?dāng)?shù)組(包含所有源PDF路徑)和一個(gè)目標(biāo)文件路徑,然后執(zhí)行合并操作并將結(jié)果保存。
- try-catch 塊用于捕獲可能發(fā)生的異常,確保程序的健壯性。
到此這篇關(guān)于C#實(shí)現(xiàn)一鍵批量合并PDF文檔的文章就介紹到這了,更多相關(guān)C#合并PDF內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c# winform treelistview的使用(treegridview)實(shí)例詳解
這篇文章主要介紹了c# winform treelistview的使用(treegridview),本文通過實(shí)例代碼給大家詳細(xì)介紹,需要的朋友可以參考下2017-12-12
利用Distinct()內(nèi)置方法對(duì)List集合的去重問題詳解
這篇文章主要給大家介紹了關(guān)于利用Distinct()內(nèi)置方法對(duì)List集合的去重問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06
unity實(shí)現(xiàn)場(chǎng)景切換進(jìn)度條顯示
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)場(chǎng)景切換進(jìn)度條顯示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11

