Bretbas
Bretbas

Reputation: 192

Color with transparency in iText 7.1.4

Can I use a color with transparency in my programm, and I want to use this color in my PDF file. I create my pdf with iText 7.1.4, and I don't know how to set transpanrent to type of DeviceRgb:

public static DeviceRgb ToDeviceRgb(this System.Windows.Media.Color color) =>
    new DeviceRgb(color.R, color.G, color.B);

Is it possible to use color with transparency in iText7?

UPDATED:

I tried to do as Uladzimir Asipchuk told me, but I don't see any result: enter image description here

A template of the product card I can edit in my program(margin, padding, colors, fonts etc..). When setting up a template, some colors may have a alpha cannel(transparent), and I want to see this transparent factor in my PDF document. So, as Uladzimir Asipchuk advised me, I pass the opacity level to the second parameter in the SetBackgroundColor method:

public override Table CreateTemplate(Product product)
{
    if(product == null) throw new ArgumentNullException(nameof(product));

    // Create a table of the product card
    var productTable = new Table(new UnitValue[] { UnitValue.CreatePercentValue(40), UnitValue.CreatePercentValue(60) })
        .SetWidth(UnitValue.CreatePercentValue(100))
        .SetBackgroundColor(Settings.BackgroundColor.ToDeviceRgb(), 0.3f) // Here!!
        .SetMarginBottom(10)
        .SetKeepTogether(true);

    // Here we create a cell of the header, 
    // image, description, notes, prices of out product card

    return productTable;
}

And how can you see on the screenshot, I don't have a color transparent equal 0.3f

Upvotes: 0

Views: 4000

Answers (1)

Uladzimir Asipchuk
Uladzimir Asipchuk

Reputation: 2458

iText supports transparent colors for backgrounds. Please look at the samples there: https://github.com/itext/itext7/tree/develop/layout/src/test/resources/com/itextpdf/layout/OpacityTest

For example, with the next snippet I can get satisfactory results:

    Table table = new Table(1);
    table.addCell(new Cell().setBackgroundColor(new DeviceRgb(200, 100, 50), 1f).add(new Paragraph("Cell with Opacoty 1")));
    table.addCell(new Cell().setBackgroundColor(new DeviceRgb(200, 100, 50), 0.5f).add(new Paragraph("Cell with Opacoty 0.5")));
    table.addCell(new Cell().setBackgroundColor(new DeviceRgb(200, 100, 50), 0.1f).add(new Paragraph("Cell with Opacoty 0.1")));
    doc.add(table);

enter image description here

Upvotes: 2

Related Questions