C# 给PDF增加背景图片

日前在用FastReport做报表,用户要求pdf文档要好看一些,所以加了一些背景图片,之前的模板已经做完了,PDF也能正常导出了,如果仅仅加个背景图片,还是考虑在生成后的文件中二次添加背景图片,通过下方代码,最终的功能效果还是实现了,写个博客记录一下。

核心代码:

        /// <summary>
        /// 添加PDF背景图片
        /// </summary>
        /// <param name="inputPath">传入文件路径</param>
        /// <param name="outPath">输出文件路径</param>
        /// <param name="imgPath">背景图片路径</param>
        /// <param name="pages">需要添加背景的页码</param>
        /// <param name="isone">是否仅处理第一页</param>
        public static void AddPdfBackgroundImages(string inputPath, string outPath, string imgPaths, bool isone = false)
        {
            FileStream stream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite);
            PdfReader reader = new PdfReader(inputPath);
            PdfStamper stamper = new PdfStamper(reader, stream);

            int totalPage = reader.NumberOfPages;
            for (int current = 0; current < totalPage; current++)
            {
                var canvas = stamper.GetUnderContent(current + 1);
                var page = stamper.GetImportedPage(reader, current + 1);

                if (isone == true)
                {
                    if (current == 0)
                    {
                        System.Drawing.Image image = System.Drawing.Image.FromFile(imgPaths);
                        var img = Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
                        //图片起始位置
                        img.SetAbsolutePosition(0, 0);
                        //图片整页缩放
                        img.ScaleAbsolute(page.Width, page.Height);
                        //添加图片到页
                        canvas.AddImage(img);
                    }
                }
                else
                {
                    System.Drawing.Image image = System.Drawing.Image.FromFile(imgPaths);
                    var img = Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
                    //图片起始位置
                    img.SetAbsolutePosition(0, 0);
                    //图片整页缩放
                    img.ScaleAbsolute(page.Width, page.Height);
                    //添加图片到页
                    canvas.AddImage(img);
                }
            }

            stamper.Close();
            reader.Close();
        }

效果展示(箭头指向均为背景):

THE END