发布:2023/12/7 15:41:48作者:大数据 来源:大数据 浏览次数:468
nuget安装iTextSharp,安装的是最新版本5.5.13.2的,根据自己需求安装。
项目文件编辑如下:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="iTextSharp" Version="5.5.13.2" />
<PackageReference Include="System.Drawing.Common" Version="5.0.2" />
</ItemGroup>
</Project>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
/// <summary> /// 设置pdf图片水印 /// </summary> /// <param name="imgPath">水印图片路径</param> /// <param name="filePath">需要添加水印的pdf文件</param> /// <param name="outfilePath">添加完成的pdf文件</param> /// <returns></returns> public static bool SetImgWaterMark(string fileDirPath, string filePath, out string outfilePath) { PdfReader pdfReader = null; PdfStamper pdfStamper = null; FileStream fileStream = null; try { string outputfilepath = "e:\\" + Guid.NewGuid().ToString() + ".pdf"; string imgPath = "e:\\1.png"; pdfReader = new PdfReader(filePath); fileStream = new FileStream(outputfilepath, FileMode.Create); pdfStamper = new PdfStamper(pdfReader, fileStream); int total = pdfReader.NumberOfPages; Rectangle psize = pdfReader.GetPageSize(1); float width = psize.Width; float height = psize.Height; PdfContentByte content; //获取水印图片 Image image = Image.GetInstance(imgPath); image.SetAbsolutePosition((width / 2) - 100, (height / 2) - 100); for (int i = 1; i <= total; i++) { //content = pdfStamper.GetOverContent(i);//在内容上方加水印 content = pdfStamper.GetUnderContent(i);//在内容下方加水印 content.AddImage(image); } outfilePath = outputfilepath; return true; } catch (Exception ex) { outfilePath = ""; return false; } finally { if (pdfStamper != null) { pdfStamper.Close(); } if (pdfReader != null) { pdfReader.Close(); } if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } } } |
根据需求自己修改图片路径,pdf路径,以及生成图片的路径。
代码参照:
1 2 3 4 5 6 |
public IActionResult Index() { string aa; SetImgWaterMark(null, @"e:\1.pdf",out aa); return View(); } |
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4