zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【C#】pdf文件合并

2023-04-18 15:33:44 时间

环境:VS2019 + Win10 + .NET Framework3.5

依赖于: itextsharp.dll

 

源码,封装接口:

        /// <summary>
        /// 合并pdf文件至输出文件
        /// </summary>
        /// <param name="fileList">要合并的pdf文件列表(全路径)</param>
        /// <param name="outMergeFile">输出文件全路径</param>
        public void mergePdfFiles(List<string> fileList, string outMergeFile)
        {
            using (var stream = new FileStream(outMergeFile, FileMode.Create))
            {
                using (var doc = new iTextSharp.text.Document())
                {
                    using (var pdf = new PdfCopy(doc, stream))
                    {
                        doc.Open();
                        fileList.ForEach(file =>
                        {
                            var reader = new PdfReader(file);
                            for (int i = 0; i < reader.NumberOfPages; i++)
                            {
                                var page = pdf.GetImportedPage(reader, i + 1);
                                pdf.AddPage(page);
                            }
                            pdf.FreeReader(reader);
                            reader.Close();
                        });
                    }
                }
            }
        }

  调用者代码:

// using iTextSharp.text.pdf;

        /// <summary>
        /// 合并pdf文件至输出文件
        /// </summary>
        /// <param name="fileList">要合并的pdf文件列表(全路径)</param>
        /// <param name="outMergeFile">输出文件全路径</param>
        public void mergePdfFiles(List<string> fileList, string outMergeFile)
        {
            using (var stream = new FileStream(outMergeFile, FileMode.Create))
            {
                using (var doc = new iTextSharp.text.Document())
                {
                    using (var pdf = new PdfCopy(doc, stream))
                    {
                        doc.Open();
                        fileList.ForEach(file =>
                        {
                            var reader = new PdfReader(file);
                            for (int i = 0; i < reader.NumberOfPages; i++)
                            {
                                var page = pdf.GetImportedPage(reader, i + 1);
                                pdf.AddPage(page);
                            }
                            pdf.FreeReader(reader);
                            reader.Close();
                        });
                    }
                }
            }
        }