Skip to content

Commit df355ea

Browse files
committed
html-to-pdf: deal with HUGO_RELATIVEURLS=false
When Hugo is told to use absolute URLs, it generates links and image references that start with a slash, which are misinterpreted when loading the file into a browser via the file: protocol. Rewrite those URLs to point to the local filesystem. To do so, we use the very convenient `page.route()` functionality of Playwright. Unfortunately, we do not get the "URLs" that start with a slash, but instead we get bogus `file:///<wrong-path>` URLs. Luckily, those wrong paths do not start with the absolute path of the `public/` directory, that's what we can use as tell-tale that an incorrect URL needs rewriting. Signed-off-by: Johannes Schindelin <[email protected]>
1 parent aec7dfa commit df355ea

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

script/html-to-pdf.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,23 @@ const htmlToPDF = async (htmlPath, options) => {
3838
const page = await browser.newPage()
3939

4040
const htmlPathURL = url.pathToFileURL(htmlPath).toString()
41-
4241
console.log(`Processing ${htmlPathURL}...`)
42+
43+
// Work around HUGO_RELATIVEURLS=false by rewriting the absolute URLs
44+
const baseURLPrefix = htmlPathURL.substring(0, htmlPathURL.lastIndexOf('/public/') + 8)
45+
await page.route(/^file:\/\//, async (route, req) => {
46+
// This _will_ be a correct URL when deployed to https://whatevers/, but
47+
// this script runs before deployment, on a file:/// URL, where we need to
48+
// be a bit clever to give the browser the file it needs.
49+
const original = req.url()
50+
const url =
51+
original.startsWith(baseURLPrefix)
52+
? original
53+
: original.replace(/^file:\/\/\/([A-Za-z]:\/)?(git-scm\.com\/)?/, baseURLPrefix)
54+
if (url !== original) console.error(`::notice::Rewrote ${original} to ${url}`)
55+
await route.continue({ url })
56+
})
57+
4358
await page.goto(htmlPathURL, { waitUntil: 'load' })
4459

4560
await page.pdf({

0 commit comments

Comments
 (0)