C# 使用Aspose.Pdf给Pdf文件添加文字水印和图片水印 - Shi_zy

时间:2024-03-09 13:10:26

C# 使用Aspose.Pdf给Pdf文件添加文字水印和图片水印

使用Aspose.Pdf给pdf文件添加水印,代码如下:仅供参考(带一些个人业务,还有些小bug自行修改)

Aspose试用版 pdf超过4页会报错,商用请购买正式版本。

1、添加文字水印

/// <summary>
        /// pdf添加文字水印(自定义水印行数和列数)
        /// </summary>
        /// <param name="pdfStream">pdf文件流</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="fontSize">文字大小</param>
        /// <param name="fontColor">文字颜色</param>
        /// <param name="typeface">字体:(中文水印请自行查找相应字体的英文名称,如:宋体(SimSun),黑体(SimHei),仿宋(FangSong),微软雅黑(Microsoft YaHei)等等...)</param>
        /// <param name="rotation">倾斜角度</param>
        /// <param name="opacity">不透明度(值为:0-1)</param>
        /// <param name="watermarkRowNum">水印行数</param>
        /// <param name="watermarkColumnNum">水印列数</param>
        /// <returns></returns>
        public Stream AddTextWatermarkCustom(Stream pdfStream, string watermarkText, float fontSize, Aspose.Pdf.Color fontColor, string typeface, double rotation = 0, double opacity = 0, int watermarkRowNum = 1, int watermarkColumnNum = 1)
        {
            try
            {
                /*计算倾斜高度-start*/
                var angle = Math.Abs(rotation);
                var width = watermarkText.Length * fontSize;
                var radian = 2 * Math.PI / 360 * angle;
                var top = Math.Sin(radian) * width;
                /*计算倾斜高度-end*/
                Document document = new Document(pdfStream);
                for (int i = 1; i <= document.Pages.Count; i++)
                {
                    var pageWidth = document.Pages[i].GetPageRect(false).Width;
                    var pageHeight = document.Pages[i].GetPageRect(false).Height;
                    WatermarkArtifact artifact = new WatermarkArtifact();
                    artifact.SetTextAndState(watermarkText, new TextState
                    {
                        FontSize = fontSize,
                        ForegroundColor = fontColor,
                        Font = FontRepository.FindFont(typeface),
                    });
                    artifact.Rotation = rotation;
                    artifact.Opacity = opacity;
                    artifact.IsBackground = false;
                    if (watermarkRowNum == 1 && watermarkColumnNum == 1)
                    {
                        artifact.ArtifactHorizontalAlignment = HorizontalAlignment.Center;
                        artifact.ArtifactVerticalAlignment = VerticalAlignment.Center;
                        document.Pages[i].Artifacts.Add(artifact);
                    }
                    else
                    {
                        artifact.ArtifactHorizontalAlignment = HorizontalAlignment.Left;
                        artifact.ArtifactVerticalAlignment = VerticalAlignment.Top;
                        for (int j = 1; j <= watermarkColumnNum; j++)
                        {
                            artifact.LeftMargin = (j - 1) * (pageWidth / watermarkColumnNum) + fontSize;
                            for (int z = 1; z <= watermarkRowNum; z++)
                            {
                                artifact.TopMargin = (z - 1) * (pageHeight / watermarkRowNum) + top;
                                document.Pages[i].Artifacts.Add(artifact);
                            }
                        }
                    }
                }
                Stream outStream = new MemoryStream();
                document.Save(outStream, SaveFormat.Pdf);
                outStream.Seek(0, SeekOrigin.Begin);
                return outStream;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// pdf添加文字水印(平铺)
        /// </summary>
        /// <param name="pdfStream">pdf文件流</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="fontSize">文字大小</param>
        /// <param name="fontColor">文字颜色</param>
        /// <param name="typeface">字体:(中文水印请自行查找相应字体的英文名称,如:宋体(SimSun),黑体(SimHei),仿宋(FangSong),微软雅黑(Microsoft YaHei)等等...)</param>
        /// <param name="rotation">倾斜角度</param>
        /// <param name="opacity">不透明度(值为:0-1)</param>
        /// <param name="density">水印密度(值为0-1)</param>
        /// <returns></returns>
        public Stream AddTextWatermarkTile(Stream pdfStream, string watermarkText, float fontSize, Aspose.Pdf.Color fontColor, string typeface, double rotation = 0, double opacity = 0, double density = 1)
        {
            try
            {
                Document document = new Document(pdfStream);
                /*计算水印详细-start*/
                var angle = Math.Abs(rotation);
                var width = watermarkText.Length * fontSize;
                var radian = 2 * Math.PI / 360 * angle;
                var top = Math.Sin(radian) * width;
                var row = Math.Cos(radian) * width;
                var pageWidth = document.Pages[1].GetPageRect(false).Width;
                var pageHeight = document.Pages[1].GetPageRect(false).Height;
                int watermarkRowNum = (int)(pageHeight / top * density);
                int watermarkColumnNum = (int)(pageHeight / row * density);
                if (rotation == 0)
                {
                    watermarkRowNum = (int)(pageHeight / fontSize * density);
                    watermarkColumnNum = (int)(pageHeight / width * density);
                }

                /*计算水印详细-end*/
                for (int i = 1; i <= document.Pages.Count; i++)
                {

                    WatermarkArtifact artifact = new WatermarkArtifact();
                    artifact.SetTextAndState(watermarkText, new TextState
                    {
                        FontSize = fontSize,
                        ForegroundColor = fontColor,
                        Font = FontRepository.FindFont(typeface),
                    });
                    artifact.Rotation = rotation;
                    artifact.Opacity = opacity;
                    artifact.IsBackground = false;
                    artifact.ArtifactHorizontalAlignment = HorizontalAlignment.Left;
                    artifact.ArtifactVerticalAlignment = VerticalAlignment.Top;
                    for (int j = 1; j <= watermarkColumnNum; j++)
                    {
                        artifact.LeftMargin = (j - 1) * (pageWidth / watermarkColumnNum) + fontSize;
                        for (int z = 1; z <= watermarkRowNum; z++)
                        {
                            artifact.TopMargin = (z - 1) * (pageHeight / watermarkRowNum) + top;
                            document.Pages[i].Artifacts.Add(artifact);
                        }
                    }
                }
                Stream outStream = new MemoryStream();
                document.Save(outStream, SaveFormat.Pdf);
                outStream.Seek(0, SeekOrigin.Begin);
                return outStream;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

调用代码部分代码:

Stream stream = File.OpenRead(@"C:\Users\HEDY\Desktop\Test\2.pdf");
            var outStream = AddTextWatermarkCustom(stream, "测试水印文字", 32, Color.Blue, "SimSun", 45, 0.5, 6, 3);
            var saveStream = new FileStream($@"C:\Users\HEDY\Desktop\Test\1_{Guid.NewGuid()}.pdf", FileMode.Create);
            outStream.CopyTo(saveStream);
            outStream.Close();
            saveStream.Close();

 

2、添加图片水印

 /// <summary>
        /// pdf添加图片水印(自定义水印行数和列数)
        /// </summary>
        /// <param name="pdfStream">pdf文件流</param>
        /// <param name="imgurl">水印文字</param>
        /// <param name="rotation">倾斜角度</param>
        /// <param name="opacity">不透明度(值为:0-1)</param>
        /// <param name="watermarkRowNum">水印行数</param>
        /// <param name="watermarkColumnNum">水印列数</param>
        /// <returns></returns>
        public Stream AddImgWatermarkCustom(Stream pdfStream, string imgPath, double rotation = 0, double opacity = 0, int watermarkRowNum = 1, int watermarkColumnNum = 1)
        {
            try
            {
                /*计算倾斜高度-start*/
                var angle = Math.Abs(rotation);
                var pic = new Bitmap(imgPath);
                var width = pic.Width;
                var radian = 2 * Math.PI / 360 * angle;
                var top = Math.Sin(radian) * width;
                /*计算倾斜高度-end*/
                Document document = new Document(pdfStream);
                for (int i = 1; i <= document.Pages.Count; i++)
                {
                    var pageWidth = document.Pages[i].GetPageRect(false).Width;
                    var pageHeight = document.Pages[i].GetPageRect(false).Height;
                    WatermarkArtifact artifact = new WatermarkArtifact();
                    artifact.SetImage(File.OpenRead(imgPath));
                    artifact.Rotation = rotation;
                    artifact.Opacity = opacity;
                    artifact.IsBackground = false;
                    if (watermarkRowNum == 1 && watermarkColumnNum == 1)
                    {
                        artifact.ArtifactHorizontalAlignment = HorizontalAlignment.Center;
                        artifact.ArtifactVerticalAlignment = VerticalAlignment.Center;
                        document.Pages[i].Artifacts.Add(artifact);
                    }
                    else
                    {
                        artifact.ArtifactHorizontalAlignment = HorizontalAlignment.Left;
                        artifact.ArtifactVerticalAlignment = VerticalAlignment.Top;
                        for (int j = 1; j <= watermarkColumnNum; j++)
                        {
                            artifact.LeftMargin = (j - 1) * (pageWidth / watermarkColumnNum) + pic.Height;
                            for (int z = 1; z <= watermarkRowNum; z++)
                            {
                                artifact.TopMargin = (z - 1) * (pageHeight / watermarkRowNum) + top;
                                document.Pages[i].Artifacts.Add(artifact);
                            }
                        }
                    }
                }
                Stream outStream = new MemoryStream();
                document.Save(outStream, SaveFormat.Pdf);
                outStream.Seek(0, SeekOrigin.Begin);
                return outStream;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// pdf添加图片水印(平铺)
        /// </summary>
        /// <param name="pdfStream">pdf文件流</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="rotation">倾斜角度</param>
        /// <param name="opacity">不透明度(值为:0-1)</param>
        /// <param name="density">水印密度(值为0-1)</param>
        /// <returns></returns>
        public Stream AddImgWatermarkTile(Stream pdfStream, string imgPath, double rotation = 0, double opacity = 0, double density = 1)
        {
            try
            {
                Document document = new Document(pdfStream);
                /*计算水印详细-start*/
                var angle = Math.Abs(rotation);
                var pic = new Bitmap(imgPath);
                var width = pic.Width;
                var imgHeight = pic.Height;
                var radian = 2 * Math.PI / 360 * angle;
                var top = Math.Sin(radian) * width;
                var row = Math.Cos(radian) * width;
                var pageWidth = document.Pages[1].GetPageRect(false).Width;
                var pageHeight = document.Pages[1].GetPageRect(false).Height;
                int watermarkRowNum = (int)(pageHeight / top * density);
                int watermarkColumnNum = (int)(pageHeight / row * density);
                if (rotation == 0)
                {
                    watermarkRowNum = (int)(pageHeight / imgHeight * density);
                    watermarkColumnNum = (int)(pageHeight / width * density);
                }

                /*计算水印详细-end*/
                for (int i = 1; i <= document.Pages.Count; i++)
                {

                    WatermarkArtifact artifact = new WatermarkArtifact();
                    artifact.SetImage(File.OpenRead(imgPath));
                    artifact.Rotation = rotation;
                    artifact.Opacity = opacity;
                    artifact.IsBackground = false;
                    artifact.ArtifactHorizontalAlignment = HorizontalAlignment.Left;
                    artifact.ArtifactVerticalAlignment = VerticalAlignment.Top;
                    for (int j = 1; j <= watermarkColumnNum; j++)
                    {
                        artifact.LeftMargin = (j - 1) * (pageWidth / watermarkColumnNum) + imgHeight;
                        for (int z = 1; z <= watermarkRowNum; z++)
                        {
                            artifact.TopMargin = (z - 1) * (pageHeight / watermarkRowNum) + top;
                            document.Pages[i].Artifacts.Add(artifact);
                        }
                    }
                }
                Stream outStream = new MemoryStream();
                document.Save(outStream, SaveFormat.Pdf);
                outStream.Seek(0, SeekOrigin.Begin);
                return outStream;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

调用代码部分代码:

Stream stream = File.OpenRead(@"C:\Users\HEDY\Desktop\Test\2.pdf");
            var outStream = AddImgWatermarkTile(stream, @"C:\Users\HEDY\Desktop\Test\123.jpg", 0, 0.5,0.5);
            var saveStream = new FileStream($@"C:\Users\HEDY\Desktop\Test\1_{Guid.NewGuid().ToString("N")}.pdf", FileMode.Create);
            outStream.CopyTo(saveStream);
            outStream.Close();
            saveStream.Close();