我的目标是将公司 Logo 添加到现有 pdf 的每一页(不是水印)。
由于 pdf 文件和 Logo 的特殊性,我只能将 Logo 放在 pdf 内容的顶部(而不是在下面),并且 Logo 必须支持透明。
另一个限制是我必须使用 .NET Core。
将此与答案一起发布,因为我找不到明确的解决方案。 欢迎提出建议/更正/改进。
希望有人觉得这有用。
最佳答案
支持 .NET Core 的最新 iTextSharp 库是 iText7但是我不能合法地使用它;将我的代码开源或购买许可证都不是我的选择。因此我使用旧的第三方库:
Install-Package iTextSharp.LGPLv2.Core
我正在使用的最新版本是 1.3.2
需要以下用法
using System;
using System.Drawing.Imaging;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
要在 pdf 中实现图像透明,图像必须以正确的格式打开
var preImage = System.Drawing.Image.FromFile(imagePath);
var image = Image.GetInstance(preImage, ImageFormat.Png);
在添加图片的时候,同样重要的是不要选择要内联的图片
canvas.AddImage(image);//do not put .AddImage(image, true);
这是全部代码
var imagePath = "logo.png";
var pdfPath = "edit_this.pdf";
//load pdf file
var pdfBytes = File.ReadAllBytes(pdfPath);
var oldFile = new PdfReader(pdfBytes);
//load image
var preImage = System.Drawing.Image.FromFile(imagePath);
var image = Image.GetInstance(preImage, ImageFormat.Png);
preImage.Dispose();
//optional: if image is wider than the page, scale down the image to fit the page
var sizeWithRotation = oldFile.GetPageSizeWithRotation(1);
if (image.Width > sizeWithRotation.Width)
image.ScalePercent(sizeWithRotation.Width / image.Width * 100);
//set image position in top left corner
//in pdf files, cooridinates start in the left bottom corner
image.SetAbsolutePosition(0, sizeWithRotation.Height - image.ScaledHeight);
//in production, I use MemoryStream
//I put FileStream here to test the code in console application
using (var newFileStream = new FileStream("with_logo.pdf", FileMode.Create))
{
//setup PdfStamper
var stamper = new PdfStamper(oldFile, newFileStream);
//iterate through the pages in the original file
for (var i = 1; i <= oldFile.NumberOfPages; i++)
{
//get canvas for current page
var canvas = stamper.GetOverContent(i);
//add image with pre-set position and size
canvas.AddImage(image);
}
stamper.Close();
}
此代码适用于本地文件。 在我的(真实世界)案例中,我收到 PDF 文件作为 Base64 字符串,从本地存储添加 Logo ,将其转换回 Base64 字符串并将其输出到网页上。
我强制(硬编码)以 PNG 格式打开图像,因为我控制 Logo 的扩展名。如有必要,您可以动态设置图像格式。
关于c# .NET CORE 使用 ITextSharp 将具有透明度的图像添加到现有 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47073013/