C#将制定文件夹下的PDF文件合并成一个并输出至指定路径

/// <summary>
/// 将源路径下的PDF合并至目标路径下
/// </summary>
/// <param name="SourcePath">源路径</param>
/// <param name="TargetPath">目标路径</param>
/// <param name="NewFileName">新文件名</param>
private void MergePDF(string SourcePath,string TargetPath,string NewFileName)
{
string[] filenames = Directory.GetFiles(SourcePath, "*.pdf", SearchOption.AllDirectories);
int fileNum = filenames.Length;//pdf的个数
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
if (fileNum < 2)
{
return;//源路径下只有一个PDF文件,那么不合并
}
Aspose.Pdf.Document a = new Document();
foreach (var file in filenames)//遍历源路径,获取该路径下所有PDF文件的path
{
Document b = new Document(file);
foreach (Page item in b.Pages)
{
a.Pages.Add(item);
}
a.Save(TargetPath + "\\" + NewFileName);
}
}

//调用,这里使用了Aspose.Pdf.dll

using Aspose.Pdf;
using System.IO;

private void button1_Click(object sender, EventArgs e)
{
string path_Source=@"C:\Users\Evan\Documents\PDF 文件\AutoSave";
string path_Target=Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//计算机桌面的路径
MergePDF(path_Source, path_Target,"666666.pdf");
}

//这里增加个大文件复制的方法

    /// <summary>
        /// 大文件多次复制文件  true:复制成功   false:复制失败
        /// </summary>
        /// <param name="soucrePath">原始文件路径包含文件名</param>
        /// <param name="targetPath">复制目标文件路径,包含文件名</param>
        /// <returns></returns>
        public bool CopyFile(string soucrePath, string targetPath)
        {
            try
            {
                //读取复制文件流
                using (FileStream fsRead = new FileStream(soucrePath, FileMode.Open, FileAccess.Read))
                {
                    //写入文件复制流
                    using (FileStream fsWrite = new FileStream(targetPath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        byte[] buffer = new byte[1024 * 1024 * 2]; //每次读取2M
                        //可能文件比较大,要循环读取,每次读取2M
                        while (true)
                        {
                            //每次读取的数据    n:是每次读取到的实际数据大小
                            int n = fsRead.Read(buffer, 0, buffer.Count());
                            //如果n=0说明读取的数据为空,已经读取到最后了,跳出循环
                            if (n == 0)
                            {
                                break;
                            }
                            //写入每次读取的实际数据大小
                            fsWrite.Write(buffer, 0, n);
                        }
                    }
                }
                return true;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }

  

转载于:https://www.cnblogs.com/evanmemo/p/8489717.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值