How to create/insert image with opacity

Currently we have license to Gembox.PDF only. I would like to write/draw an image as background / foreground item.

My question is that. Is there a way to control the opacity for imge drawn on the PDF? I see ExplicitMask and SoftMask as get-only. Not sure if it is relevant though.

Thank you a lot!

Hi,

The following code snippet is a modification of the example Export and import images to PDF file with C# / VB.NET applications.

var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

using (var document = new PdfDocument())
{
    var image = PdfImage.Load(Path.Combine(desktop, "FragonardReader.jpg"));

    var page = document.Pages.Add();

    // Add some initial content to the page.
    var pathFill = page.Content.Elements.AddPath().AddRectangle(0, 0, image.Size.Width - 100, image.Size.Height - 100).Format.Fill;
    pathFill.IsApplied = true;
    pathFill.Color = PdfColors.Red;

    // Group existing page's content so that it doesn't affect on the added image.
    page.Content.Elements.Group(page.Content.Elements.First, page.Content.Elements.Last);

    // Add a group (into which image will be added) at the end of the content (this will make the image foreground).
    var imageGroup = page.Content.Elements.AddGroup();

    // Draw image in the group.
    double x = 50, y = page.CropBox.Top - 50 - image.Size.Height;
    imageGroup.DrawImage(image, new PdfPoint(x, y));

    // Set the opacity of the group (this will also set the opacity of the descendant image content).
    imageGroup.Format.Fill.Opacity = 0.5;

    page = document.Pages.Add();

    // Add some initial content to the page.
    pathFill = page.Content.Elements.AddPath().AddRectangle(0, 0, image.Size.Width - 100, image.Size.Height - 100).Format.Fill;
    pathFill.IsApplied = true;
    pathFill.Color = PdfColors.Red;

    // Group existing page's content so that it doesn't affect on the added image.
    page.Content.Elements.Group(page.Content.Elements.First, page.Content.Elements.Last);

    // Add a group (into which image will be added) at the beginning of the content (this will make the image background).
    imageGroup = page.Content.Elements.AddGroup(page.Content.Elements.First);

    // Draw image in the group.
    x = 50; y = page.CropBox.Top - 50 - image.Size.Height;
    imageGroup.DrawImage(image, new PdfPoint(x, y));

    // Set the opacity of the group (this will also set the opacity of the descendant image content).
    imageGroup.Format.Fill.Opacity = 0.5;

    document.Save(Path.Combine(desktop, "Import Images.pdf"));
}

This code snippet creates a PDF file with two pages.
On the first page, the image is foreground content, but the rest of the page’s content (red rectangle) is also visible because the image is transparent.
On the second page, the image is background content and because of that the rest of the page’s content (red rectangle) is rendered over it.

Regards,
Stipo

2 Likes