Skip to content

Commit 1d291a3

Browse files
committed
html-to-pdf: optionally insert PDF link
Signed-off-by: Johannes Schindelin <[email protected]>
1 parent 71c911b commit 1d291a3

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

assets/sass/print.scss

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
box-decoration-break: clone;
4040
}
4141

42-
#dark-mode-button {
42+
.pdf-link, #dark-mode-button {
4343
display: none !important;
4444
}
4545

@@ -137,4 +137,9 @@
137137
}
138138
}
139139
}
140+
}
141+
142+
div#main .pdf-link img {
143+
float: right;
144+
height: 36px;
140145
}

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].replace(/\/$/, '')}/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}`)
@@ -32,18 +49,21 @@ const htmlToPDF = async (htmlPath, options) => {
3249
margin: { top: '0cm', bottom: '0cm', left: '0cm', right: '0cm' },
3350
})
3451
await browser.close()
52+
53+
if (options.insertPDFLink) insertPDFLink(htmlPath)
3554
}
3655

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

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

0 commit comments

Comments
 (0)