@@ -4,6 +4,23 @@ const fs = require('fs')
4
4
const path = require ( 'path' )
5
5
const { chromium } = require ( 'playwright' )
6
6
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 ( / < l i n k h r e f = " ( .* ?) f a v i c o n \. i c o " / )
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
+ / < h 1 / ,
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
+
7
24
const htmlToPDF = async ( htmlPath , options ) => {
8
25
if ( ! htmlPath . endsWith ( '.html' ) ) {
9
26
throw new Error ( `Input file must have the '.html' extension: ${ htmlPath } ` )
@@ -30,18 +47,21 @@ const htmlToPDF = async (htmlPath, options) => {
30
47
margin : { top : '1cm' , bottom : '1cm' , left : '1cm' , right : '1cm' } ,
31
48
} )
32
49
await browser . close ( )
50
+
51
+ if ( options . insertPDFLink ) insertPDFLink ( htmlPath )
33
52
}
34
53
35
54
const args = process . argv . slice ( 2 )
36
55
const options = { }
37
56
while ( args ?. [ 0 ] . startsWith ( '-' ) ) {
38
57
const arg = args . shift ( )
39
58
if ( arg === '--force' || arg === '-f' ) options . force = true
59
+ else if ( arg === '--insert-pdf-link' || arg === '-i' ) options . insertPDFLink = true
40
60
else throw new Error ( `Unknown argument: ${ arg } ` )
41
61
}
42
62
43
63
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' )
45
65
process . exit ( 1 )
46
66
}
47
67
0 commit comments