ASP.NET Core 给 PDF 加水印

需要使用 itext-dotnet :https://github.com/itext/itext-dotnet


使用Nuget:

Install-Package itext

Install-Package itext.bouncy-castle-adapter


给 PDF 加水印

        public static bool WatermarkPdf(string inputPath,string outputPath, string watermarkImage, string watermarkTxt)
        {
            bool result = false;
            try
            {
                using (FileStream pdfStream = new FileStream(outputPath, FileMode.Create))
                {
                    using (PdfReader existingPdf = new PdfReader(inputPath))
                    {
                        using (PdfWriter newPdf = new PdfWriter(pdfStream))
                        {
                            using (PdfDocument pdfDocument = new PdfDocument(existingPdf, newPdf))
                            {
                                Document document = new Document(pdfDocument);
                                iText.Kernel.Geom.Rectangle pageSize;
                                PdfCanvas canvas;

                                var image = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(watermarkImage)).ScaleToFit(200, 200);
                                PdfFont fonts= PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);


                                int red = 51;
                                int green = 53;
                                int blue = 102;

                                for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++)
                                {
                                    PdfPage page = pdfDocument.GetPage(i);
                                    pageSize = page.GetPageSize();
                                    canvas = new PdfCanvas(page);

                                    Paragraph p = new Paragraph();
                                    p.Add(image);
                                    p.SetFont(fonts);
                                    p.Add(new Text("\r\n"));
                                    p.Add(new Text(watermarkTxt).SetFontSize(90).SetFontColor(new DeviceRgb((float)red / 255f, (float)green / 255f, (float)blue / 255f)));
                                    p.Add(new Text("\r\n"));
                                    p.Add(new Text(DateTime.Now.ToString("yyyy-MM-dd HH:mm")).SetFontSize(60).SetFontColor(ColorConstants.DARK_GRAY));
                                    canvas.SaveState();
                                    PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.4f);
                                    canvas.SetExtGState(gs1);
                                    document.ShowTextAligned(p, pageSize.GetWidth() / 2 - 50, pageSize.GetHeight() / 2 + 50, pdfDocument.GetPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
                                }

                                pdfDocument.Close();
                                newPdf.Close();
                                existingPdf.Close();
                                pdfStream.Close();
                            }
                        }
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"error:{e}");
            }
            return result;
        }



在控制器里调用下:

        public IActionResult Index()
        {
            bool result = PdfHelper.WatermarkPdf("F:\\pdf\\compressed.tracemonkey-pldi-09.pdf", "F:\\pdf\\compressed.tracemonkey-pldi-16.pdf", "F:\\pdf\\netcore.png", "Asp.Net Core 8.0");
            return Content(result.ToString());
        }


看下效果:

image



注意:默认字体的话,是不支持中文的,如果文字有中文,请引入支持中文的字体,比如:

PdfFont fontChinese;
var path = System.IO.Path.Combine("F:\\pdf", "font.ttf");
fontChinese = PdfFontFactory.CreateFont(path, PdfEncodings.IDENTITY_H);
posted @ 2024-04-01 19:40  sun8134  阅读(154)  评论(0编辑  收藏  举报
分享按钮