首页 > 编程语言 >C# .Net Core 合并PDF文件

C# .Net Core 合并PDF文件

时间:2023-05-10 10:44:30浏览次数:38  
标签:Core string fileNameList C# filename fileError PDF Path folderPath

使用 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("结束!");
}

标签:Core,string,fileNameList,C#,filename,fileError,PDF,Path,folderPath
From: https://www.cnblogs.com/nuomibaibai/p/17387254.html

相关文章

  • QA|Pycharm中的git分支提交冲突问题和解决|GIT
    前天,Pycharm中的git分支提交冲突了,原因是我PC上改了文件没有提交,笔记本又本地改代码,笔记本提交时就出现报错:提交拒绝,但pull也被拒绝,网上试了rebase等方法,均没得到解决,最终自己尝试找到了解决办法:现象: 解决:选中分支按照图中操作注意:记得提前备份本地代码接下来就可以了 ......
  • arcpy遍历数据随记
    arcpy.da.SearchCursor和arcpy.SearchCursor的区别两者的都可以实现查询及遍历arcpy.da.SearchCursor:witharcpy.da.SearchCursor("GXB","*",sql_clause=(None,"Orderbyhbm"))ascursor:witharcpy.da.SearchCursor("Schools.shp",("......
  • chatgpt帮我创建一个由go+mysql+jwt+gorm搭建的restapi
    好的,下面是一个简单的由go+mysql+jwt+gorm搭建的RESTAPI示例:首先,你需要创建一个新的Go模块。你可以使用如下命令来创建一个名为example的新模块:gomodinitexample接下来,你需要安装需要的依赖库,使用以下命令进行安装:gogetgithub.com/gorilla/muxgogetgithub.com/jinzhu......
  • CH57x/CH58x原理图与PCB绘制
    前言针对供电系统、天线系统、下载以及出现问题进行汇总。一、供电系统1、供电以CH582M举例(其他见芯片手册的第二十参数章节),芯片可供供电范围[2.3-3.6],一般给到芯片引脚(VIO33/VDD33)的供电典型值为3.3V,只需要给该引脚供电,其他引脚均不需要供电。2、内部电路内部电路注意VSW/......
  • Echarts引入——绘制一个简单的图表
    获取EChartsNPM安装EChartsnpminstallecharts--save引入EChartsimport*asechartsfrom'echarts';//基于准备好的dom,初始化echarts实例varmyChart=echarts.init(document.getElementById('main'));//绘制图表myChart.setOption({title:{text......
  • Induction_Motor_VF_Control:基于MATLAB/Simulink的利用V/F控制的感应电机调速仿真模型
    Induction_Motor_VF_Control:基于MATLAB/Simulink的利用V/F控制的感应电机调速仿真模型。仿真条件:MATLAB/SimulinkR2015bID:8460650374052032......
  • 解决webgl使用canvas.toDataURL()没有内容的问题
    这个问题很好解决,就是在获取webgl对象的时候,多传入一个​​{preserveDrawingBuffer:true}​​​,然后在使用​​canvas.toDataURL()​​​获取就能够获取到了。案例:varcanvas=document.getElementById("canvas");vargl=canvas.getContext("webgl",{preserveDrawingBuf......
  • linux下拆分PDF、批量裁剪图片及合并为PDF操作
    好久不碰代码,文件操作啥的快忘光了(你丫本来就没怎么学吧!)我先放两串代码在这QAQ拆分PDFpdftoppm-png?.pdfs批量裁剪图片裁剪图片指令,这个指令是ImageMagick带的一个什么东西,单位电脑能装convertsrc.png-crop长x高+起始像素点横坐标+起始像素低纵坐标dest.png然后......
  • DC_Machine_Armature_Control:基于MATLAB/Simulink的直流电机电枢闭环控制系统仿真模型
    DC_Machine_Armature_Control:基于MATLAB/Simulink的直流电机电枢闭环控制系统仿真模型。仿真条件:MATLAB/SimulinkR2015bID:6840650770413102......
  • C#-Linq
    linq可以对多种数据源和对象进行查询,如数据库、数据集、XML文档、数组等。通过对linq的使用,可以减少代码量并优化检索操作。LINQ关键字from指定数据源和范围变量where根据布尔表达式(由逻辑与或等组成)从数据源中筛选元素select指定查询结果中的元素所具有的类型或表......