Skip to content

Commit 7e272b1

Browse files
committed
html-to-pdf: optionally insert PDF link
Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 358a843 commit 7e272b1

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

assets/sass/print.scss

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,9 @@
3030
#dark-mode-button {
3131
display: none !important;
3232
}
33+
}
34+
35+
div#main .pdf-link img {
36+
float: right;
37+
height: 36px;
3338
}

script/html-to-pdf.js

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,23 @@ const path = require('path')
55
const url = require('url')
66
const { chromium } = require('playwright')
77

8+
const insertPDFLink = (htmlPath) => {
9+
const html = fs.readFileSync(htmlPath, 'utf-8')
10+
if (html.includes('class="pdf-link"')) {
11+
return
12+
}
13+
// get baseURL prefix via the `favicon.ico` link, it's in the top-level directory
14+
const match = html.match(/<link href="(.*?)favicon\.ico"/)
15+
if (!match) throw new Error('Failed to determine baseURL prefix from favicon.ico link')
16+
const img = `<img src="${match[1]}/images/pdf.png" />`
17+
const updatedHtml = html.replace(
18+
/<h1/,
19+
`<a class="pdf-link" href="${path.basename(htmlPath, '.html')}.pdf">${img}</a>$&`
20+
)
21+
if (updatedHtml === html) throw new Error('Failed to insert PDF link, no <h1> found')
22+
fs.writeFileSync(htmlPath, updatedHtml, 'utf-8')
23+
}
24+
825
const htmlToPDF = async (htmlPath, options) => {
926
if (!htmlPath.endsWith('.html')) {
1027
throw new Error(`Input file must have the '.html' extension: ${htmlPath}`)
@@ -31,18 +48,21 @@ const htmlToPDF = async (htmlPath, options) => {
3148
margin: { top: '1cm', bottom: '1cm', left: '1cm', right: '1cm' },
3249
})
3350
await browser.close()
51+
52+
if (options.insertPDFLink) insertPDFLink(htmlPath)
3453
}
3554

3655
const args = process.argv.slice(2)
3756
const options = {}
3857
while (args?.[0].startsWith('-')) {
3958
const arg = args.shift()
4059
if (arg === '--force' || arg === '-f') options.force = true
60+
else if (arg === '--insert-pdf-link' || arg === '-i') options.insertPDFLink = true
4161
else throw new Error(`Unknown argument: ${arg}`)
4262
}
4363

4464
if (args.length !== 1) {
45-
process.stderr.write('Usage: html-to-pdf.js [--force] <input-file.html>\n')
65+
process.stderr.write('Usage: html-to-pdf.js [--force] [--insert-pdf-link] <input-file.html>\n')
4666
process.exit(1)
4767
}
4868

0 commit comments

Comments
 (0)