Skip to content

vellum ​

@c9up/vellum: a PDF toolkit on a Rust engine: render pages to images, read text, metadata and forms, merge, split, rotate and stamp documents, fill and flatten forms, sign and verify signatures, and author new documents with PdfDocument. Guide: PDF.

Installation ​

bash
pnpm add @c9up/vellum
ream configure @c9up/vellum

ream configure @c9up/vellum adds the provider, the VELLUM_FORMAT variable, and writes config/vellum.ts. @c9up/ream is an optional peer.

The native engine comes as one small package per platform, @c9up/vellum-<platform>, for linux x64 and arm64 (glibc), macOS x64 and arm64, and Windows x64. @c9up/vellum lists them as optional dependencies, and your package manager installs only the one that matches your machine. No Rust toolchain is needed. Do not install with optional dependencies turned off (--no-optional, --omit=optional): the engine would be left out.

There is no JavaScript fallback. Without the engine, the first call throws E_VELLUM_NAPI_REQUIRED, and its message names the package to install, for example @c9up/vellum-linux-x64-gnu. The bundled fonts stay in @c9up/vellum itself.

Entry points ​

ImportContents
@c9up/vellumVellum, PdfDocument and its companions, defineConfig, signers, inspect, createBlank, A4, the types and the error classes.
@c9up/vellum/providerVellumProvider (default export).
@c9up/vellum/services/mainThe application's Vellum (default export), usable once the provider booted.
@c9up/vellum/configureconfigure(codemods), run by ream configure @c9up/vellum.

Exports ​

@c9up/vellum ​

ExportKindDescription
VellumclassWorks on existing PDFs: render, read, edit, fill, sign, verify.
defineConfigfunctionChecks and types config/vellum.ts.
VellumConfigtypeThe vellum config; also the base of RenderOptions.
inspectfunctioninspect(pdf: Buffer): Promise<DocumentInfo>: page count, version, encryption.
createBlankfunctioncreateBlank(pages: ReadonlyArray<PageSize>): Buffer: a document of blank pages, in points.
A4const{ width: 595.28, height: 841.89 }.
pkcs8SignerfunctionA signer from a PKCS#8 key and its certificate.
timestampedfunctionAdds an RFC 3161 timestamp to any signer.
Signerinterface{ sign(digest: Buffer): Promise<Buffer> }: turns the SHA-256 of the signed byte range into CMS SignedData.
Pkcs8SignerOptions, TimestampOptionsinterfaceOptions of the two signer helpers.
ResponderPolicy, ResponderClienttypeWhich revocation responders may be asked, and the client that asks them.
RenderOptions, PageOptions, Band, ImageFormattypeRendering options.
EditOptions, StampOptions, TextStampOptions, StandardFonttypeEditing options.
SignOptions, VerifyOptions, CheckedSignaturetypeSigning and verification.
DocumentInfo, DocumentMetadata, PageDimensions, PageSize, FormField, SignatureReport, RevocationAnswertypeWhat the reading methods return.
PdfDocumentclassAuthors a new PDF, as a readable stream.
PdfPageclassOne page of a PdfDocument.
PdfTableclassA table being drawn, from doc.table().
PdfGradient, PdfLinearGradient, PdfRadialGradientclassGradients, from doc.linearGradient() and doc.radialGradient().
toBytesfunctiontoBytes(document: PdfDocument): Promise<Uint8Array>: every byte of a document once it has ended.
registerFilefunctionregisterFile(path: string | URL, data: Uint8Array | undefined, stats?: FileStats): void: serves path from memory to every document that reads it; undefined forgets it.
PAGE_SIZESconstNamed page sizes (A0…A10, B0…, letter…), [width, height] in points.
PageSizeName, Size, SideDefinitiontypePage sizes and lengths.
PdfDocumentOptions, PdfPageOptions, PdfDocumentInfo, PageLayout, PermissionstypeOptions of PdfDocument and addPage.
TextOptions, TextAlign, TextBaseline, WidthOptions, ListOptions, ListItems, FontSourcetypeText options.
Colour, ColourValue, FillRuletypeColours and fill rules.
ImageOptions, ImageSource, PdfImage, SvgOptionstypeImages and SVG.
FileSource, FileStats, FileOptions, PdfFileSpectypeFiles read and embedded.
AnnotationOptions, AnnotationSubtype, NoteOptionstypeAnnotations.
FieldOptions, FieldFormat, PdfFormFieldtypeForm fields.
TableOptions, TableCell, TableCellStyle, CellStyle, ColumnStyle, RowStyle, TableAlign, TableFonttypeTables.
isNativeAvailablefunctionWhether the Rust engine is loaded.
errorsnamespaceThe package's errors, one class per code, see Errors. Each is a flare Exception with a string code.

Vellum ​

Every method takes the PDF as a Buffer and runs on the thread pool. Pages count from 1. An edit of a signed document is refused with E_VELLUM_SIGNED_DOCUMENT unless discardSignatures: true.

MemberSignatureDescription
constructornew Vellum(config?: VellumConfig)Checks the ceilings.
configget config(): Readonly<VellumConfig>
renderrender(pdf: Buffer, options?: RenderOptions): Promise<Buffer>Rasterises one page (page, default 1); band renders only a rectangle, and a band that does not fit the page is an error.
renderAllrenderAll(pdf: Buffer, options?: RenderOptions): Promise<Buffer[]>Every page, within maxTotalPixels.
dimensionsdimensions(pdf: Buffer): Promise<PageDimensions[]>Every page's natural size, in points.
inspectinspect(pdf: Buffer): Promise<DocumentInfo>Page count, version, encryption.
metadatametadata(pdf: Buffer): Promise<DocumentMetadata>Title, author, subject, keywords, creator, producer, dates.
pageCountpageCount(pdf: Buffer): Promise<number>
extractTextextractText(pdf: Buffer, options?: PageOptions): Promise<string>The text of one page.
extractTextAllextractTextAll(pdf: Buffer): Promise<string[]>The text of every page, in order.
mergemerge(pdfs: ReadonlyArray<Buffer>, options?: EditOptions): Promise<Buffer>Joins documents end to end.
selectPagesselectPages(pdf: Buffer, pages: ReadonlyArray<number>, options?: EditOptions): Promise<Buffer>A document of the given pages, in the given order.
splitsplit(pdf: Buffer, options?: EditOptions): Promise<Buffer[]>One document per page.
rotaterotate(pdf: Buffer, degrees: number, options?: { pages?: ReadonlyArray<number> } & EditOptions): Promise<Buffer>Rotates pages clockwise by a multiple of 90; every page without pages.
stampstamp(pdf: Buffer, image: Buffer, options?: StampOptions): Promise<Buffer>Draws a PNG or JPEG at x, y (from the top-left, in points), width, height, opacity; every page without page.
stampTextstampText(pdf: Buffer, text: string, options?: TextStampOptions): Promise<Buffer>Writes a line of text: x, y (to the baseline), size (default 12), font (a configured font or a StandardFont, default 'Helvetica'), color (default black), opacity.
formFieldsformFields(pdf: Buffer): Promise<FormField[]>The form's fields.
fillFormfillForm(pdf: Buffer, values: Record<string, string>, options?: EditOptions): Promise<Buffer>Fills fields by name.
flattenFormflattenForm(pdf: Buffer, options?: EditOptions): Promise<Buffer>Turns the fields into page content.
signsign(pdf: Buffer, options: SignOptions): Promise<Buffer>Signs with a configured signer.
verifySignaturesverifySignatures(pdf: Buffer, options?: VerifyOptions): Promise<CheckedSignature[]>Checks every signature against the trusted anchors, and optionally asks each issuer about revocation.
SignOptions fieldTypeDefaultDescription
signerstringrequiredA signer named in the config.
reason, location, contact, namestringWhat the signature says about itself.
signedAtDatenow
capacitynumber16384Bytes reserved for the signature value.
VerifyOptions fieldTypeDefaultDescription
anchorsReadonlyArray<Buffer>config trustedAnchorsRoot certificates to trust, DER or PEM.
allowedRespondersResponderPolicyconfigWhich responders may be contacted.
checkRevocationbooleanAsk each signing certificate's issuer; the answer is good, revoked or unknown. A signature that is not trusted answers unknown without anything being asked.
revocationTimeoutMsnumber10000

SignatureReport carries field, coversWholeDocument, digestMatches, signatureVerifies, signer, signedAt, timestamped, trusted, chain, moment, momentAt, signerCertificate, issuerCertificate and problems; CheckedSignature adds revocation?: RevocationAnswer ({ status: string; detail?: string }). FormField is { name, kind, value?, options, readOnly, required, multiline, password, maxLength? }.

StandardFont is 'Helvetica' | 'Helvetica-Bold' | 'Helvetica-Oblique' | 'Times-Roman' | 'Times-Bold' | 'Times-Italic' | 'Courier' | 'Courier-Bold'.

Signers ​

FunctionSignatureDescription
pkcs8Signerpkcs8Signer(options: Pkcs8SignerOptions): Signerkey (PKCS#8 DER), certificate (DER), chain? (DER, nearest issuer first).
timestampedtimestamped(inner: Signer, options: TimestampOptions): Signerurl of the RFC 3161 authority, headers?, timeoutMs? (default 10000).

ResponderPolicy is ReadonlyArray<string> | ((url: URL) => boolean | Promise<boolean>): hosts or origins, or a predicate. ResponderClient is { post(url: URL, options: { headers; body: Uint8Array; timeout: number; maxResponseBytes: number }): Promise<…> }.

PdfDocument ​

Extends Node's Readable: pipe it to a file or a response, or collect it with toBytes. Coordinates count from the top-left corner, in points; lengths (Size) also take units ('2cm', '1.5em', '50%'). Most methods return this.

GroupSignatures
Documentnew PdfDocument(options?: PdfDocumentOptions)
readonly options: PdfDocumentOptions, readonly info: DocumentInfo, readonly outline: PdfOutline (addItem(title, options?))
end(): this
PagesaddPage(options?: PageOptions): this, continueOnNewPage(options?: PageOptions): this
get page(): PdfPage, switchToPage(index: number): PdfPage, bufferedPageRange(): { start: number; count: number }, flushPages(): void
x, y (get and set), sizeToPoint(size, fallback?, page?, percentageOf?): number
Fonts and textregisterFont(name: string, src: FontSource, family?: string): this
font(src: FontSource, family?: string | number, size?: Size): this, fontSize(size: Size): this, lineGap(gap: number): this
text(text: unknown, options?: TextOptions): this / text(text: unknown, x?: number, y?: number, options?: TextOptions): this
list(items: ListItems, x?: number | ListOptions, y?: number, options?: ListOptions): this
moveDown(lines?: number): this, moveUp(lines?: number): this
widthOfString(text: string, options?: WidthOptions): number, heightOfString(text: unknown, options?: TextOptions): number, boundsOfString(…): { x; y; width; height }, currentLineHeight(includeGap?: boolean): number
Transformsave(), restore(), transform(m11, m12, m21, m22, dx, dy), translate(x, y), rotate(angle, options?: { origin? }), scale(xFactor, yFactor?, options?)
PathsmoveTo, lineTo, bezierCurveTo, quadraticCurveTo, closePath, rect(x, y, width, height), roundedRect(x, y, width, height, radius?), ellipse(x, y, radiusX, radiusY?), circle(x, y, radius), arc(x, y, radius, startAngle, endAngle, anticlockwise?), polygon(...points), path(data: string) (SVG path data)
Paintingfill(colour?: Colour | FillRule, rule?: FillRule), stroke(colour?: Colour), fillAndStroke(fillColour?, strokeColour?, rule?), clip(rule?: FillRule)
fillColor(colour: Colour, opacity?: number), strokeColor(colour: Colour, opacity?: number), opacity(opacity), fillOpacity(opacity), strokeOpacity(opacity)
lineWidth(width), lineCap(cap), lineJoin(join), miterLimit(limit), dash(length, options?: { space?; phase? }), undash()
linearGradient(x1, y1, x2, y2): PdfLinearGradient, radialGradient(x1, y1, r1, x2, y2, r2): PdfRadialGradient, addSpotColor(name, c, m, y, k)
Images and SVGimage(src: ImageSource, x?: number | ImageOptions, y?: number, options?: ImageOptions): this
openImage(src: ImageSource): PdfImage
svg(src: FileSource, x?: number | SvgOptions, y?: number, options?: SvgOptions): this
Tablestable(options: TableOptions & { data }): this (draws it at once)
table(options?: TableOptions): PdfTable<this> (then row(cells, lastRow?) and end())
Links and navigationlink(x, y, width, height, target: string | number), goTo(x, y, width, height, name), addNamedDestination(name, ...view)
Taggingstruct(type, options?, children?): PdfStructureElement, addStructure(element), markContent(tag, options?), markStructureContent(tag, options?), endMarkedContent()
Filesfile(src: FileSource, options?: FileOptions): PdfFileSpec (embeds a file, at most maxFileBytes)
FormsinitForm(): this, then formField(name, options?), formText, formPushButton, formCombo, formList, formRadioButton, formCheckbox (name, x, y, width, height, options?: FieldOptions): PdfFormField, formAnnotation(name, type, x, y, width, height, options?)
Annotationsnote(x, y, width, height, contents, options?), highlight, underline, strike, rectAnnotation, ellipseAnnotation (x, y, width, height, options?), lineAnnotation(x1, y1, x2, y2, options?), textAnnotation(x, y, width, height, text, options?), fileAnnotation(x, y, width, height, file, options?), annotate(x, y, width, height, options)
RawaddContent(content: string): this
PdfDocumentOptions fieldTypeDefaultDescription
sizestring | readonly [number, number]'letter'A PAGE_SIZES name (any case) or [width, height] in points.
layout'portrait' | 'landscape''portrait'
margin, marginsSideDefinition<Size>72
fontFontSourceThe first page's font.
pdfVersion'1.4' | '1.5' | '1.6' | '1.7' | '2.0''1.7'
compressboolean
autoFirstPagebooleanAdd the first page at construction.
bufferPagesbooleanKeep pages for switchToPage.
infoPdfDocumentInfoTitle, Author, Subject, Keywords, Creator, Producer, CreationDate, ModDate.
lang, displayTitle, pageLayoutViewer hints.
ignoreOrientationbooleanDraw JPEGs as stored, not turned by their EXIF orientation.
taggedbooleanWrite a structure tree.
maxFileBytesnumber64 MiBThe largest file file() embeds.
userPassword, ownerPasswordstringEncrypt with AES-256.
permissionsPermissionsWhat the user password allows: printing, modifying, copying, annotating, fillingForms, contentAccessibility, documentAssembly.
subset'PDF/A-1' … 'PDF/A-3u' | 'PDF/UA'The standard checked as the document is written; what it forbids is refused at end().

PdfPage exposes width, height, size, layout, margins, userUnit, options, contentWidth, contentHeight and maxY(). A gradient takes stop(offset: number, colour: ColourValue, opacity?: number): this and setTransform(m11, m12, m21, m22, dx, dy): this.

@c9up/vellum/provider ​

ExportKindDescription
VellumProviderprovider (default)register() binds Vellum from the vellum config; boot() publishes the service; shutdown() clears it.

@c9up/vellum/services/main ​

ExportKindDescription
defaultconstThe application's Vellum. Any property access before the provider booted throws.
ts
import vellum from '@c9up/vellum/services/main'

const preview = await vellum.render(pdf, { page: 1, width: 1200 })

@c9up/vellum/configure ​

ExportKindDescription
configurefunctionconfigure(codemods): Promise<void>: what ream configure @c9up/vellum runs.

Configuration ​

config/vellum.ts, written by ream configure @c9up/vellum. Every rendering option can be overridden per call.

OptionTypeDefaultDescription
format'png' | 'jpeg''png'Image encoding. The generated config reads VELLUM_FORMAT; any other value is refused.
scalenumberMultiplier over the page's natural size, 1 being 72 DPI.
widthnumberTarget width in pixels; wins over scale.
qualitynumberJPEG quality, 1–100.
backgroundstring#rgb, #rrggbb, #rrggbbaa or 'transparent'.
maxPixelsnumber50 millionPixels one page may rasterise to.
maxTotalPixelsnumber500 millionPixels renderAll may rasterise across every page.
maxDecodedBytesnumber256 MiBDecoded stream bytes reading one page may need, plus, when rendering, the buffers drawing it keeps: a byte per pixel per soft mask, four per pixel per image draw.
maxOperationsnumber10 millionContent operators and glyphs one page may take.
maxTotalDecodedBytesnumber1 GiBDecoded bytes across every page of renderAll and extractTextAll.
maxTotalOperationsnumber10 millionOperators and glyphs across every page of renderAll and extractTextAll.
fontsRecord<string, string>TrueType or OpenType files by name, looked up before the standard fonts.
signersRecord<string, Signer>Who may sign, by name.
trustedAnchorsReadonlyArray<Buffer>[]Certificates to trust when checking a signature; with none, every signature is untrusted.
allowedRespondersResponderPolicypublic http(s) addressesWhich revocation responders may be contacted.
httpClientResponderClientHttpClient from @c9up/ream/http-clientThe client responders are asked through; refuses private addresses.

Every ceiling is a whole number from 1 to 4294967295.

Container bindings ​

TokenResolves to
VellumThe Vellum singleton.
'vellum'The same instance; declared on ContainerBindings.

Errors ​

Each code is a class of the errors namespace (import { errors } from '@c9up/vellum'): a flare Exception with code and status. E_VELLUM_INVALID_PDF has status 422 (the input is not a PDF); the others 500.

CodeRaised when
E_VELLUM_INVALID_PDFThe bytes are not a PDF vellum can read.
E_VELLUM_SIGNED_DOCUMENTAn edit would invalidate the document's signatures.
E_VELLUM_INVALID_PAGEA page number is not a whole number from 1.
E_VELLUM_INVALID_ROTATIONA rotation is not a multiple of 90.
E_VELLUM_EMPTY_MERGEmerge() was given no document.
E_VELLUM_EMPTY_SELECTIONselectPages() was given no page.
E_VELLUM_MERGE_FAILEDMerging failed.
E_VELLUM_SELECT_FAILEDSelecting pages failed.
E_VELLUM_SPLIT_FAILEDSplitting failed.
E_VELLUM_ROTATE_FAILEDRotating failed.
E_VELLUM_STAMP_FAILEDStamping an image failed.
E_VELLUM_STAMP_TEXT_FAILEDStamping text failed.
E_VELLUM_FILL_FAILEDFilling the form failed.
E_VELLUM_FLATTEN_FAILEDFlattening the form failed.
E_VELLUM_RENDER_FAILEDRendering a page failed.
E_VELLUM_EXTRACT_FAILEDExtracting text failed.
E_VELLUM_WRITE_FAILEDWriting the document failed.
E_VELLUM_SIGN_FAILEDSigning failed.
E_VELLUM_VERIFY_FAILEDVerifying the signatures failed.
E_VELLUM_UNKNOWN_SIGNERNo signer of this name is configured.
E_VELLUM_SIGNER_INVALIDA signer's key or certificate is empty.
E_VELLUM_TIMESTAMP_FAILEDBuilding or reading a timestamp failed.
E_VELLUM_TIMESTAMP_UNREACHABLEThe timestamp authority could not be reached.
E_VELLUM_TIMESTAMP_REFUSEDThe timestamp authority answered with an error status.
E_VELLUM_FONT_UNREADABLEA configured font file cannot be read.
E_VELLUM_FILE_NOT_FOUNDA file given by path cannot be read.
E_VELLUM_INVALID_OPTIONSA document, page, table, drawing option or ceiling is invalid, or config/vellum.ts asks for a format other than "png" or "jpeg".
E_VELLUM_INVALID_COLORA colour cannot be read.
E_VELLUM_INVALID_IMAGEAn image cannot be used.
E_VELLUM_INVALID_SVGAn SVG cannot be used.
E_VELLUM_UNSUPPORTED_CONTENTA path holds an operator vellum does not draw.
E_VELLUM_INVALID_STRUCTUREA structure element was changed after it ended.
E_VELLUM_NO_PAGEThere is no current page; call addPage() first.
E_VELLUM_NO_FORMForm fields were added before initForm().
E_VELLUM_DOCUMENT_ENDEDThe document has ended.
E_VELLUM_NAPI_REQUIREDThe Rust PDF engine is not loaded.
E_VELLUM_NOT_BOOTEDThe services/main service was used before VellumProvider booted.
E_VELLUM_TABLE_ENDEDA row was added to a table after lastRow ended it.
E_VELLUM_INVALID_LINKA link or a named destination cannot be used.
E_VELLUM_INVALID_OUTLINEAn outline entry cannot be used.
E_VELLUM_INVALID_FONTA font cannot be used.
E_VELLUM_NO_FONTText was written before a font was selected.
E_VELLUM_PAGE_OUT_OF_RANGEA page index names no page of the document.
E_VELLUM_UNBALANCED_RESTORErestore() was called without a matching save().
E_VELLUM_NOTHING_TO_RESUMENo text is waiting for a page.
E_VELLUM_VALIDATIONThe document does not meet its subset (PDF/A, PDF/UA), or a form field or an annotation breaks a PDF rule.
E_VELLUM_DOCUMENT_BROKENAn earlier call failed inside the engine; start a new document.
E_VELLUM_INTERNALThe engine panicked.

Migration ​

  • VellumError is gone: test error.code, or error instanceof errors.E_VELLUM_* with import { errors } from '@c9up/vellum'.
  • VellumNativeRequiredError becomes errors.E_VELLUM_NAPI_REQUIRED.
  • The name of an error is no longer "VellumError".
  • E_VELLUM_INVALID_PDF now has status 422.
  • verifySignatures() no longer trusts a path through a certificate that is not an authority (basicConstraints without cA), even one bearing the signer's own name, nor through an authority whose key usage leaves out keyCertSign. Such a signature now reports trusted: false; have it signed with a certificate the authority issued directly.
  • With checkRevocation: true, a signature whose trusted is false now answers revocation: { status: 'unknown' } without asking any responder, since its issuer is not known to be one.
  • render() and renderAll() now charge maxDecodedBytes with the buffers drawing a page keeps: a byte per pixel per soft mask, four bytes per pixel per image draw, pattern tiles and cached glyphs. A large page with many soft masks or image draws can now be refused with E_VELLUM_RENDER_FAILED; raise maxDecodedBytes for a document you trust.
  • An edit or a signature whose written document would weigh more than 1 GiB is now refused with the operation's error (E_VELLUM_ROTATE_FAILED, E_VELLUM_SIGN_FAILED…).
  • PdfDocument.svg() now refuses, with E_VELLUM_INVALID_SVG, an SVG that draws more than 1 000 000 elements and path segments once its <use> elements, clip paths, masks and patterns are expanded, and a gzip SVG that inflates past 16 MiB. Simplify the drawing, or draw it as an image.

See also ​