【发布时间】:2017-12-01 19:36:37
【问题描述】:
我有一个传入的 jpg 文件,我可以将颜色设置为透明。当我将图像添加到另一个图像时,这非常有效。
我正在尝试使用 iTextSharp 将相同的图像添加到 PDF,但我无法使透明度正常工作。
我尝试了两种方法,但都不起作用。第一种方法是在位图中打开图像,设置透明度,然后在 PDF 中使用该位图对象。第二种方法(此处显示)是将位图保存到磁盘并将文件打开到 iTextSharp 图像中。
using (Bitmap b = new Bitmap(Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + ImageFileName))))
{
b.MakeTransparent(Color.White);
b.Save(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + GuidFileName), System.Drawing.Imaging.ImageFormat.Png);
ImageFileName = GuidFileName;
iTextSharp.text.Image savedImage = iTextSharp.text.Image.GetInstance(Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + GuidFileName)), iTextSharp.text.Color.WHITE);
savedImage.SetAbsolutePosition(Convert.ToSingle(x + 1.0), Convert.ToSingle(imageY + 12) - Convert.ToSingle(h));
savedImage.ScaleToFit(Convert.ToSingle(w), Convert.ToSingle(h));
contentByte.AddImage(savedImage, true);
}
我看到有一个透明选项...
savedImage.Transparency = ???
但我不知道在值中添加什么。我在搜索中找不到任何内容。
【问题讨论】:
-
这里有些东西没有意义,因为 JPEG 不支持透明度。你如何“将图像添加到另一个图像”?
-
JPEG 不支持透明度,但试试看。它将变得透明,然后您可以将其保存为 .png。这就是 MakeTransparent 所做的。在这个问题中,我不是添加到另一个图像,而是添加到 PDF。要将透明的“jpg”添加到另一个图像... Bitmap b = (Bitmap)Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + GuidFileName)); b.MakeTransparent(Color.White); graphics.DrawImage(b, x, y - 10, newWidth, newHeight);
-
你是如何检查你的两次尝试是否成功的?
-
通过运行它并检查输出文件......也可以通过点击我的断点来确保它实际运行了代码。另外,当我创建一个透明的 .png 文件(在上面的代码中)时,我手头有文件,而且 png 绝对是透明的。只是放在 PDF 上时不透明。
-
仅供参考。我改变了这个...... iTextSharp.text.Image savedImage = iTextSharp.text.Image.GetInstance(Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + GuidFileName)), iTextSharp。文本.颜色.白色);为此... iTextSharp.text.Image savedImage = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + GuidFileName));以便它直接从文件中获取,而不是首先加载到图像对象中。现在,我的 PDF 显示黑色背景,它应该是透明的。
标签: c# itext pdf-generation