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