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