支持 .NET Core 的最新 iTextSharp 库是iText7 https://itextpdf.com/但是我不能合法地使用它;对我来说,既不将我的代码开源,也不购买许可证。因此我使用旧的第三方库:
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();
}
此代码适用于本地文件。
在我的(现实世界)案例中,我收到 Base64 字符串形式的 pdf 文件,从本地存储添加徽标,将其转换回 Base64 字符串并将其输出到网页上。
我强制将图像打开为 PNG(硬编码),因为我控制徽标的扩展名。如果需要,您可以动态设置图像格式。