Free Support Forum - aspose.com

Add a transparent PNG image to a PDF file in C# using Aspose.PDF for .NET

Hi,

I am trying to add a transparent PNG image to a PDF file. When I do this, the transparent background is rendered as black instead of transparent.

How do I do this?

Thanks,

Chris

Hi Chris,

Thank you for considering Aspose.

Can you please provide your image and code so we can test it?

Hi,

It seems that this is only a problem when I try to add the image from memory. When I save it to a file first, then it works fine. Here is the code I am using to add it from memory and I have attached the image file and the PDF produced.

Dim PDFDocument As New Aspose.Pdf.Pdf

Dim MasterSection As Aspose.Pdf.Section

Dim NewImage As Aspose.Pdf.Image

Dim stmImage As System.IO.MemoryStream

Dim bmp As Drawing.Image

MasterSection = New Section

PDFDocument.Sections.Add(MasterSection)

NewImage = New Aspose.Pdf.Image(MasterSection)

bmp = Drawing.Bitmap.FromFile("test2.png")

stmImage = New System.IO.MemoryStream

bmp.Save(stmImage, System.Drawing.Imaging.ImageFormat.Png)

With NewImage

.ImageInfo.OpenType = ImageOpenType.Memory

.ImageInfo.MemoryData = stmImage.ToArray

.ImageInfo.ImageFileType = ImageFileType.MemoryBmp

End With

stmImage.Close()

MasterSection.Paragraphs.Add(NewImage)

PDFDocument.Save("test.pdf")

Hi,

Please take the following code as an example to resolve the problem. It works well in my test.

[C#]
Aspose.Pdf.Pdf pdf = new Aspose.Pdf.Pdf();
Aspose.Pdf.Section sec = pdf.Sections.Add();
Aspose.Pdf.Image png = new Aspose.Pdf.Image(sec);
System.Drawing.Bitmap bm;
bm = new System.Drawing.Bitmap("F:/temp/test2.png");
MemoryStream ms = new MemoryStream();
bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
png.ImageInfo.ImageFileType = ImageFileType.Png;
png.ImageInfo.ImageStream = ms;
sec.Paragraphs.Add(png);
pdf.Save(@"F:/temp/test.pdf");

Thanks.

Best regards.

Worked perfectly thanks, so what is the difference between ImageInfo.MemoryData and ImageInfo.ImageStream?

Hi,

As you can see from the API reference, the ImageInfo.MemoryData is obsolete. Please use ImageInfo.ImageStream instead.