[.net MVC] 合併Pdf - 使用ITexSharp

以後怕會有同樣需求

在這邊記上程式碼

 /// <summary> 合併PDF檔(集合) </summary> 
        /// <param name="fileList">合併PDF檔之集合</param>
        /// <param name="outMergeFile">合併後的檔名</param> 
        public bool mergePDFFiles(List<string> fileList, string outMergeFile)
        {
            PdfReader reader;
            using (iTextSharp.text.Document document = new iTextSharp.text.Document())
            {
                FileStream fs;
                try
                {
                    fs = new FileStream(outMergeFile, FileMode.Create);
                }
                catch (Exception)
                {
                    //檔案被鎖住 已經有開啟                 
                    return true;
                }
                                
                PdfWriter writer = PdfWriter.GetInstance(document, fs);
                document.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage newPage;
                for (int i = 0; i < fileList.Count; i++)
                {
                    //iTextSharp reads the data as a stream. iTextSharp 
                    // force iTextSharp to "load" the first file by binding your PdfReader to a byte array of the file 
                    //讀取資料就是stream 所以會有lock問題
                    //所以如果一開始就用byte讀取就不會有lock問題
                    reader = new PdfReader(System.IO.File.ReadAllBytes(fileList[i]));
                    int iPageNum = reader.NumberOfPages;
                    for (int j = 1; j <= iPageNum; j++)
                    {
                        document.NewPage();
                        newPage = writer.GetImportedPage(reader, j);
                        cb.AddTemplate(newPage, 0, 0);
                    }
                }
                document.Close();                
            }
            return false;
        }