最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#實現(xiàn)一鍵批量合并PDF文檔

 更新時間:2025年09月01日 09:09:35   作者:小碼編匠  
這篇文章主要為大家詳細介紹了如何使用C#實現(xiàn)一鍵批量合并PDF文檔功能,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學習一下

前言

由于項目需要編寫大量的材料,以及各種簽字表格、文書等,最后以PDF作為材料交付的文檔格式,過程文檔時有變化或補充,故此處理PDF文檔已經(jīng)成為日常工作的一部分。

網(wǎng)上有各種PDF處理工具,總是感覺用得不跟手。

最后回顧自己的需求總結為以下幾項:

1、可以便捷、快速的對多份PDF進行合并。

2、可以從源PDF選取指定頁碼進行合并。

3、可以從單個PDF提取特定頁碼(拆分PDF)。

4、對多個PDF分組,合并作為最終PDF的導航書簽,可快速定位。

5、統(tǒng)一合成后PDF頁面尺寸,如統(tǒng)一為A4幅面。

6、操作盡量簡便,支持文件拖放,不需要花巧的東西。

效果展示

首先,我們看看最終成品:

1、可以批量添加多個PDF到列表框中,也可以資料管理器將文件批量拖進來實現(xiàn)添加。

2、[可選]定義分組標題對文件進行分組,也作為合并后PDF的書簽。

3、將列表中PDF批量合并到一個文件中。如果只有PDF,而且定義了頁碼范圍,則轉換為拆分功能。

4、顯示PDF總頁數(shù),如果只需提取部分內(nèi)容,可以定義頁碼范圍。

5、可以更改合并后PDF頁面的尺寸,統(tǒng)一為A4、B4或A5幅面。

功能實現(xiàn)

搜索發(fā)現(xiàn)github有個開源的

github.com/schourode/pdfbinder

比較接近想要的效果,本著能省即省、成本最低、能效更高的原則,直接以此為基礎進行擴展,開發(fā)自身所需的功能。

1、添加文件

這個比較簡單,點擊按鈕后彈出選擇對話框,將選擇的文件逐一加到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ù)單獨編寫是為了在拖放事件中復用。

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;
    }
}

這里對PDF文件有效性進行了檢查,而且添加到ListBox的是PdfInfo對象,它還記錄了總頁數(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 
    {
        //如果選擇的是文件,提取文件名作默認值
        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、定義頁碼范圍

沒有定義頁碼范圍表示整個PDF進行合并。定義了頁面范圍,合并時只提取相應的頁面進行合并。

頁碼范圍的格式與常見的打印功能的頁碼定義相一致,如:1,2,3,6-9。

這個操作放在右鍵彈出菜單中實現(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;
        }
        //針對逗號和空格做處理
        string[] arr = range.Replace(",", ",").Replace(" ", "").Split(',');
        range = "";
        for (int i = 0; i < arr.Length; i++)
        {
            //用正則表達式判斷有效性
            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)
    {
        //繪書簽(分組名)圖標
        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、定義頁面尺寸

默認是原始尺寸(不做調整),可根據(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批量合并

這個比較長,有興趣的可以到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);
                //刷新進度
                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同步、文件移除、上移、下移、排序、多語言支持這些比較簡單就不展開了。

方法補充

C#使用Spire.PDF for .NET合并PDF

為什么選擇Spire.PDF for .NET

Spire.PDF for .NET 是一款功能全面、性能卓越的PDF處理庫,專為.NET平臺設計。它允許開發(fā)者在C#、VB.NET等語言中輕松創(chuàng)建、編輯、轉換、打印和查看PDF文檔,而無需安裝Adobe Acrobat等第三方軟件。

選擇Spire.PDF for .NET進行PDF合并的主要原因包括:

  • 功能全面: 除了合并,它還支持PDF的拆分、加密、解密、內(nèi)容提取、文本替換、添加水印、數(shù)字簽名等多種操作。
  • 性能優(yōu)異: 在處理大量或復雜的PDF文檔時,Spire.PDF for .NET展現(xiàn)出卓越的穩(wěn)定性和處理速度,有效提升開發(fā)效率。
  • 易于集成: 作為一個純.NET組件,它可以無縫集成到各種.NET應用中,如Windows Forms、ASP.NET、WPF以及.NET Core項目。
  • 兼容性強: 支持從.NET Framework 2.0到.NET 5.0+的多個版本,并能處理從PDF 1.2到1.7的各種PDF版本。
  • 開發(fā)者友好: 提供清晰的API接口和豐富的示例,大大降低了學習曲線。

環(huán)境準備:安裝Spire.PDF for .NET

在使用Spire.PDF for .NET之前,我們需要將其添加到項目中。最簡便的方式是通過NuGet包管理器在Visual Studio中進行安裝。

安裝步驟:

  • 打開Visual Studio。
  • 在“解決方案資源管理器”中,右鍵點擊您的項目,選擇“管理NuGet程序包...”。
  • 在“瀏覽”選項卡中,搜索“Spire.PDF”。
  • 找到“Spire.PDF”包,點擊“安裝”。

您也可以通過NuGet包管理器控制臺運行以下命令:

Install-Package Spire.PDF

安裝完成后,Spire.PDF for .NET的引用將自動添加到您的項目中。

核心實現(xiàn):使用C#合并PDF文檔的步驟與代碼

Spire.PDF for .NET 提供了簡潔而強大的方法來合并PDF文檔。以下是詳細的步驟和示例代碼:

步驟列表:

  • 準備源PDF文件路徑: 確定您要合并的所有PDF文件的完整路徑。
  • 創(chuàng)建字符串數(shù)組: 將所有源PDF文件的路徑存儲在一個字符串數(shù)組中。
  • 調用 PdfDocument.MergeFiles 方法: 使用 PdfDocument.MergeFiles(string[] filePaths, string destFile) 靜態(tài)方法一次性合并所有文件。這個方法會直接將合并后的PDF保存到指定的目標路徑。

示例代碼塊:

using System;
using Spire.Pdf;

namespace MergePdfDocuments
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. 定義源PDF文件路徑數(shù)組
            // 請將 "Document1.pdf", "Document2.pdf", "Document3.pdf" 替換為您的實際文件路徑
            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文檔
                // 這個方法是靜態(tài)的,可以直接調用,它會處理所有的合并邏輯并將結果保存到指定文件
                PdfDocument.MergeFiles(sourceFiles, outputFile);

                Console.WriteLine($"PDF文檔已成功合并到:{outputFile}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"合并PDF文檔時發(fā)生錯誤:{ex.Message}");
            }

            Console.ReadKey();
        }
    }
}

代碼解釋:

  • using Spire.Pdf; 導入了Spire.PDF庫的命名空間,以便訪問其提供的類和方法。
  • string[] sourceFiles 數(shù)組包含了所有待合并的PDF文件的完整路徑。您可以根據(jù)需要添加或刪除文件。
  • string outputFile 定義了合并后新PDF文檔的保存路徑和文件名。
  • PdfDocument.MergeFiles(sourceFiles, outputFile) 是核心方法。它接收一個字符串數(shù)組(包含所有源PDF路徑)和一個目標文件路徑,然后執(zhí)行合并操作并將結果保存。
  • try-catch 塊用于捕獲可能發(fā)生的異常,確保程序的健壯性。

到此這篇關于C#實現(xiàn)一鍵批量合并PDF文檔的文章就介紹到這了,更多相關C#合并PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

财经| 望谟县| 靖西县| 沈丘县| 克山县| 奉贤区| 临猗县| 宿松县| 红安县| 白银市| 玛沁县| 石柱| 贵德县| 台江县| 合江县| 奉新县| 苍溪县| 阜阳市| 莫力| 尉犁县| 河南省| 邹城市| 潞城市| 雷山县| 福州市| 巴马| 博兴县| 库车县| 久治县| 武邑县| 湘乡市| 贺兰县| 扎兰屯市| 武隆县| 兰考县| 延安市| 新兴县| 三原县| 锡林浩特市| 济南市| 灌阳县|