Skip to content

Commit 6718a27

Browse files
committed
html-to-pdf: optionally insert PDF link
Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 0c4104a commit 6718a27

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
@@ -14,4 +14,9 @@
1414
#dark-mode-button {
1515
display: none !important;
1616
}
17+
}
18+
19+
div#main .pdf-link img {
20+
float: right;
21+
height: 36px;
1722
}

script/html-to-pdf.js

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

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

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

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

0 commit comments

Comments
 (0)