Socket
Book a DemoInstallSign in
Socket

@alessiofrittoli/html-to-pdf

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@alessiofrittoli/html-to-pdf

Easily convert HTML to PDF

latest
Source
npmnpm
Version
1.1.0
Version published
Weekly downloads
29
-87.87%
Maintainers
1
Weekly downloads
 
Created
Source

Html to PDF 📓

NPM Latest Version Coverage Status Socket Status NPM Monthly Downloads Dependencies

GitHub Sponsor

Easily convert HTML to PDF

Table of Contents

Getting started

Run the following command to start using html-to-pdf in your projects:

npm i @alessiofrittoli/html-to-pdf

or using pnpm

pnpm i @alessiofrittoli/html-to-pdf

[!WARNING] This package uses puppeteer and cannot be external, thus it needs to be installed in your project by running

pnpm i puppeteer

then import it and easily use it like this

import { PDF } from "@alessiofrittoli/html-to-pdf";

const content = `
  <html>
    <body>
      <h1>My first PDF!</h1>
    </body>
  </html>
`;

const path = "folder/my-first-pdf.pdf";

await new PDF({ content, path }).generate();

API Reference

Supported input types

We accept multiple input types to provide high flexibility by using coerceToUint8Array() exported by @alessiofrittoli/crypto-buffer which gives us a standard view of the provided data.

See coerceToUint8Array() for a list of supported data type.

Examples

Basic usage

import { PDF } from "@alessiofrittoli/html-to-pdf";

const content = `
  <html>
    <body>
      <h1>My first PDF!</h1>
    </body>
  </html>
`;

const buffer = await new PDF({ content }).generate();
// do something with pdf `buffer`

Generate a PDF from a webpage

import { PDF } from "@alessiofrittoli/html-to-pdf";

const url = "https://google.com";

const buffer = await new PDF({ url }).generate();
// do something with pdf `buffer`

Store generated PDF into a file

import { join } from "path";
import { PDF } from "@alessiofrittoli/html-to-pdf";

const content = `...`;
const path = "folder/my-first-pdf.pdf";

const buffer = await new PDF({ content, path }).generate();
// do something else with pdf `buffer`

Disabling inline CSS

By default all styles defined in a <style /> HTML tag get applied to the corresponding HTML NodeElement. You can opt-out by this behavior by setting inlineCss to false.

This may be usefull to properly load custom fonts using @font-face declaration. If you still want to inline CSS (which is recommended) but load custom fonts, please read Loading custom fonts section.

import { PDF } from "@alessiofrittoli/html-to-pdf";

const content = `
  <html>
    <head>
      <style>
        ...
      </style>
    </head>
    <body>
      <h1>My first PDF!</h1>
    </body>
  </html>
`;

// parsed markup will contain `<style />` tag before rendering the PDF.
await new PDF({ content }).generate();

Loading custom fonts

You can load additional styles that won't be parsed before rendering the PDF by defining URLs, paths or CSS declarations through the GeneratePdfOptions.styles option.

Load custom font from remote URL
import { PDF, type StyleTagsOptions } from "@alessiofrittoli/html-to-pdf";

const content = `
  <html class='corinthia-regular'>
    <head>
      <style>
        .corinthia-regular {
          font-family: "Corinthia", cursive;
          font-weight: 400;
          font-style: normal;
        }
      </style>
    </head>
    <body>
      <h1>My first PDF!</h1>
    </body>
  </html>
`;

const styles: StyleTagsOptions = [
  { url: "https://fonts.googleapis.com/css2?family=Corinthia&display=swap" },
];

const pdf = new PDF({ content, styles });
Load custom font declaration from local file
import { join } from "path";
import { PDF, type StyleTagsOptions } from "@alessiofrittoli/html-to-pdf";

const content = `
  <html class='corinthia-regular'>
    <head>
      <style>
        .corinthia-regular {
          font-family: "Corinthia", cursive;
          font-weight: 400;
          font-style: normal;
        }
      </style>
    </head>
    <body>
      <h1>My first PDF!</h1>
    </body>
  </html>
`;

const styles: StyleTagsOptions = [
  { path: join(process.cwd(), "font-css-file-declaration.css") },
];

const pdf = new PDF({ content, styles });
/* font-css-file-declaration.css */
/* latin */
@font-face {
  font-family: "Corinthia";
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: url(https://fonts.gstatic.com/s/corinthia/v13/wEO_EBrAnchaJyPMHE01VvoK_kgXiQ.woff2)
    format("woff2");
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
    U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193,
    U+2212, U+2215, U+FEFF, U+FFFD;
}
Load custom font from local file

If you need to load a custom font that will be available in off-line conditions or you don't want to depend on external resources, you can embed the font by encoding it to base64.

import { join } from "path";
import { Base64 } from "@alessiofrittoli/crypto-encoder";
import { PDF, type StyleTagsOptions } from "@alessiofrittoli/html-to-pdf";

const content = `
  <html class='corinthia-regular'>
    <head>
      <style>
        .corinthia-regular {
          font-family: "Corinthia", cursive;
          font-weight: 400;
          font-style: normal;
        }
      </style>
    </head>
    <body>
      <h1>My first PDF!</h1>
    </body>
  </html>
`;

const fontBasePath = resolve(process.cwd(), "assets/fonts/Corinthia");
const fontfile = readFileSync(join(fontBasePath, "local-font-filename.woff2"));
const fontBase64 = Base64.encode(fontfile, false);
const css = readFileSync(
  join(fontBasePath, "font-css-file-declaration.css"),
  "utf-8"
).replace("url(custom-font-url)", `url(data:font/woff2;base64,${fontBase64})`);

const styles: StyleTagsOptions = [{ content: css }];

const pdf = new PDF({ content, styles });
/* font-css-file-declaration.css */
/* latin */
@font-face {
  font-family: "Corinthia";
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: url(custom-font-url) format("woff2");
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
    U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193,
    U+2212, U+2215, U+FEFF, U+FFFD;
}

Generating multiple pdf with the same constructed instance

You can generate multiple PDFs with a single constructed instance of PDF which shares common options and eventually override or add new options for each generated pdf.

This is possible since customization options can be either passed to the PDF constructor or to the PDF.generate() method.

[!WARNING] Note that you cannot generate multiple PDFs with the same ReadableStream since it can be read once. If you still need to do so, please set the content once by passing the ReadableStream in the constructor. Please refer to the Rendering Readable Streams section for more info.

import { PDF } from "@alessiofrittoli/html-to-pdf";

const pdf = new PDF({
  format: "A4",
  styles: [{ path: "/absolute/path/to/custom/style.css" }],
});

await pdf.generate({ content: "PDF 1", path: "folder/pdf-1.pdf" });
await pdf.generate({
  content: "PDF 2",
  path: "folder/pdf-2.pdf",
  format: "A3",
  landscape: true,
});

Rendering Readable Streams

In addition to the various supported input types, this library also supports ReadableStreams (it happens more often than you think).

In this example we render async React Server Components inside a PDF page.

Asynchronous React Server Components needs to be rendered using renderToReadableStream() which returns a Promise that resolves a ReadableStream so this is a perfect example on how to deal with it.

import { PDF } from "@alessiofrittoli/html-to-pdf";

const MyAsyncPdfComponent: React.FC = async () => {
  await { ...someAsyncTask };

  return (
    <html>
      <body>
        <h1>My React PDF Component</h1>
      </body>
    </html>
  );
};

const { renderToReadableStream } = await import("react-dom/server");

const content = await renderToReadableStream(<MyAsyncPdfComponent />);
const pdf = new PDF({ content });

await pdf.generate();

Development

Install depenendencies

npm install

or using pnpm

pnpm i

Build the source code

Run the following command to test and build code for distribution.

pnpm build

ESLint

warnings / errors check.

pnpm lint

Jest

Run all the defined test suites by running the following:

# Run tests and watch file changes.
pnpm test:watch

# Run tests in a CI environment.
pnpm test:ci

Run tests with coverage.

An HTTP server is then started to serve coverage files from ./coverage folder.

⚠️ You may see a blank page the first time you run this command. Simply refresh the browser to see the updates.

test:coverage:serve

Contributing

Contributions are truly welcome!

Please refer to the Contributing Doc for more information on how to start contributing to this project.

Help keep this project up to date with GitHub Sponsor.

GitHub Sponsor

Security

If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and NOT open a public issue. We will investigate all legitimate reports. Email security@alessiofrittoli.it to disclose any security vulnerabilities.

Made with ☕

avatar
Alessio Frittoli
https://alessiofrittoli.it | info@alessiofrittoli.it

Keywords

nodejs

FAQs

Package last updated on 21 Dec 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts