npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@akcraft/html2pdf-sdk

v1.2.1

Published

TypeScript SDK for the html2pdf API - convert HTML to PDF with a typed, promise-based client.

Readme

@akcraft/html2pdf-sdk

TypeScript SDK for the html2pdf API — convert HTML to PDF with a single request.

The SDK wraps the html2pdf REST API and provides a typed, promise-based client with automatic error handling. It is written in TypeScript and ships with its own type definitions.


Table of contents


Installation

npm install @akcraft/html2pdf-sdk

The SDK is ESM-only ("type": "module") and requires Node 18+ (native fetch).

From git

To use an unreleased build, install directly from the repository and point at a branch, tag, or commit:

npm install git+https://github.com/<owner>/<repo>.git#main

From a local path

If the SDK lives in a sibling directory (e.g. a monorepo), reference it with a relative file: path:

npm install file:../sdk

Quickstart

import { Html2PdfClient, PaperFormat, PdfOrientation } from '@akcraft/html2pdf-sdk';

// Initialize client with your API key

const client = new Html2PdfClient('YOUR_API_KEY');

const job = await client.sendHtmlRequest({
  userId: 'YOUR_ACCOUNT_ID',
  content: '<h1>Hello</h1>',
  options: { format: PaperFormat.A4, orientation: PdfOrientation.PORTRAIT },
});

const { pdfUrl } = await client.getPdfUrl(job.fileName);
console.log(pdfUrl);

Getting an API key

  1. Open the html2pdf dashboard.
  2. Go to API keys.
  3. Click Create key.

A new key is generated with the prefix h2p_live_. The raw key is shown only once, at creation time — copy it immediately. The dashboard stores only a SHA-256 hash of the key, so it cannot be recovered later. If you lose it, create a new key.

userId (Account ID)

The userId field is the Account ID shown in the dashboard under Settings. It is a UUID that must own the API key you are using.


Request example

A full sendHtmlRequest call with all fields:

import { Html2PdfClient, PaperFormat, PdfOrientation } from '@akcraft/html2pdf-sdk';

const client = new Html2PdfClient('h2p_live_...');

const response = await client.sendHtmlRequest({
  // Optional: only needed if you did NOT pass an apiKey to the constructor.
  // When the constructor key is present it is sent via the `x-api-key` header
  // and this field is ignored.
  apikey: 'h2p_live_...',

  // Required: the Account ID from dashboard Settings.
  userId: 'YOUR_ACCOUNT_ID',

  // Required: the HTML content to convert.
  content: '<h1>Hello</h1><p>This becomes a PDF.</p>',

  // Optional: custom output filename (e.g. 'monthly-invoice.pdf').
  filename: 'monthly-invoice.pdf',

  // Optional: when true, returns raw binary ArrayBuffer instead of JSON.
  // sendBuffer: true,

  // Optional: PDF formatting options.
  options: {
    format: PaperFormat.A4,
    orientation: PdfOrientation.PORTRAIT,
  },
});

The API key is sent as the x-api-key header on every request. The body apikey field is optional and kept for backward compatibility — it is only used when no key was provided to the constructor.


Response example

sendHtmlRequest

By default, returns SendHTMLRequestResponse:

{
  status: Html2PdfStatus, // PENDING | PROCESSING | COMPLETED | FAILED
  jobId: string,          // UUID
  pdfUrl?: string,        // Optional URL to the generated PDF
  fileName: string,       // File name of the generated PDF
}

When sendBuffer: true is passed, sendHtmlRequest returns an ArrayBuffer containing the raw PDF binary:

const buffer = await client.sendHtmlRequest({
  userId: 'YOUR_ACCOUNT_ID',
  content: '<h1>Hello</h1>',
  sendBuffer: true,
}) as ArrayBuffer;

getPdfUrl

GetPdfUrlResponse:

{
  jobId: string,   // UUID
  pdfUrl: string,  // URL to the generated PDF
  fileName: string // File name of the generated PDF
}

Error handling

Any non-2xx response throws an Html2PdfError. It extends the built-in Error and carries the following properties:

| Property | Type | Description | | ------------ | -------- | -------------------------------------------------- | | statusCode | number | The HTTP status code returned by the API. | | apiError | string | The error field from the API error response. | | message | string | A human-readable error message. | | retryAfter | number | Seconds to wait before retrying (set on HTTP 429). | | response | ErrorResponse | The full raw error response, if available. |

import { Html2PdfClient, Html2PdfError } from '@akcraft/html2pdf-sdk';

const client = new Html2PdfClient('h2p_live_...');

try {
  await client.sendHtmlRequest({
    userId: 'YOUR_ACCOUNT_ID',
    content: '<h1>Hello</h1>',
  });
} catch (error) {
  if (error instanceof Html2PdfError) {
    console.error(`Request failed with ${error.statusCode}: ${error.message}`);
    if (error.statusCode === 429 && error.retryAfter) {
      console.log(`Rate limited — retry after ${error.retryAfter}s`);
    }
  } else {
    throw error;
  }
}

PDF options

Both options are optional and are passed under the options field of sendHtmlRequest.

format

The paper size, from the PaperFormat enum. Defaults to A4.

| Value | Size | | -------- | ----------- | | A0 | A0 | | A1 | A1 | | A2 | A2 | | A3 | A3 | | A4 | A4 (default)| | A5 | A5 | | A6 | A6 | | LETTER | Letter | | LEGAL | Legal | | TABLOID| Tabloid | | LEDGER | Ledger |

orientation

The page orientation, from the PdfOrientation enum. Defaults to portrait.

| Value | Meaning | | ---------- | --------- | | PORTRAIT | portrait | | LANDSCAPE| landscape |

options: {
  format: PaperFormat.LETTER,
  orientation: PdfOrientation.LANDSCAPE,
}

Extended print options

| Field | Type | Description | | ----- | ---- | ----------- | | margin | PdfMargin | { top?, bottom?, left?, right? } with CSS units (e.g. '20px', '1in', '10mm') or numbers. | | preferCSSPageSize | boolean | When true, gives @page { size: ... } precedence over format. | | printBackground | boolean | Whether to print CSS background graphics. Defaults to true. | | pageRanges | string | Paper ranges to print, e.g. '1-5, 8, 11-13'. | | scale | number | Scale of the webpage rendering. Between 0.1 and 2.0. Defaults to 1. | | headerTemplate | string | HTML template for the print header. Dynamic placeholders: <span class="pageNumber"></span>, <span class="totalPages"></span>, <span class="date"></span>, <span class="title"></span>, <span class="url"></span>. | | footerTemplate | string | HTML template for the print footer (supports same dynamic placeholders). |

Note: When using headerTemplate or footerTemplate, configure sufficient margin.top or margin.bottom (e.g. '40px') so the templates are visible and do not overlap page content.

options: {
  format: PaperFormat.A4,
  margin: { top: '40px', bottom: '40px', left: '20px', right: '20px' },
  printBackground: true,
  footerTemplate: '<div style="font-size: 10px; text-align: center; width: 100%;">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>',
}

API reference

new Html2PdfClient(apiKey?)

Creates a client configured to communicate with the html2pdf API service (https://api.html2pdf.akcraft.app).

| Argument | Type | Required | Description | | -------- | -------- | -------- | -------------------------------------------------------- | | apiKey | string | No | API key sent as the x-api-key header on every request. |

const client = new Html2PdfClient('h2p_live_...');

sendHtmlRequest(request): Promise<SendHTMLRequestResponse | ArrayBuffer>

Sends HTML to be converted to PDF. Returns a SendHTMLRequestResponse object by default, or an ArrayBuffer when sendBuffer: true.

| Field | Type | Required | Description | | ------------ | ------------ | -------- | --------------------------------------------------------------------- | | apikey | string | No | API key (backward-compatible; ignored if the constructor key is set). | | userId | string | Yes | Account ID from dashboard Settings. | | content | string | Yes | The HTML content to convert. | | filename | string | No | Custom output filename (e.g. 'monthly-invoice.pdf'). | | sendBuffer | boolean | No | When true, returns binary ArrayBuffer directly instead of JSON. | | options | PdfOptions | No | PDF formatting options (format, orientation, margins, etc.). |

sendHtmlBuffer(request): Promise<ArrayBuffer>

Convenience helper method that converts HTML and returns the raw binary PDF ArrayBuffer directly (shorthand for sendHtmlRequest with sendBuffer: true).

| Field | Type | Required | Description | | ---------- | ------------ | -------- | --------------------------------------------------------------------- | | apikey | string | No | API key (backward-compatible; ignored if the constructor key is set). | | userId | string | Yes | Account ID from dashboard Settings. | | content | string | Yes | The HTML content to convert. | | filename | string | No | Custom output filename (e.g. 'invoice.pdf'). | | options | PdfOptions | No | PDF formatting options (format, orientation, margins, etc.). |

const buffer = await client.sendHtmlBuffer({
  userId: 'YOUR_ACCOUNT_ID',
  content: '<h1>Invoice</h1>',
  filename: 'invoice.pdf',
});

getPdfUrl(fileName, jobId?): Promise<GetPdfUrlResponse>

Gets the presigned download URL of a generated PDF.

| Parameter | Type | Required | Description | | ---------- | -------- | -------- | ------------------------------------------------------------------------------------------ | | fileName | string | Yes | File name of the generated PDF (e.g. '{jobId}.pdf' or custom 'invoice.pdf'). | | jobId | string | No | Job ID UUID. Required when fileName is a custom display filename without an embedded UUID.|

getHealthStatus(): Promise<{ message: string }>

Checks the health of the API service.


License

MIT