Skip to content

Instantly share code, notes, and snippets.

@maple3142
Last active March 6, 2024 06:25
Show Gist options
  • Save maple3142/39f2d0d9dbcf10e0c0c111f31542011a to your computer and use it in GitHub Desktop.
Save maple3142/39f2d0d9dbcf10e0c0c111f31542011a to your computer and use it in GitHub Desktop.
Convert markdown to pdf using pandoc and chromium
#!/bin/sh
source=$1
dest=$2
if [ -z "$source" ] || [ -z "$dest" ]; then
echo "Usage: $0 <source> <dest>"
exit 1
fi
tmpmd="$(mktemp tmp-XXXXXX.md)"
tmphtml="$(mktemp tmp-XXXXXX.html)"
tmpcss="$(mktemp tmp-XXXXXX.css)"
# simple preprocessing by replacing INCLUDE-FILE-CONTENT(filename) with the content of the file
if ! (python3 - "$source" "$tmpmd" <<EOF
import sys, re
def replace_include(match):
with open(match.group(1), 'r') as f:
return f.read()
with open(sys.argv[1], 'r') as f:
content = f.read()
content = re.sub(r'INCLUDE-FILE-CONTENT\(([^)]+)\)', replace_include, content)
with open(sys.argv[2], 'w') as f:
f.write(content)
EOF
); then
echo "Failed to preprocess $source"
exit 1
fi
cat <<EOF > "$tmpcss"
code {
color: #8a7449;
}
h1,
h2,
h3,
h4,
h5,
h6,
ul,
ol,
table,
p {
font-family: 'Noto Sans TC', Arial;
}
div.sourceCode {
padding: 0.5em;
}
@media print {
pre > code.sourceCode { white-space: pre-wrap; }
pre > code.sourceCode > span { text-indent: -5em; padding-left: 0; }
}
blockquote {
border-left: 4px solid #ddd;
color: #666;
margin: 0;
padding: 0 15px;
}
blockquote > :first-child {
margin-top: 0;
}
p:has(> img) {
text-align: center;
}
img {
max-width: 100%;
border: 0.5px solid #ddd;
}
div.page-break {
page-break-after: always;
}
/* table css taken from https://github.com/FabrizioMusacchio/GitHub_Flavor_Markdown_CSS */
table {
padding: 0;
border-collapse: collapse;
margin-left: auto;
margin-right: auto;
text-align: center;
}
table tr {
background-color: white;
margin: 0;
padding: 0;
}
table tr:nth-child(2n) {
background-color: #f8f8f8;
}
table tr th {
font-weight: bold;
background-color: #eefbff;
font-size: 14px;
margin: 0;
padding: 0.4em 0.35em 0.4em 0.35em;
}
table tr td {
margin: 0;
font-size: 14px;
padding: 5px 5px;
}
table tr th :first-child,
table tr td :first-child {
margin-top: 0;
}
table tr th :last-child,
table tr td :last-child {
margin-bottom: 0;
}
EOF
pandoc "$tmpmd" --mathjax --standalone -o "$tmphtml" --metadata title="UNUSED" --variable=title="" --css="$tmpcss" --highlight-style tango
DISPLAY='' chromium --headless=new --print-to-pdf="$dest" --print-to-pdf-no-header --no-pdf-header-footer --virtual-time-budget=10000 "$tmphtml"
rm "$tmpmd"
rm "$tmphtml"
rm "$tmpcss"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment