TCPDF 指定 SVG 填充颜色

TCPDF Specifying SVG Fill Color

TCPDF 如何为 SVG 文件指定颜色? https://tcpdf.org

尽管文件中指定了其他颜色,但我的还是纯黑色,我似乎无法超越它。 理想情况下,我希望能够动态设置颜色

$pdf->SetTextColor(255,255,255);
$pdf->SetTextColorArray(255,255,255);
$pdf->SetFillColor(255,255,255);
$pdf->SetFillColorArray(255,255,255);
$pdf->SetDrawColor(255,255,255);
$pdf->ImageSVG($file=get_stylesheet_directory_uri().'/images/icon-bath.svg', $x=155, $y=124, $w=10, $h=10, $link='', $align='', $palign='', $border=0, $fitonpage=false);

遵循这些示例

https://tcpdf.org/examples/example_058/

https://hotexamples.com/examples/-/TCPDF/ImageSVG/php-tcpdf-imagesvg-method-examples.html

复杂的方法并稍微减慢了生成速度,但它有效

    $svg = get_stylesheet_directory_uri().'/images/icon.svg';
    $doc = new DOMDocument;
    $doc->load($svg);
    $xpath = new DOMXPath($doc);
    $xpath->registerNamespace('svg', 'http://www.w3.org/2000/svg');
    $path_list = $xpath->query('svg:path');
    $circle_list = $xpath->query('svg:circle');
    foreach ($path_list as $path) {
        $path->setAttribute('fill', '#FFFFFF');
    }
    foreach ($circle_list as $circle) {
        $circle->setAttribute('fill', '#FFFFFF');
    }
    $svgString = $doc->saveXML();

    $pdf->ImageSVG('@' . $svgString, $x=130, $y=124, $w=10, $h=10, $link='', $align='', $palign='', $border=0, $fitonpage=false);

改进了处理多个 SVG 文件的逻辑

function getModifiedSvgString($svg, $color) {
    $doc = new DOMDocument;
    $doc->load($svg);
    $xpath = new DOMXPath($doc);
    $xpath->registerNamespace('svg', 'http://www.w3.org/2000/svg');
    $path_list = $xpath->query('svg:path');
    $circle_list = $xpath->query('svg:circle');
    foreach ($path_list as $path) {
        $path->setAttribute('fill', $color);
    }
    foreach ($circle_list as $circle) {
        $circle->setAttribute('fill', $color);
    }
    return $doc->saveXML();
}

// Icon 1
$svg = get_stylesheet_directory_uri() . '/images/icon-1.svg';
$svgString = getModifiedSvgString($svg, $UserCompanyColourSecondaryFontHex);
$pdf->ImageSVG($file = '@' . $svgString, $x = 130, $y = 124, $w = 10, $h = 10, $link = '', $align = '', $palign = '', $border = 0, $fitonpage = false);

// Icon 2
$svg = get_stylesheet_directory_uri() . '/images/icon-2.svg';
$svgString = getModifiedSvgString($svg, $UserCompanyColourSecondaryFontHex);
$pdf->ImageSVG($file = '@' . $svgString, $x = 155, $y = 124, $w = 10, $h = 10, $link = '', $align = '', $palign = '', $border = 0, $fitonpage = false);

// Icon 3
$svg = get_stylesheet_directory_uri() . '/images/icon-3.svg';
$svgString = getModifiedSvgString($svg, $UserCompanyColourSecondaryFontHex);
$pdf->ImageSVG($file = '@' . $svgString, $x = 178, $y = 124, $w = 18, $h = 10, $link = '', $align = '', $palign = '', $border = 0, $fitonpage = false);