@@ -4,6 +4,23 @@ const fs = require('fs')
44const path = require ( 'path' )
55const { 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 ( / < 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+
724const 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
3554const args = process . argv . slice ( 2 )
3655const options = { }
3756while ( 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
4363if ( 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