ASP.NET Core 给 PDF 加多组水印

前面讲了如何给PDF文件加水印:https://www.cnblogs.com/sun8134/p/18109237


当我们需要加多组水印的时候,该如何处理呢?

其实很简单,多加点 Paragraph 用 document.ShowTextAligned 加上去就行了


修改下之前的代码,我们加两个  Paragraph ,并且设定不同的透明度看看效果


        /// <summary>
        /// PDF 转 Base64,加水印
        /// </summary>
        /// <param name="inputPath"></param>
        /// <param name="watermarkImage"></param>
        /// <param name="watermarkTxt"></param>
        /// <returns></returns>
        public static string PdfWatermark2Base64(string inputPath, string watermarkImage, string watermarkTxt)
        {
            MemoryStream outputStream = new MemoryStream();
            using (PdfReader existingPdf = new PdfReader(inputPath))
            {
                using (PdfWriter newPdf = new PdfWriter(outputStream))
                {
                    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);

                        //PdfFont fontChinese;
                        //var path = System.IO.Path.Combine("F:\\pdf", "font.ttf");
                        //fontChinese = PdfFontFactory.CreateFont(path, PdfEncodings.IDENTITY_H);

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

                        Random random = new Random();

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

                            Paragraph p1 = new Paragraph();
                            p1.Add(image);
                            p1.SetFont(fonts);
                            p1.Add(new Text("\r\n"));
                            p1.Add(new Text(watermarkTxt).SetFontSize(90).SetFontColor(new DeviceRgb((float)red / 255f, (float)green / 255f, (float)blue / 255f)));
                            p1.Add(new Text("\r\n"));
                            p1.Add(new Text(DateTime.Now.ToString("yyyy-MM-dd HH:mm")).SetFontSize(60).SetFontColor(ColorConstants.DARK_GRAY));


			    Paragraph p2 = new Paragraph();
                            p2.SetFont(fonts);
                            for (int j = 1; j <= 15; j++)
                            {
	                            if (j % 2 == 0)
	                            {
		                            p2.Add(new Text(DateTime.Now.ToString("yyyy-MM-dd HH:mm")).SetFontSize(24).SetFontColor(ColorConstants.BLUE));
	                            }

	                            for (int k = 0; k < 3; k++)
	                            {
		                            for (int l = 0; l < 20; l++)
		                            {
						p2.Add(new Text(("\u00A0")).SetFontSize(24).SetFontColor(ColorConstants.WHITE));
					    }
					p2.Add(new Text(DateTime.Now.ToString("yyyy-MM-dd HH:mm")).SetFontSize(24).SetFontColor(ColorConstants.BLUE));
				    }

	                            p2.Add(new Text("\r\n"));
	                            p2.Add(new Text("\r\n"));
	                            p2.Add(new Text("\r\n"));
	                            p2.Add(new Text("\r\n"));
                            }

                            canvas.SaveState();
                            PdfExtGState gs1 = new PdfExtGState().SetFillOpacity(0.2f);
                            canvas.SetExtGState(gs1);
			    document.ShowTextAligned(p2, pageSize.GetWidth() / 2 - 50, pageSize.GetHeight() / 2 + random.Next(1, 100), pdfDocument.GetPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 6);

			    gs1 = new PdfExtGState().SetFillOpacity(0.6f);
			    canvas.SetExtGState(gs1);
			    document.ShowTextAligned(p1, pageSize.GetWidth() / 2 - 50, pageSize.GetHeight() / 2 + 50, pdfDocument.GetPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);

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

            byte[] extractedPdfData = ((MemoryStream)outputStream).ToArray();
            string base64 = Convert.ToBase64String(extractedPdfData);
            outputStream.Close();
            outputStream.Dispose();

            return base64;
        }


上面代码我们加了两个 Paragraph ,一个设置透明度为0.2,一个社厅透明度为0.6

然后调用下看看效果

public IActionResult Privacy()
{
    DefaultModel dm = new DefaultModel();
    dm.PdfBase64 = PdfHelper.PdfWatermark2Base64("F:\\pdf\\compressed.tracemonkey-pldi-09.pdf", "F:\\pdf\\netcore.png", "Asp.Net Core 8.0");

    return View(dm);
}


运行如下图:

imageimage

posted @ 2024-09-24 16:10  sun8134  阅读(30)  评论(0编辑  收藏  举报
分享按钮