Search code examples
python-3.xsvgpngsvg-filters

Python Convert SVG with filters to PNG


The svg doesnot contains dropshadow filter, instead the filter comprises of simpler filters. The svg has a small shadow around geometries so as to give a 3D look. Here is the svg filter

<defs>
    <filter id="id1">
        <feGaussianBlur in="SourceGraphic" stdDeviation="4" />
        <feOffset dx="-5" dy="5" in="[]" result="offsetblur" />
        <feFlood flood-color="#95aec7" flood-opacity="0.8" />
        <feComposite in="[]" in2="offsetblur" operator="in" />
        <feMerge>
            <feMergeNode in="[]" />
            <feMergeNode in="SourceGraphic" />
        </feMerge>
    </filter>
</defs>

I have used cairosvg as well as wand, the result was a PNG but without those shadows which were responsible for 3D look. Any help would be appreciated.enter image description here


Solution

  • Unfortunately, CairoSVG supports only three filter effects: feBlend, feFlood, feOffset.

    But you can use Inkscape command-line interface to get full SVG support:

    import subprocess
    
    INKSCAPE_PATH = 'inkscape'  # for Linux
    # INKSCAPE_PATH = r'C:\Program Files\Inkscape\bin\inkscape.exe'  # for Windows
    
    subprocess.run([
        INKSCAPE_PATH,
        '--export-width=<width>',
        '--export-type=png',
        f'--export-filename={<output_file>}',
        <input_file>
    ])
    

    See Inkscape documentation for the full list of options.

    Of course, this is a less convenient than Cairo, because you have to create a temporary file if you generate the SVG on the fly. But otherwise it works fine for me.