其他分享
首页 > 其他分享> > 基于iTextSharp.text+iTextSharp.text.pdf 的pdf文件合并

基于iTextSharp.text+iTextSharp.text.pdf 的pdf文件合并

作者:互联网

先引用

using iTextSharp.text;
using iTextSharp.text.pdf;

 

        public static string MergePdf(List<string> list, string merFilePath, bool isDelOldFile = true)
        {
            try
            {
                List<PdfReader> pdfReaders = new List<PdfReader>();
                PdfReader reader;
                Rectangle re;
                Document document = new Document();
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(merFilePath, FileMode.Create));
                document.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage newPage;
                for (int i = 0; i < list.Count; i++)
                {
                    reader = new PdfReader(list[i]);
                    int iPageNum = reader.NumberOfPages;
                    for (int j = 1; j <= iPageNum; j++)
                    {
                        re = reader.GetPageSize(reader.GetPageN(j)); //获取当前页面的纸张方向
                        document.SetPageSize(re); //设置新PDF当前页面的纸张方向
                        document.NewPage();
                        newPage = writer.GetImportedPage(reader, j);
                        cb.AddTemplate(newPage, 0, 0);
                    }
                    pdfReaders.Add(reader);
                }
                document.Close();
                document.Dispose();
                //循环释放 才能删除源文件
                foreach (var read in pdfReaders)
                {
                    read.Dispose();
                }
                if (isDelOldFile)
                {
                    foreach (var file in list)
                    {
                        if (System.IO.File.Exists(file)) System.IO.File.Delete(file);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return merFilePath;
        }

  

标签:document,text,list,iTextSharp,reader,new,pdf
来源: https://www.cnblogs.com/request/p/16670758.html