C#把多个PDF合并成一个

书接上文,上篇博客写了一个给PDF加背景的文章,这次又因为客户说多个PDF太乱了,要求合并成一个PDF,思路就是把所有生成的PDF的保存路径存到一个数组或者LIST中,然后使用下面我提供的拼接方法就可以实现把多个PDF按顺序拼成一个PDF输出了。

核心代码:

        /// <summary>
        /// 合并多个PDF文件
        /// </summary>
        /// <param name="fileList">待合并PDF集合</param>
        /// <param name="outMergeFile">输出文件路径</param>
        public static bool MergePdfFiles(List<string> fileList, string outMergeFile)
        {
            bool ret;
            try
            {
                //记录合并后的PDF集合
                List<PdfReader> readerList = new List<PdfReader>();
                Rectangle rec;
                Document document = new Document();
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
                document.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage newPage;
                for (int i = 0; i < fileList.Count; i++)
                {
                    PdfReader reader = new PdfReader(fileList[i]);
                    int iPageNum = reader.NumberOfPages;
                    int rotation;
                    for (int j = 1; j <= iPageNum; j++)
                    {
                        rotation = reader.GetPageRotation(j);
                        rec = reader.GetPageSize(reader.GetPageN(j));
                        if (rotation == 90)
                        {
                            Rectangle rec2 = new Rectangle(0, 0, rec.Height, rec.Width);
                            document.SetPageSize(rec2);
                            document.NewPage();
                            newPage = writer.GetImportedPage(reader, j);
                            cb.AddTemplate(newPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(j).Height);
                        }
                        else
                        {
                            document.SetPageSize(rec);
                            document.NewPage();
                            newPage = writer.GetImportedPage(reader, j);
                            cb.AddTemplate(newPage, 0, 0);
                        }
                    }
                    readerList.Add(reader);
                }
                document.Close();
                writer.Close();
                //释放占用资源
                foreach (PdfReader rd in readerList)
                {
                    rd.Dispose();
                }
                ret = true;
            }
            catch (Exception)
            {
                ret = false;
            }
            return ret;
        }

实现效果:

THE END