C# .Net Core 合并PDF文件

使用 PdfSharpCore nuget包

代码实现

using Microsoft.AspNetCore.Razor.TagHelpers;
using PdfSharpCore.Pdf;
using PdfSharpCore.Pdf.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo_PDFByPage
{
    public class PdfSharpTool
    {

        /// <summary>
        /// 合并PDF
        /// </summary>
        /// <param name="splitFolderPath">分割文件夹</param>
        /// <param name="mergeFolderPath">合并文件夹</param>
        /// <param name="filepath">生成文件路径</param>
        public static void CombinePdfFiles(string splitFolderPath, string mergeFolderPath, string filepath)
        {
            try
            {
                //读取文件夹中的文件夹
                int fileCount = 0;
                int pageCount = 0;
                PdfDocument outPdfFile = new PdfDocument();
                List<string> fileNameList = new List<string>();
                List<string> fileError = new List<string>();
                foreach (var filename in Directory.GetFiles(splitFolderPath))
                {
                    if (Path.GetExtension(filename) == ".pdf")
                    {
                        try
                        {
                            PdfDocument pdfFile = PdfReader.Open(filename, PdfDocumentOpenMode.Import);
                            fileCount++;
                            pageCount += pdfFile.PageCount;
                            foreach (var pdfPage in pdfFile.Pages)
                            {
                                outPdfFile.AddPage(pdfPage);
                                fileNameList.Add(string.Format("{0} {1}", Path.GetFileName(filename), pdfFile.PageCount));
                            }
                        }
                        catch (Exception ex)
                        {
                            fileError.Add(Path.GetFileName(filename));
                        }
                    }
                }
                string combineResult = "";
                if (fileCount > 0)
                {
                    //导出pdf文件
                    string fileName = Path.GetFileName(filepath);

                    if (!Directory.Exists(mergeFolderPath))
                    {
                        Directory.CreateDirectory(mergeFolderPath);
                    }

                    string mergeFilePath = Path.Combine(mergeFolderPath, fileName);

                    outPdfFile.Save(mergeFilePath);

                    fileNameList.Add(string.Format("共 {0} 个文件,共 {1} 页。", outPdfFile, pageCount));
                    if (fileError.Count > 0)
                    {
                        fileNameList.Add("合并失败文件:");
                        foreach (string p in fileError)
                        {
                            fileNameList.Add(p);
                        }
                    }
                    SaveTxtFile(mergeFolderPath, Path.GetFileNameWithoutExtension(mergeFilePath) + ".txt", fileNameList);
                }
                combineResult = string.Format("合并文件数量:{0}", fileCount);
                if (fileError.Count > 0)
                {
                    combineResult += "\r\n";
                    combineResult += string.Format("合并失败文件数量:{0}", fileError.Count);
                }
                Console.WriteLine(combineResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        public void CombinePdfFiles(string folderPath)
        {
            try
            {
                //读取文件夹中的文件夹
                int fileCount = 0;
                int pageCount = 0;
                PdfDocument outPdfFile = new PdfDocument();
                List<string> fileNameList = new List<string>();
                List<string> fileError = new List<string>();
                foreach (var filename in Directory.GetFiles(folderPath))
                {
                    if (Path.GetExtension(filename) == ".pdf")
                    {
                        try
                        {
                            PdfDocument pdfFile = PdfReader.Open(filename, PdfDocumentOpenMode.Import);
                            fileCount++;
                            pageCount += pdfFile.PageCount;
                            foreach (var pdfPage in pdfFile.Pages)
                            {
                                outPdfFile.AddPage(pdfPage);
                                fileNameList.Add(string.Format("{0} {1}", Path.GetFileName(filename), pdfFile.PageCount));
                            }
                        }
                        catch (Exception ex)
                        {
                            fileError.Add(Path.GetFileName(filename));
                        }
                    }
                }
                string combineResult = "";
                if (fileCount > 0)
                {
                    //导出pdf文件
                    string timeTag = DateTime.Now.ToString("MMdd_HH_mm_ss");
                    SavePdfFile(folderPath + "\\合并", timeTag + ".pdf", outPdfFile);
                    fileNameList.Add(string.Format("共 {0} 个文件,共 {1} 页。", outPdfFile, pageCount));
                    if (fileError.Count > 0)
                    {
                        fileNameList.Add("合并失败文件:");
                        foreach (string p in fileError)
                        {
                            fileNameList.Add(p);
                        }
                    }
                    SaveTxtFile(folderPath + "\\合并", timeTag + ".txt", fileNameList);
                }
                combineResult = string.Format("合并文件数量:{0}", fileCount);
                if (fileError.Count > 0)
                {
                    combineResult += "\r\n";
                    combineResult += string.Format("合并失败文件数量:{0}", fileError.Count);
                }
                Console.WriteLine(combineResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private void SavePdfFile(string folderPath, string fileName, PdfDocument pdfFile)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            pdfFile.Save(folderPath + "\\" + fileName);
        }
        private static void SaveTxtFile(string folderPath, string fileName, List<string> content)
        {
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string fileFullPath = folderPath + "\\" + fileName;
            if (!File.Exists(fileFullPath))
            {
                var newFile = File.CreateText(fileFullPath);
                newFile.Close();
            }
            using (StreamWriter sw = new StreamWriter(fileFullPath, true))
            {
                foreach (string line in content)
                {
                    sw.WriteLine(line);
                }
                sw.Close();
            }
        }
    }

}

调用

static void Main(string[] args)
{
    string folderPath1 = Path.Combine(@"E:\Desktop", @"testpdf\Split");
    string folderPath2 = Path.Combine(@"E:\Desktop", @"testpdf\Merge");
    string folderPath3 = Path.Combine(folderPath1, $@"{DateTime.Now:yyyyMMddHHmmss}.pdf");
    PdfSharpTool.CombinePdfFiles(folderPath1, folderPath2, folderPath3);
    Console.WriteLine("结束!");
}

posted on   糯米白白  阅读(551)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示