SVG Rasterisation
Don’t spend so much time fiddling around with imagemagick, inkscape, or wkhtmltopdf when trying to rasterise complex SVG images.
Chrome can render SVGs (almost) perfectly, so use its native headless mode!
Here’s an example command to render an SVG to a transparent PNG:
google-chrome --headless --disable-gpu --hide-scrollbars --default-background-color=0 \
--window-size=1000,1000 --screenshot=raster.png vector.svg
I ran into constant issues while batch-rendering dynamically-generated SVG images that contained:
- SVG filters
- Blending modes
- Text on paths
- Custom fonts
- CSS custom properties
No tool could support even a few of those, let alone all. Except Chrome.
And then there’s the long rendering times. 80 seconds to render a 2048×2048 PNG? Chrome did it in 4.
Run Chrome from PHP
$png_path = '/some/path/to/raster.png';
$svg_path = '/some/path/to/vector.svg';
$resolution = '512,512';
$output = [];
$return = null;
exec( implode( ' ', [
'google-chrome',
'--headless',
'--disable-gpu',
'--hide-scrollbars',
'--default-background-color=0',
'--window-size=' . escapeshellarg( $resolution ),
'--screenshot=' . escapeshellarg( $png_path ),
escapeshellarg( $svg_path ),
'2>&1',
] ), $output, $return );
Install Chrome using Ansible
---
- name: Add Google signing key
apt_key:
url: "https://dl-ssl.google.com/linux/linux_signing_key.pub"
- name: Add Google APT repository
apt_repository:
filename: "google.list"
repo: "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main"
- name: Install Google Chrome
apt:
package: google-chrome-stable
Install Chrome on Ubuntu
wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'
sudo apt update
sudo apt install google-chrome-stable