c# .NET CORE 使用 ITextSharp 将具有透明度的图像添加到现有 PDF

标签 c# pdf itext .net-core

我的目标是将公司 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/

相关文章:

c# - 在 C# 中保存为事件

c# - 绑定(bind) MobileServiceCollection 未在 UI (MVVM) 中更新

c# - 在子列表中传递带有过滤器/组的对象

ios - 在 iOS 应用程序中为 pdf 和文档使用默认苹果图标?

android - 通过 Intent.ACTION_VIEW 查看 pdf 后应用程序关闭后退按钮

java - PDF文档可以包含 "unreachable"内容吗?

c# - 如何使用 iTextSharp 保留 CSS?

C# 和 Android/Java - 跨语言二进制流编写器/读取器? (对于原语和 UTF-8 字符串)

xml - 使用预先创建的 PDF 页面作为书籍封面

java - 文本 : Add New line when element is added to new Page