html-to-pdf-converter v0.3.0
html-to-pdf-converter
HTML to PDF converter with support for HEADERS, FOOTERS and page numbers.
Using headless chrome via puppeteer and than modifying generated pdf via HummusJS to add headers and footers with page numbers
Install
npm install html-to-pdf-converter
Usage
All fonts that are used inside passed html document need to be installed on the machine where the conversion is going to happen.
Headers and footers could be generated by passing either as a separate html document or as a single line that can be customized to left
, center
and right
sections.
There are two special placeholders {page}
and {pages}
that could be used inside your document footers and headers, which are going to be replaced by current page number and total pages count respectively.
mkCompoundPdf
accepts array of html documents that would be concatenated. Total page count is going to be the sum of the final generated pdf.
All documents had to be proper HTML documents.
For usage checkout ./src/compound-pdf.spec.ts file. For JS strip all types.
import { initialize, MkPdfOptions, HtmlToPdfConverter, Millimeters } from 'html-to-pdf-converter'
Define page print margins.
const margin: PrintMargin = PrintMargin.ofMillimeters({
top: 7.5,
right: 15,
bottom: 5,
left: 17,
})
Get converter
converter = await initialize(puppeteerOptions)
It returns promise which resolves to a few functions:
export interface HtmlToPdfConverter {
mkCompoundPdf: (contents: PdfContentWithSlots[]) => Promise<Buffer>
mkPdf: (content: PdfContent) => Promise<Buffer>
destroy: () => Promise<void>
}
mkCompoundPdf
could be used to create a single multi page pdf from various content, where each content could have it's own different header or footer, while current page and total pages would be counted in sequence.
mkPdf
will create pdf from html. Page size and margins could be specified for the output pdf.
Do not forget to call converter.destroy()
before app exit to clean resources.
Roadmap
- add html headers
- add text headers
- document API
- provide more examples using
javascript
- load document from URL, wait for all resources do be loaded (css, js, images, fonts, etc.), wait for javascript execution and than generate PDF
- setup CI
- cover with tests
- add performance tests
- option to configure reusing chrome instances
- use puppeteer header/footer template only when there is no need for different headers/footers per different pages
- use nvm inside docker image
How to run tests
Docker is used to run tests due to minor difference in generated pdfs across various environments.
Build container:
docker build -t html-to-pdf-converter .
To run tests (note that this will give rw rights to docker container to projects folder):
docker-compose run --rm converter npm run test
In watch mode:
docker-compose run --rm converter npm run test:watch
If pdf comparing tests would fail, an image diff would be generated inside output
folder.