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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM