zztaeha

Types

11 types in daeepdf 1.2.0, as its declarations give them, filed by area.

Import a type with import type, and PdfError itself to check an error with instanceof.

What comes back

An export resolves to a PdfFile: the PDF, its page count, and the warnings for what it left out. It is frozen, and holds nothing that changes.

PdfFile
interface PdfFile {
  readonly bytes: Uint8Array;
  readonly pages: number;
  readonly warnings: readonly PdfWarning[];
  blob(): Blob;
  download(filename: string): void;
}

The PDF an export makes, with its page count and what it left out.

pdf.render and pdf.download resolve to one. It is frozen, its PdfFile.warnings too, and holds nothing that changes, so call PdfFile.blob and PdfFile.download as often as you like.

import pdf from 'daeepdf'
import type { PdfFile } from 'daeepdf'

const file: PdfFile = await pdf.render(html)
file.pages // 2
file.blob().type // 'application/pdf'

await fetch('/api/reports', { method: 'POST', body: file.blob() })
file.download('report') // saves report.pdf, whenever you like
readonly bytes: Uint8Array
The PDF itself, a PDF 2.0 file, to send as it is or keep. It is the array daeepdf wrote, which PdfFile.blob and PdfFile.download read too, so change a copy of it, not it.
readonly pages: number
How many pages the PDF has, from 1 to 10,000. Every page the layout reaches counts, a last page holding only blank space or bottom padding too, as in Chrome's print.
readonly warnings: readonly PdfWarning[]
What the export left out or drew another way, one PdfWarning for each distinct message, in the order they came up. Empty when everything printed. Each is logged to the console too, with [daeepdf] in front.
blob(): Blob
Returns the bytes as a new Blob of type application/pdf on every call, for an upload, URL.createObjectURL or an <iframe>.
download(filename: string): void
Saves the file as pdf.download does: the name trimmed, and .pdf added when it lacks it. It returns nothing, and for a name that is empty, only spaces or not a string it throws a PdfError with 'invalid-option' right away, not a rejected promise.

Options

PdfOptions is the one object pdf.render, pdf.download and pdf.preview take, and the other types here are the shapes of its values. Every length is a Length: a number of pt, or a string with its unit. The options list has each option in full.

PdfOptions
interface PdfOptions {
  size?: PageSize;
  landscape?: boolean;
  margin?: Length | {
    top?: Length;
    right?: Length;
    bottom?: Length;
    left?: Length;
  };
  shrinkToFit?: boolean;
  header?: Band;
  footer?: Band;
  title?: string;
  author?: string;
  subject?: string;
  creator?: string;
  keywords?: string[];
  language?: string;
  bookmarks?: boolean | Bookmark[];
  accessible?: boolean;
  pdfA?: boolean;
  pdfUA?: boolean;
  security?: {
    password?: string;
    ownerPassword?: string;
    allow?: Permission[];
  };
  fillable?: boolean;
  fallbackFont?: string;
  useAppStyles?: boolean;
  loadTimeout?: number;
  strict?: boolean;
  signal?: AbortSignal;
}

The one options object pdf.render, pdf.download and pdf.preview take.

Every option is optional, and one left out or undefined takes its default. They are checked as you call: an unknown or misspelled name, a value of the wrong type, null, or a value outside a list fails with 'invalid-option' before any work starts, and the message names the option, and for a misspelling the closest one. Lengths are pt as numbers, or strings like '20mm'; see Length.

A template's own @page rule sets the size, orientation and margins wherever size, landscape and margin are left out. pdf.preview uses the options that shape the page or its loading, and ignores the rest. The options list has each one in full: its default, how it meets the template's CSS, and what it fails with.

import pdf from 'daeepdf'
import type { PdfOptions } from 'daeepdf'

const options: PdfOptions = {
  size: 'Letter',
  margin: { top: '1in', bottom: '1in', left: '0.75in', right: '0.75in' },
  footer: ({ page, pages }) => `<p style="font: 9pt Inter; text-align: right">Page ${page} of ${pages}</p>`,
  title: 'Q4 Report',
  bookmarks: true,
}
await pdf.preview(html, container, options) // the pages, on screen
const file = await pdf.render(html, options) // the same pages, in a file
size?: PageSize
The paper: one of six names, or { width, height }. Default 'A4', or the template's @page size.
landscape?: boolean
Turns the paper so its long side runs across. Default: the template's @page orientation, else portrait.
margin?: Length | { top?: Length; right?: Length; bottom?: Length; left?: Length }
Space kept clear around the content on every page, one Length or one per side. Default 0, or the template's @page margins.
shrinkToFit?: boolean
Scales content wider than the page down onto it, as Chrome's print does. Default true.
header?: Band
A Band at the top of every page, inside the margin. Default none.
footer?: Band
A Band at the bottom of every page, inside the margin. Default none.
title?: string
The document's title, for a viewer to show. Required with pdfUA.
author?: string
Who wrote the document.
subject?: string
What the document is about.
creator?: string
The app that made the document.
keywords?: string[]
Words to find the document by, written as one comma-separated string.
language?: string
The text's language, like 'en-US'. Default: the template's <html lang>.
bookmarks?: boolean | Bookmark[]
true for an outline built from the headings, or a list of Bookmarks. Default none.
accessible?: boolean
Tags the structure so screen readers can follow it. Default true.
pdfA?: boolean
Writes PDF/A-4, for archiving. Default false.
pdfUA?: boolean
Writes PDF/UA-2, for accessibility, and needs a title. Default false.
security?: { password?: string; ownerPassword?: string; allow?: Permission[] }
Encrypts the file with AES-256: security.password to open it, security.ownerPassword, and the Permissions in security.allow. Default none.
fillable?: boolean
Keeps form fields fillable; false prints them as they show. Default true.
fallbackFont?: string
A TTF or OTF file's URL, for text in a font the template doesn't declare. Default none.
useAppStyles?: boolean
Lets your app page's own stylesheets reach the template. Default true.
loadTimeout?: number
How long to wait for fonts, images and stylesheets, in ms. Default 10000.
strict?: boolean
Fails with 'strict' instead of finishing with warnings. Default false.
signal?: AbortSignal
An AbortSignal that stops the export with 'aborted'. Default none.
PageSize
type PageSize = 'A3' | 'A4' | 'A5' | 'Letter' | 'Legal' | 'Tabloid' | {
  width: Length;
  height: Length;
}

The paper's size: one of six names, or a width and a height.

The names, each portrait, in pt: 'A3' 841.89 × 1190.55, 'A4' 595.28 × 841.89, 'A5' 419.53 × 595.28, 'Letter' 612 × 792, 'Legal' 612 × 1008 and 'Tabloid' 792 × 1224. They are case-sensitive, so 'a4' fails with 'invalid-option', and landscape turns any of them.

{ width, height } takes each side as a Length, and each must come to 3 to 14,400 pt (200 in), PDF's own range, or the export fails with 'invalid-page-size'. A missing side, or one that isn't a Length, fails with 'invalid-option'.

A template's @page { size } takes more than this: every CSS size keyword, b4, b5, jis-b4, jis-b5 and ledger among them, and lengths in any absolute CSS unit. See size.

import pdf from 'daeepdf'
import type { PageSize } from 'daeepdf'

const label: PageSize = { width: '4in', height: '6in' }
const file = await pdf.render(html, { size: label }) // 288 × 432 pt

const tiny: PageSize = { width: '1mm', height: '1mm' } // 2.83 pt a side, under PDF's 3
const code = await pdf.render(html, { size: tiny }).catch((e: { code: string }) => e.code)
code // 'invalid-page-size'
Length
type Length = number | string

A length: a number of pt, or a string with its unit.

A number is in pt, 1/72 in, and must be finite and 0 or more. A string is a number and one of mm, cm, in, pt or px, like '20mm' or '.75in': the unit in any case, spaces around it allowed, no sign and no exponent. A px is a CSS px, 0.75 pt.

Anything else fails with 'invalid-option', naming the option: a bare '20', '2em', '10%' or a negative number. size, margin and a Bookmark's y take one. The relative units are for the template's own @page, where em is 12 pt and a percentage is of the paper.

import pdf from 'daeepdf'
import type { Length } from 'daeepdf'

const width: Length = '8.5in'
const height: Length = 792
const file = await pdf.render(html, { size: { width, height } }) // 612 × 792 pt, Letter

const relative: Length = '2em'
const code = await pdf.render(html, { margin: relative }).catch((e: { code: string }) => e.code)
code // 'invalid-option': em is for CSS
Band
type Band = string | ((at: {
  page: number;
  pages: number;
}) => string)

A header or footer: HTML, or a function of the page that returns it.

A string is the same on every page. A function is called with { page, pages }, the page's number from 1 and the page count, and returns that page's HTML, or '' for a page without one; null and undefined count as ''. It is first called with { page: 1, pages: 1 }, to measure the band before the count is known, then once for each page, and once more for each page if one page's band came out taller than the first, so keep it free of side effects.

Each band is a small document of its own, sanitized as the template is. It can use the fonts the template declares with @font-face, but none of the template's other CSS, not even its body font, so give it its font in a style attribute or a <style> of its own. Your app's stylesheets reach it unless useAppStyles is false, and fallbackFont covers its text.

header and footer say where a band goes and how much room it takes. An error object the function throws reaches the caller of pdf.render as it is.

import pdf from 'daeepdf'
import type { Band } from 'daeepdf'

const footer: Band = ({ page, pages }) =>
  page === 1 ? '' : `<p style="font: 9pt Inter; text-align: center">Page ${page} of ${pages}</p>`
const file = await pdf.render(html, { footer })
// no footer on the cover, then Page 2 of 3 and Page 3 of 3
Bookmark
interface Bookmark {
  title: string;
  target: string | {
    page: number;
    y?: Length;
  };
  children?: Bookmark[];
}

One entry of an outline you list yourself, with the entries nested under it.

Pass a list of them as bookmarks. The outline holds them in the order given, each Bookmark.children a level under its parent, and every entry starts closed, its children folded under it.

An entry whose id no element has, or whose page is past the last one, is left out with a 'bookmark-target-missing' warning, and its children move up a level into its place.

import pdf from 'daeepdf'
import type { Bookmark } from 'daeepdf'

const outline: Bookmark[] = [
  { title: 'Introduction', target: '#intro' },
  { title: 'Results', target: '#results', children: [{ title: 'Figures', target: { page: 2, y: '30mm' } }] },
]
const file = await pdf.render(html, { bookmarks: outline })
// Introduction on page 1, Results on page 2 with Figures under it
title: string
The text the outline shows. Any string, an empty one too.
target: string | { page: number; y?: Length }
Where it goes: an element's id, with or without its #, or { page, y }, a page number from 1 and a Length down from the paper's top edge, 0 when left out. An id goes to the top of its element, on the page that element starts on; the first element with the id wins, and ids in a header or footer don't count.
children?: Bookmark[]
The entries one level under this one, each a Bookmark.
Permission
type Permission = 'print' | 'copy' | 'edit' | 'annotate' | 'fill'

Something security.allow lets a viewer do with an encrypted PDF.

List the ones you allow in security.allow; the rest are withheld, and with allow left out all five are allowed. Withholding every one still lets screen readers and other assistive tools extract the text, as PDF allows.

A viewer honors them, and the file can't enforce them: a viewer that ignores them can print or copy anyway. Only security.password keeps someone without it from reading the file.

import pdf from 'daeepdf'
import type { Permission } from 'daeepdf'

const allow: Permission[] = ['print', 'fill']
const file = await pdf.render(html, { security: { allow } })
// may be printed and filled in, not copied, changed or commented on
'print'
Printing it.
'copy'
Copying its text and images.
'edit'
Changing it, and inserting, deleting and rotating its pages.
'annotate'
Adding comments and markup. It allows filling in form fields too, since PDF ties the two together.
'fill'
Filling in its form fields, without commenting.

Errors and warnings

Every failure is a PdfError with a PdfErrorCode, and each thing an export left out or drew another way is a PdfWarning with a PdfWarningCode. Branch on the code; the message is for people. The errors and warnings lists have an entry for every code.

PdfError
class PdfError extends Error {
  readonly code: PdfErrorCode;
  readonly warnings: PdfWarning[];
  readonly name = "PdfError";
  constructor(code: PdfErrorCode, message: string, warnings?: PdfWarning[], options?: {
    cause?: unknown;
  });
}

The error every failure comes as, with a code that says why.

pdf.render, pdf.download, pdf.preview and pdf.warmup reject with one, and PdfFile.download throws one. Import the class to tell it from other errors, with instanceof PdfError. Branch on PdfError.code: the message is for people, starts with [daeepdf] , and says what to change.

'internal', a fault in daeepdf itself, and 'engine-not-loaded' carry the original error as their cause, and 'aborted' the signal's reason. Two failures aren't a PdfError: an error object your own header or footer function throws reaches you as it is, and pdf.safeName throws a TypeError for anything but a string.

import pdf, { PdfError } from 'daeepdf'

try {
  await pdf.render(html, { strict: true })
} catch (e) {
  if (!(e instanceof PdfError)) throw e
  e.code // 'strict'
  e.warnings.map((w) => w.code) // ['font-not-declared']: Helvetica isn't declared
}

const mine = new PdfError('invalid-option', 'The invoice has no lines.')
mine.message // 'The invoice has no lines.'
readonly code: PdfErrorCode
Why it failed, one of the PdfErrorCode strings.
readonly warnings: PdfWarning[]
The warnings the export had gathered: every one for 'strict', those so far for 'aborted', and none for the other codes.
readonly name = "PdfError"
Always 'PdfError'.
constructor(code: PdfErrorCode, message: string, warnings?: PdfWarning[], options?: { cause?: unknown })
Makes one from a code and a message, and optionally the warnings and a cause. The message is used as given. daeepdf makes every one it throws; make your own where code of yours should fail the way daeepdf does, so one catch handles both.
PdfErrorCode
type PdfErrorCode = 'invalid-option' | 'invalid-page-size' | 'margins-too-large' | 'bands-too-tall' | 'too-many-pages' | 'missing-title' | 'pdfa-encryption' | 'invalid-password' | 'container-detached' | 'strict' | 'aborted' | 'engine-not-loaded' | 'internal'

Why an export or preview failed: the code of every PdfError.

A union of string literals, so a switch on PdfError.code can cover each case and TypeScript checks that it names only real ones. Each code has an entry in the errors list, with when it happens and what to change.

import pdf, { PdfError } from 'daeepdf'
import type { PdfErrorCode } from 'daeepdf'

function explain(code: PdfErrorCode): string {
  switch (code) {
    case 'aborted': return 'Canceled.'
    case 'strict': return 'Part of the document would not print.'
    case 'engine-not-loaded': return 'Check that daegun.wasm is served beside daeepdf.'
    default: return 'The export failed.'
  }
}
const controller = new AbortController()
controller.abort()
const outcome = await pdf.render(html, { signal: controller.signal })
  .then(() => 'Done.', (e: unknown) => (e instanceof PdfError ? explain(e.code) : 'Unknown error.'))
outcome // 'Canceled.'
'invalid-option'
An option, argument or file name of the wrong kind, misspelled or outside its list.
'invalid-page-size'
A page side outside 3 to 14,400 pt.
'margins-too-large'
Margins that leave less than 3 pt of the page for content.
'bands-too-tall'
A header and footer that leave less than 3 pt for content.
'too-many-pages'
A document that would have more than 10,000 pages.
'missing-title'
pdfUA without a title.
'pdfa-encryption'
pdfA with security, which PDF/A forbids.
'invalid-password'
A password with a character SASLprep prohibits, such as a control character.
'container-detached'
A preview container that isn't in the document.
'strict'
strict, and the export had warnings.
'aborted'
The signal aborted the export.
'engine-not-loaded'
The engine, daegun.wasm, couldn't be loaded.
'internal'
A fault in daeepdf itself, the original error as its cause.
PdfWarning
interface PdfWarning {
  code: PdfWarningCode;
  message: string;
}

Something an export left out or drew another way.

They come back in PdfFile.warnings, and in PdfError.warnings when strict turns them into a failure. A message is reported once per export, however often it happened, and logged to the console as well.

import pdf from 'daeepdf'
import type { PdfWarning } from 'daeepdf'

const file = await pdf.render(html)
const missing: PdfWarning[] = file.warnings.filter((w) => w.code === 'font-not-declared')
missing.length // 1, though two paragraphs use Georgia
missing[0]?.message // 'Font "Georgia" is not registered – text skipped. Declare it with @font-face…'
code: PdfWarningCode
What kind of thing happened, one of the PdfWarningCode strings, and the part to branch on.
message: string
What happened and what to change, for people, such as Font "Georgia" is not registered – text skipped. It lacks the [daeepdf] the console shows in front of it.
PdfWarningCode
type PdfWarningCode = 'font-not-declared' | 'font-not-loaded' | 'glyph-missing' | 'image-skipped' | 'stylesheet-removed' | 'unsupported-css' | 'limit-reached' | 'alt-missing' | 'bookmark-target-missing'

What kind of thing an export left out or drew another way: the code of every PdfWarning.

A union of string literals. Each code has an entry in the warnings list, with when it comes up and what to change.

import pdf from 'daeepdf'
import type { PdfWarningCode } from 'daeepdf'

const fixable: PdfWarningCode[] = ['font-not-declared', 'font-not-loaded', 'stylesheet-removed']
const file = await pdf.render(html)
file.warnings.filter((w) => fixable.includes(w.code)).map((w) => w.code)
// ['stylesheet-removed', 'font-not-declared']
'font-not-declared'
Text in a font no @font-face declares, left out.
'font-not-loaded'
A declared font that didn't load in time, or isn't TTF, OTF or TTC.
'glyph-missing'
Characters no font covers, left out under pdfA or pdfUA.
'image-skipped'
An image, canvas or SVG that couldn't be loaded or drawn.
'stylesheet-removed'
A <link> stylesheet or an @import, removed from the template.
'unsupported-css'
CSS drawn another way, such as a 3D transform drawn flat.
'limit-reached'
One of the export's safety limits, past which things are skipped or simplified.
'alt-missing'
Images without alternative text, under pdfUA.
'bookmark-target-missing'
A bookmark pointing at an id no element has, left out.

Type to search.