Background image are often used in a document for making its appearance be more beautiful. But sometimes we find that texts are not difficult to read because of background dark color. In order to make text to be shown more clearly with background image, we can set transparency for background image. In this post, I will introduce a method about how to set image transparency in PDF by using C#.
I prepare one image firstly, and then set transparency for it. Actually, when setting transparency, we need to consider its percentage, for example, 100% transparency which means fully transparent. In this example, I will show images with different transparency in a PDF document.
Also, I use Spire.PDF to help me realize this function. Therefore, I add its dll file as reference.
Steps:
Main Coding:
using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace GraphicsTransparency
{
class transparency
{
static void Main(string[] args)
{
//Create
PdfDocument doc = new PdfDocument();
//Add Section
PdfSection section = doc.Sections.Add();
//Load image
PdfImage image = PdfImage.FromFile(@"D:\work\My Documents\Adele19.jpg");
float imageWidth = image.PhysicalDimension.Width / 2;
float imageHeight = image.PhysicalDimension.Height / 2;
foreach (PdfBlendMode mode in Enum.GetValues(typeof(PdfBlendMode)))
{
PdfPageBase page = section.Pages.Add();
float pageWidth = page.Canvas.ClientSize.Width;
float y = 0;
//Title
y = y + 20;
PdfBrush brush = new PdfSolidBrush(Color.DarkOrange);
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Calibri", 15f, FontStyle.Regular));
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
String text = String.Format("Transparency Blend Mode: {0}", mode);
page.Canvas.DrawString(text, font, brush, pageWidth / 2, y, format);
SizeF size = font.MeasureString(text, format);
y = y + size.Height + 6;
//Set Transparency
page.Canvas.DrawImage(image, 0, y, imageWidth, imageHeight);
page.Canvas.Save();
float d = (page.Canvas.ClientSize.Width – imageWidth) / 5;
float x = d;
y = y + d / 2;
for (int i = 0; i < 5; i++)
{
float alpha = 1.0f / 6 * (5 – i);
page.Canvas.SetTransparency(alpha, alpha, mode);
page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight);
x = x + d;
y = y + d / 2;
}
page.Canvas.Restore();
}
//Save
doc.SaveToFile("Transparency.pdf");
doc.Close();
//Launch
System.Diagnostics.Process.Start("Transparency.pdf");
}
}
}
Result Shown by Following:


Note: Two of results are shown.
___________________________________________________________________
Click Here to Learn more about Spire.PDF
Click Here to Download Spire.PDF