c# 多个PDF合并带页码

c# 电子档案项目用到多个PDF合并为一个PDF文件,网上找了很久,发现可以用 iTextSharp 这个包。

废话不多说直接上代码

        /// <summary>
        /// 合并PDF并且产生页码
        /// </summary> 
        /// <param name="inFiles">子PDFlist</param>
        /// <param name="outFile">合成的pdf名称</param>
        static string MergePDFFilesWithPageNumber(List<String> inFiles, String outFile)
        {
            //最后合成的PDF文件的文件名
            string reportName = "XXXXXX_.pdf";
            reportName = "/" + outFile;
            //最后合并的PDF的完整地址  string mergePDFFiles = reportPath + reportName;
            string reportPath = "PDFFlileout";
            //如果目录不存在,创建目录  
            if (!Directory.Exists(reportPath))
            {
                Directory.CreateDirectory(reportPath);
            }         //如果文件已存在,把原来的删除
            if (System.IO.File.Exists(reportPath + reportName))
            {
                //删除文件,第一次起效,第二次就抛异常 ,原因是ConvertToBinary 读取后没有关闭
                new FileInfo(reportPath + reportName).Attributes = FileAttributes.Normal;
                System.IO.File.Delete(reportPath + reportName);

            }

            #region 使用iTextSharp合并PDF
            //在总PDF的存放位置创建一个新的PDF
            iTextSharp.text.Document DOC = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate());
            PdfWriter writer = PdfWriter.GetInstance(DOC, new FileStream(reportPath + reportName, FileMode.Create));
            DOC.Open();
            iTextSharp.text.Rectangle re;
            PdfContentByte cb = writer.DirectContent;
            //PdfImportedPage newPage;  //页码的字体,大小样式
            PdfTemplate newPage;
            BaseFont bfHei = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font font = new Font(bfHei, 10);

            for (int i = 0; i < inFiles.Count; i++)
            {    //读取每个子PDF文件
                //PdfReader reader = new PdfReader(filePdfPath + "/" + inFiles[i].pdfName);    //单个子PDF文件的页数
                PdfReader reader = new PdfReader(inFiles[i]);
                int iPageNum = reader.NumberOfPages;    //将每个子pdf的每一页插入到新创建的总PDF文件里,根据需要增加页面
                for (int j = 1; j <= iPageNum; j++)
                {
                    re = reader.GetPageSize(reader.GetPageN(j));
                    DOC.SetPageSize(re);
                    DOC.NewPage();
                    newPage = writer.GetImportedPage(reader, j);
                    cb.AddTemplate(newPage, 0, 0);

                    //增加页码-封面和底页都加
                    //Phrase header = new Phrase("第" + writer.PageNumber.ToString() + "页", font);
                    ////页脚显示的位置
                    //ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, header, DOC.PageSize.Width / 2, DOC.Bottom, 0);

                    //增加页码-封面和底页不加
                    //if (writer.PageNumber != 1 && !(i == data.Count - 1 && j == iPageNum))
                    //{
                    //    Phrase header = new Phrase("第" + (writer.PageNumber - 1).ToString() + "页", font);
                    //    //页脚显示的位置
                    //    ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, header, DOC.PageSize.Width / 2, DOC.Bottom, 0);
                    //}

                    //增加页码-封面不加,没有底页,封面只占一页
                    if (writer.PageNumber != 1)
                    {
                        Phrase header = new Phrase("" + (writer.PageNumber - 1).ToString() + "", font);
                        //页脚显示的位置
                        ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, header, DOC.PageSize.Width / 2, DOC.Bottom, 0);
                    }
                }
            }
            DOC.Close();
            return reportPath + reportName;
            #endregion
        }

 读取文件,转成流文件方法

        /// <summary>
        /// 将文件转换成二进制
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <returns></returns>
        public static byte[] ConvertToBinary(string Path)
        {
           using( FileStream stream = new FileInfo(Path).OpenRead()){
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
                stream.Close();
                return buffer;
            }
        }

 由于使用了c# core 后 iTextSharp 不支持跨平台,升级为iText7合并PDF增加页码

代码如下

iText.Kernel.Pdf.PdfDocument pdfout = new iText.Kernel.Pdf.PdfDocument(new PdfWriter(reportPath + reportName));
            PdfMerger merger = new PdfMerger(pdfout);
            //合并PDF
            for (int i = 0; i < inFiles.Count; i++)
            {    //读取每个子PDF文件
                iText.Kernel.Pdf.PdfDocument dpfdoc = new iText.Kernel.Pdf.PdfDocument(new PdfReader(inFiles[i]));
                merger.Merge(dpfdoc, 1, dpfdoc.GetNumberOfPages());
                dpfdoc.Close();
            }

            //增加页码
            iText.Layout.Document document = new iText.Layout.Document(pdfout);

            iText.Kernel.Font.PdfFont sysFont = PdfFontFactory.CreateFont("C:/Windows/Fonts/simsun.ttc,1", iText.IO.Font.PdfEncodings.IDENTITY_H);
            //document.Add(new Paragraph("好 的!").SetFont(sysFont));
            // Page numbers
            int n = pdfout.GetNumberOfPages();
            for (int i = 1; i <= n; i++)
            {
                //增加页码到右上角
                //document.ShowTextAligned(new Paragraph(String.Format("第" + i + "页 共" + n + "页")).SetFont(sysFont), 559, 806, i, TextAlignment.RIGHT, VerticalAlignment.TOP, 0);
                //增加页码到底部居中
                //document.ShowTextAligned(new Paragraph(String.Format("第" + i + "页 共" + n + "页")).SetFont(sysFont), pdfout.GetPage(i).GetPageSize().GetWidth() / 2, pdfout.GetPage(i).GetPageSize().GetBottom() + 15, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0);
                //增加页码-封面不加,没有底页,封面只占一页,目录占一页
                if (i != 1 && i != 2) {
                    document.ShowTextAligned(new Paragraph(String.Format("" + (i-2) + "")).SetFont(sysFont), pdfout.GetPage(i).GetPageSize().GetWidth() / 2, pdfout.GetPage(i).GetPageSize().GetBottom() + 15, i, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0);
                }

            }
            pdfout.Close();

            return reportPath + reportName;

 

posted @ 2022-06-23 17:36  蓬鹏  阅读(579)  评论(1编辑  收藏  举报