Search code examples
pdflib

PDFlib - controlling background and opacity of text color, text background and text stroke


I'm trying to set separate values of background and opacity of text color, text background and text stroke (outline).

Code below

$p->save();
$p->setfont($font, 240);
$p->set_gstate($p->create_gstate('opacityfill=1 opacitystroke=1')); // Both fill and stroke are opaque
$p->set_graphics_option('fillcolor={rgb 0.075 0.973 0.024} strokecolor={rgb 0 0 1}');
$p->fit_textline('QfjIL', 30, 30, 'matchbox={boxheight={88% 24.5%} borderwidth=0 round=0 fillcolor={rgb 1 1 0}} charspacing=0 textrendering=2 strokewidth=10 position={left top}');
$p->restore();

results in:

enter image description here

Yellow background, blue letter stroke and green letter fill are opaque - as expected.

Adding opacity for fill and stroke to gstate as:

$p->save();
$p->setfont($font, 240);
$p->set_gstate($p->create_gstate('opacityfill=0.3 opacitystroke=0.3'));
$p->set_graphics_option('fillcolor={rgb 0.075 0.973 0.024} strokecolor={rgb 0 0 1}');
$p->fit_textline('QfjIL', 30, 30, 'matchbox={boxheight={88% 24.5%} borderwidth=0 round=0 fillcolor={rgb 1 1 0}} charspacing=0 textrendering=2 strokewidth=10 position={left top}');
$p->restore();

results in ALL OF background, fill and stroke using the same opacity:

enter image description here

Question:

How can I control separately text background opacity (yellow), letter stroke opacity (blue) and letter fill opacity (green)?


Solution

  • this is the expected result, as you specify the graphics state for all fill and stroke content.

    You should set the opacity gstate only for the text, and a solid gstate for the matchbox.

    $p->save();
    $gstate_solid = $p->create_gstate('opacityfill=1 opacitystroke=1');
    $gstate = $p->create_gstate('opacityfill=0.3 opacitystroke=0.3');
    $p->fit_textline('QfjIL', 30, 30, 
       'fontname=NotoSerif-Regular encoding=unicode fontsize=240 ' . 
       'matchbox={boxheight={88% 24.5%} borderwidth=0 round=0 fillcolor={rgb 1 1 0} gstate=' . $gstate_solid . '} '
       'charspacing=0 textrendering=2 strokewidth=10 position={left top} gstate=' . $gstate . 'fillcolor={rgb 0.075 0.973 0.024} strokecolor={rgb 0 0 1}');
    $p->restore();
    

    this give the following result, I guess this is the expected result.

    enter image description here

    you find within the PDFlib 9.2 API reference, chapter 6.2 "Matchboxes" all details about the matchbox options.