Created
April 29, 2020 07:18
-
-
Save s417-lama/84bf66de1096c4587e8187092fb41684 to your computer and use it in GitHub Desktop.
Reliable way to convert an SVG file to a PDF file using headless Chrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Convert an SVG file to a PDF file by using headless Chrome. | |
# | |
if [ $# -ne 2 ]; then | |
echo "Usage: ./svg2pdf.bash input.svg output.pdf" 1>&2 | |
exit 1 | |
fi | |
INPUT=$1 | |
OUTPUT=$2 | |
HTML=" | |
<html> | |
<head> | |
<style> | |
body { | |
margin: 0; | |
} | |
</style> | |
<script> | |
function init() { | |
const element = document.getElementById('targetsvg'); | |
const positionInfo = element.getBoundingClientRect(); | |
const height = positionInfo.height; | |
const width = positionInfo.width; | |
const style = document.createElement('style'); | |
style.innerHTML = \`@page {margin: 0; size: \${width}px \${height}px}\`; | |
document.head.appendChild(style); | |
} | |
window.onload = init; | |
</script> | |
</head> | |
<body> | |
<img id=\"targetsvg\" src=\"${INPUT}\"> | |
</body> | |
</html> | |
" | |
tmpfile=$(mktemp XXXXXX.html) | |
trap "rm -f $tmpfile" EXIT | |
echo $HTML > $tmpfile | |
google-chrome --headless --disable-gpu --print-to-pdf=$OUTPUT $tmpfile |
For everyone looking for a solution to the annoying blank page being appended: when sizing is not super critical just add 1px to the height in line 29.
Looking forward to dominant-baseline
support in librsvg2 ... but in the meantime this works nicely.
I had a problem with a UTF-8 char.
That's why I propose to update the <head>
with <meta charset="UTF-8">
inside.
Anyone knows what's the backend is used to implement conversion from SVG to PS in chromium? Thanks in advance!
I didn't try this, but by including the SVG as an image in an HTML document, doesn't it lose text information (it's rasterized for security)? Therefore, I'm guessing the PDF produced will also not contain text (that can be searched). Maybe not a huge problem...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks.
That's good to know. The svgs I need to convert for SymPy get messed up in some way or other with every tool I've tried (Inkscape, rsvg-convert, convert, cairosvg) except for Chrome.