pkg

ctxcode/valk-pdf

Pure-Valk PDF generator with text layout, tables, vector drawing and image embedding

github.com/ctxcode/valk-pdf ↗
0.2.0 latest Valk ≥ 0.9.1

Install

vman install github.com/ctxcode/valk-pdf

Adds the package to your valk.json. To allow only some versions, add them: vman install github.com/ctxcode/valk-pdf 0.2.x

Documentation

Namespaces: main


main

Enums for 'main'

// The 14 standard PDF Type1 fonts built into every PDF viewer.
+ enum Font : uint { helvetica (0), helvetica_bold (1), helvetica_oblique (2), helvetica_bold_oblique (3), times_roman (4), times_bold (5), times_italic (6), times_bold_italic (7), courier (8), courier_bold (9), courier_oblique (10), courier_bold_oblique (11), symbol (12), zapf_dingbats (13) }
// Horizontal alignment for text and table cells.
+ enum TextAlign { left, center, right }

Font

The 14 standard PDF Type1 fonts built into every PDF viewer.

TextAlign

Horizontal alignment for text and table cells.

Functions for 'main'

// Encodes a UTF-8 string into WinAnsiEncoding (Windows-1252) bytes for PDF Type1 fonts.
+ fn encode_win_ansi(text: String) String
// Returns the PostScript `/BaseFont` name of `font`.
+ fn font_pdf_name(font: Font) String
// Measures the rendered width of `text` in points when drawn with `font` at `size` points.
+ fn measure_text(text: String, font: Font, size: float) float
// Splits `text` into lines that fit within `max_width` points when rendered with `font` at `size`.
+ fn wrap_text(text: String, max_width: float, font: Font, size: float) Array[String]

encode_win_ansi

Encodes a UTF-8 string into WinAnsiEncoding (Windows-1252) bytes for PDF Type1 fonts.

Supports ASCII, Latin-1 Supplement (U+00A0..U+00FF), and common typographic symbols
(€, —, –, “, ”, ‘, ’, •, …, ™, Š, Œ, Ž, Ÿ, etc.). Unmapped
codepoints are replaced with ?.

font_pdf_name

Returns the PostScript /BaseFont name of font.

measure_text

Measures the rendered width of text in points when drawn with font at size points.

wrap_text

Splits text into lines that fit within max_width points when rendered with font at size.

Explicit \n (and \r\n) breaks are preserved. Words wider than max_width are split across
lines by UTF-8 character so text never overflows its container.

Classes for 'main'

// An RGB color with channels in `0.0..1.0`.
+ struct Color {
    // Blue channel (`0.0..1.0`).
    + b: float
    // Green channel (`0.0..1.0`).
    + g: float
    // Red channel (`0.0..1.0`).
    + r: float

    // Solid black (`#000000`).
    + static fn black() Color
    // Blue (`#2563EB`).
    + static fn blue() Color
    // Dark gray (`#333333`).
    + static fn dark_gray() Color
    // Creates a grayscale color from `0.0` (black) to `1.0` (white).
    + static fn gray(v: float) Color
    // Green (`#16A34A`).
    + static fn green() Color
    // Creates a color from a 24-bit `0xRRGGBB` value.
    + static fn hex(value: u32) Color
    // Light gray (`#E5E7EB`).
    + static fn light_gray() Color
    // Red (`#DC2626`).
    + static fn red() Color
    // Creates a color from 8-bit RGB channels (`0..255`).
    + static fn rgb(r: u8, g: u8, b: u8) Color
    // Creates a color from normalized floating-point RGB channels (`0.0..1.0`).
    + static fn rgb_f(r: float, g: float, b: float) Color
    // Solid white (`#FFFFFF`).
    + static fn white() Color
}

Color

An RGB color with channels in 0.0..1.0.

b

Blue channel (0.0..1.0).

g

Green channel (0.0..1.0).

r

Red channel (0.0..1.0).

black

Solid black (#000000).

blue

Blue (#2563EB).

dark_gray

Dark gray (#333333).

gray

Creates a grayscale color from 0.0 (black) to 1.0 (white).

green

Green (#16A34A).

hex

Creates a color from a 24-bit 0xRRGGBB value.

light_gray

Light gray (#E5E7EB).

red

Red (#DC2626).

rgb

Creates a color from 8-bit RGB channels (0..255).

rgb_f

Creates a color from normalized floating-point RGB channels (0.0..1.0).

white

Solid white (#FFFFFF).

// Specification for a single table column.
+ struct Column {
    // Horizontal text alignment for cells (and header) in this column.
    + align: TextAlign
    // Column header label.
    + header: String
    // Relative proportional share when `width <= 0.0`.
    + weight: float
    // Fixed width in points (`0.0` means proportional via `weight`).
    + width: float
}

Column

Specification for a single table column.

Set width > 0 for a fixed width in points, or leave width == 0 to share remaining table
width proportionally according to weight.

align

Horizontal text alignment for cells (and header) in this column.

Column header label.

weight

Relative proportional share when width <= 0.0.

width

Fixed width in points (0.0 means proportional via weight).

// A PDF 1.4 document supporting both direct page drawing and flowing multi-page layout.
+ class Document {
    // Controls FlateDecode (zlib) stream compression.
    + compress: bool
    // Current vertical flow cursor (top-down from the top of the current page).
    + cursor_y: float
    // Optional custom footer callback `(page, page_num, total_pages)`.
    + footer: ?fn(Page, uint, uint)()
    // Reserved footer height in points.
    + footer_height: float
    // Optional simple footer text (supports `{page}` and `{pages}`).
    + footer_text: String
    // Optional custom header callback `(page, page_num, total_pages)`.
    + header: ?fn(Page, uint, uint)()
    // Style for `header_text` and `footer_text`.
    + header_footer_style: TextStyle
    // Reserved header height in points.
    + header_height: float
    // Optional simple header text (supports `{page}` and `{pages}`).
    + header_text: String
    // Page margins used by flow helpers.
    + margins: Margins
    // PDF `/Info` metadata fields.
    + metadata: Metadata
    // Default page size for new pages.
    + page_size: PageSize
    // All pages currently in the document.
    ~ pages: Array[Page]

    // Appends a new page using `size` (or the document's default `page_size`) and resets `cursor_y`.
    + fn add_page(size: ?PageSize (null)) Page
    // Bottom y coordinate of the flow content area (above bottom margin and footer).
    + fn content_bottom() float
    // Left x coordinate of the flow content area.
    + fn content_left() float
    // Top y coordinate of the flow content area (below top margin and header).
    + fn content_top() float
    // Usable content width of the current page between left and right margins.
    + fn content_width() float
    // Returns the active (last) page, creating the first page automatically if none exist yet.
    + fn current_page() Page
    // Embeds a JPEG image directly via `DCTDecode` without re-encoding.
    + fn embed_jpeg(data: local &[u8]) ImageRef !Error
    // Embeds raw 8-bit pixel bytes (`channels` = `1` Grayscale, `3` RGB, or `4` RGBA with `/SMask`).
    + fn embed_pixels(width: uint, height: uint, channels: u8, pixels: local &[u8]) ImageRef !Error
    // Ensures at least `height` points remain on the current page, breaking to a new page if needed.
    + fn ensure_space(height: float) Page
    // Adds a heading at `level` (`1` = largest, `2`, `3`, `4`+) and advances the flow cursor.
    + fn heading(text: String, level: uint (1), color: ?Color (null), align: TextAlign (TextAlign.left)) void
    // Draws a horizontal rule across the content width and advances the flow cursor.
    + fn hr(color: Color (Color.hex(0xCBD5E1)), thickness: float (0.75), space_before: float (6.0), space_after: float (6.0)) void
    // Places an embedded image in the document flow with automatic page breaking and alignment.
    + fn image(img: ImageRef, width: float, height: float, align: TextAlign (TextAlign.left), space_after: float (8.0)) void
    // Creates a new empty PDF document.
    + static fn new(options: DocumentOptions (DocumentOptions{})) Document
    // Forces a page break, appending a new page and resetting `cursor_y` to `content_top()`.
    + fn page_break() Page
    // Flows wrapped paragraph text across one or more pages, breaking cleanly between lines.
    + fn paragraph(text: String, style: TextStyle (TextStyle{}), space_after: float (8.0)) void
    // Advances the flow cursor downward by `pt` points.
    + fn spacer(pt: float) void
    // Renders a formatted table in the document flow with automatic cell wrapping, row striping, borders, and page breaks with optional header repetition.
    + fn table(options: TableOptions) void
    // Serializes the entire document into a PDF 1.4 byte string.
    + fn to_bytes() String
    // Serializes and writes the PDF to `path`.
    + fn write_file(path: String) void !Error
    // Serializes and writes the PDF into `writer`.
    + fn write_into(writer: Writer) void !Error
}

Document

A PDF 1.4 document supporting both direct page drawing and flowing multi-page layout.

compress

Controls FlateDecode (zlib) stream compression.

cursor_y

Current vertical flow cursor (top-down from the top of the current page).

Optional custom footer callback (page, page_num, total_pages).

Reserved footer height in points.

Optional simple footer text (supports {page} and {pages}).

header

Optional custom header callback (page, page_num, total_pages).

Style for header_text and footer_text.

header_height

Reserved header height in points.

header_text

Optional simple header text (supports {page} and {pages}).

margins

Page margins used by flow helpers.

metadata

PDF /Info metadata fields.

page_size

Default page size for new pages.

pages

All pages currently in the document.

add_page

Appends a new page using size (or the document's default page_size) and resets cursor_y.

content_bottom

Bottom y coordinate of the flow content area (above bottom margin and footer).

content_left

Left x coordinate of the flow content area.

content_top

Top y coordinate of the flow content area (below top margin and header).

content_width

Usable content width of the current page between left and right margins.

current_page

Returns the active (last) page, creating the first page automatically if none exist yet.

embed_jpeg

Embeds a JPEG image directly via DCTDecode without re-encoding.

embed_pixels

Embeds raw 8-bit pixel bytes (channels = 1 Grayscale, 3 RGB, or 4 RGBA with /SMask).

ensure_space

Ensures at least height points remain on the current page, breaking to a new page if needed.

heading

Adds a heading at level (1 = largest, 2, 3, 4+) and advances the flow cursor.

hr

Draws a horizontal rule across the content width and advances the flow cursor.

image

Places an embedded image in the document flow with automatic page breaking and alignment.

new

Creates a new empty PDF document.

page_break

Forces a page break, appending a new page and resetting cursor_y to content_top().

paragraph

Flows wrapped paragraph text across one or more pages, breaking cleanly between lines.

spacer

Advances the flow cursor downward by pt points.

table

Renders a formatted table in the document flow with automatic cell wrapping, row striping,
borders, and page breaks with optional header repetition.

to_bytes

Serializes the entire document into a PDF 1.4 byte string.

write_file

Serializes and writes the PDF to path.

write_into

Serializes and writes the PDF into writer.

// Configuration options for creating a `Document`.
+ struct DocumentOptions {
    // Enables FlateDecode (zlib) compression on content streams.
    + compress: bool
    // Custom footer render callback invoked per page during serialization: `(page, page_num, total_pages)`.
    + footer: ?fn(Page, uint, uint)()
    // Reserved vertical space in points at the bottom of the content area for page footers.
    + footer_height: float
    // Optional simple footer text rendered on every page (supports `{page}` and `{pages}`).
    + footer_text: String
    // Custom header render callback invoked per page during serialization: `(page, page_num, total_pages)`.
    + header: ?fn(Page, uint, uint)()
    // Style for `header_text` and `footer_text`.
    + header_footer_style: TextStyle
    // Reserved vertical space in points at the top of the content area for page headers.
    + header_height: float
    // Optional simple header text rendered on every page (supports `{page}` and `{pages}`).
    + header_text: String
    // Page margins used by flow layout helpers (`heading`, `paragraph`, `table`, etc.).
    + margins: Margins
    // Metadata written into the PDF `/Info` dictionary.
    + metadata: Metadata
    // Default page dimensions for pages added without an explicit size.
    + page_size: PageSize
}

DocumentOptions

Configuration options for creating a Document.

compress

Enables FlateDecode (zlib) compression on content streams.

Custom footer render callback invoked per page during serialization: (page, page_num, total_pages).

Reserved vertical space in points at the bottom of the content area for page footers.

Optional simple footer text rendered on every page (supports {page} and {pages}).

header

Custom header render callback invoked per page during serialization: (page, page_num, total_pages).

Style for header_text and footer_text.

header_height

Reserved vertical space in points at the top of the content area for page headers.

header_text

Optional simple header text rendered on every page (supports {page} and {pages}).

margins

Page margins used by flow layout helpers (heading, paragraph, table, etc.).

metadata

Metadata written into the PDF /Info dictionary.

page_size

Default page dimensions for pages added without an explicit size.

// Stroke, fill, dash, and opacity settings for vector drawing primitives.
+ struct DrawStyle {
    // Dash pattern lengths in points (empty for a solid stroke).
    + dash: Array[float]
    // Starting offset into the dash pattern in points.
    + dash_phase: float
    // Fill color; `null` disables filling.
    + fill_color: ?Color
    // Fill opacity (`0.0..1.0`).
    + fill_opacity: float
    // Line cap style: `0` = butt, `1` = round, `2` = projecting square.
    + line_cap: u8
    // Line join style: `0` = miter, `1` = round, `2` = bevel.
    + line_join: u8
    // Stroke width in points.
    + line_width: float
    // Stroke color; `null` disables stroking.
    + stroke_color: ?Color
    // Stroke opacity (`0.0..1.0`).
    + stroke_opacity: float
}

DrawStyle

Stroke, fill, dash, and opacity settings for vector drawing primitives.

dash

Dash pattern lengths in points (empty for a solid stroke).

dash_phase

Starting offset into the dash pattern in points.

fill_color

Fill color; null disables filling.

fill_opacity

Fill opacity (0.0..1.0).

line_cap

Line cap style: 0 = butt, 1 = round, 2 = projecting square.

line_join

Line join style: 0 = miter, 1 = round, 2 = bevel.

line_width

Stroke width in points.

stroke_color

Stroke color; null disables stroking.

stroke_opacity

Stroke opacity (0.0..1.0).

// Thrown when building or writing a PDF fails.
+ union Error {
    invalid_image(String)
    invalid_argument(String)
    io(String)

    + get message: String
    + fn to_string() String
}

Error

Thrown when building or writing a PDF fails.

  • invalid_image(message): the supplied image bytes or dimensions are invalid or unsupported.
  • invalid_argument(message): a caller passed an invalid size, dimension, or option.
  • io(message): writing the PDF to a file or io.Writer failed.
// A handle to an image embedded in a `Document`, ready to draw on any page.
+ class ImageRef {
    // Number of color channels (`1` = grayscale, `3` = RGB, `4` = RGBA/CMYK).
    ~ channels: u8
    // Pixel height of the embedded image.
    ~ height: uint
    // 1-based image resource identifier (`Im1`, `Im2`, ...).
    ~ id: uint
    // Pixel width of the embedded image.
    ~ width: uint

    // Returns the PDF XObject resource name (e.g. `"Im1"`).
    + fn resource_name() String
}

ImageRef

A handle to an image embedded in a Document, ready to draw on any page.

channels

Number of color channels (1 = grayscale, 3 = RGB, 4 = RGBA/CMYK).

height

Pixel height of the embedded image.

id

1-based image resource identifier (Im1, Im2, ...).

width

Pixel width of the embedded image.

resource_name

Returns the PDF XObject resource name (e.g. "Im1").

// Page margins in points (`1 pt = 1/72 inch`).
+ struct Margins {
    + bottom: float
    + left: float
    + right: float
    + top: float

    // Separate vertical (`top`/`bottom`) and horizontal (`left`/`right`) margins.
    + static fn symmetric(vertical: float, horizontal: float) Margins
    // Equal margin on all four sides.
    + static fn uniform(v: float) Margins
}

Margins

Page margins in points (1 pt = 1/72 inch).

symmetric

Separate vertical (top/bottom) and horizontal (left/right) margins.

uniform

Equal margin on all four sides.

// Document information metadata written into the PDF `/Info` dictionary.
+ struct Metadata {
    + author: String
    + creator: String
    + keywords: String
    + subject: String
    + title: String
}

Metadata

Document information metadata written into the PDF /Info dictionary.

// A single page in a PDF document.
+ class Page {
    // Page height in points.
    ~ height: float
    // 1-based page number within the document.
    ~ number: uint
    // Page width in points.
    ~ width: float

    // Draws a circle centered at `(cx, cy)` with `radius` points.
    + fn circle(cx: float, cy: float, radius: float, style: DrawStyle) void
    // Convenience helper for drawing a solid filled rectangle.
    + fn filled_rect(x: float, y: float, w: float, h: float, color: Color, opacity: float (1.0)) void
    // Draws an embedded image at top-left `(x, y)` scaled to `width` by `height` points.
    + fn image(img: ImageRef, x: float, y: float, width: float, height: float) void
    // Draws a straight line from `(x1, y1)` to `(x2, y2)`.
    + fn line(x1: float, y1: float, x2: float, y2: float, color: Color (Color.black()), line_width: float (1.0), dash: Array[float] (.{}), opacity: float (1.0)) void
    // Draws a custom vector `Path` using `style`.
    + fn path(p: Path, style: DrawStyle) void
    // Draws a rectangle with top-left corner `(x, y)`, width `w`, and height `h`.
    + fn rect(x: float, y: float, w: float, h: float, style: DrawStyle) void
    // Draws a rectangle with rounded corners of `radius` points.
    + fn rounded_rect(x: float, y: float, w: float, h: float, radius: float, style: DrawStyle) void
    // Convenience helper for drawing a stroked rectangle outline.
    + fn stroked_rect(x: float, y: float, w: float, h: float, color: Color, line_width: float (1.0)) void
    // Draws a single line of `text` with its top-left corner at `(x, y)`.
    + fn text(x: float, y: float, text: String, style: TextStyle (TextStyle{})) void
    // Draws a single line of `text` aligned horizontally within `[x, x + width]`.
    + fn text_aligned(x: float, y: float, width: float, text: String, style: TextStyle (TextStyle{})) void
    // Wraps and draws `text` inside a box of `width` points starting at `(x, y)`.
    + fn text_wrapped(x: float, y: float, width: float, text: String, style: TextStyle (TextStyle{})) float
}

Page

A single page in a PDF document.

All coordinates use a top-left origin: (0, 0) is the top-left corner of the page,
x increases to the right, and y increases downward, measured in points (1 pt = 1/72 inch).

height

Page height in points.

number

1-based page number within the document.

width

Page width in points.

circle

Draws a circle centered at (cx, cy) with radius points.

filled_rect

Convenience helper for drawing a solid filled rectangle.

image

Draws an embedded image at top-left (x, y) scaled to width by height points.

line

Draws a straight line from (x1, y1) to (x2, y2).

path

Draws a custom vector Path using style.

rect

Draws a rectangle with top-left corner (x, y), width w, and height h.

rounded_rect

Draws a rectangle with rounded corners of radius points.

stroked_rect

Convenience helper for drawing a stroked rectangle outline.

text

Draws a single line of text with its top-left corner at (x, y).

text_aligned

Draws a single line of text aligned horizontally within [x, x + width].

text_wrapped

Wraps and draws text inside a box of width points starting at (x, y).

Returns the total vertical height consumed in points.

// Dimensions of a PDF page in points (`1 pt = 1/72 inch`).
+ struct PageSize {
    // Page height in points.
    + height: float
    // Page width in points.
    + width: float

    // ISO A4 (`595.28 x 841.89 pt`, `210 x 297 mm`).
    + static fn a4() PageSize
    // Custom page dimensions in points.
    + static fn custom(width: float, height: float) PageSize
    // Returns a landscape orientation of this size (`width >= height`).
    + fn landscape() PageSize
    // US Legal (`612 x 1008 pt`, `8.5 x 14 in`).
    + static fn legal() PageSize
    // US Letter (`612 x 792 pt`, `8.5 x 11 in`).
    + static fn letter() PageSize
    // Returns a portrait orientation of this size (`height >= width`).
    + fn portrait() PageSize
}

PageSize

Dimensions of a PDF page in points (1 pt = 1/72 inch).

height

Page height in points.

width

Page width in points.

a4

ISO A4 (595.28 x 841.89 pt, 210 x 297 mm).

custom

Custom page dimensions in points.

landscape

Returns a landscape orientation of this size (width >= height).

US Legal (612 x 1008 pt, 8.5 x 14 in).

letter

US Letter (612 x 792 pt, 8.5 x 11 in).

portrait

Returns a portrait orientation of this size (height >= width).

// A sequence of vector path commands in top-left page coordinates.
+ class Path {
    // Closes the current subpath back to its starting point.
    + fn close() Path
    // Appends a cubic Bezier curve with control points `(cx1, cy1)` and `(cx2, cy2)` to `(x, y)`.
    + fn curve_to(cx1: float, cy1: float, cx2: float, cy2: float, x: float, y: float) Path
    // Appends a straight line segment to `(x, y)`.
    + fn line_to(x: float, y: float) Path
    // Starts a new subpath at `(x, y)`.
    + fn move_to(x: float, y: float) Path
    // Creates an empty vector path.
    + static fn new() Path
}

Path

A sequence of vector path commands in top-left page coordinates.

close

Closes the current subpath back to its starting point.

curve_to

Appends a cubic Bezier curve with control points (cx1, cy1) and (cx2, cy2) to (x, y).

line_to

Appends a straight line segment to (x, y).

move_to

Starts a new subpath at (x, y).

new

Creates an empty vector path.

// Fluent builder for constructing `TableOptions`.
+ class Table {
    // Underlying table options populated by the builder.
    + options: TableOptions

    // Appends a column definition to the table.
    + fn column(header: String, width: float (0.0), weight: float (1.0), align: TextAlign (TextAlign.left)) Table
    // Creates a new `Table` builder with default styling.
    + static fn new(options: TableOptions (TableOptions{})) Table
    // Appends a data row of cell strings to the table.
    + fn row(cells: Array[String]) Table
}

Table

Fluent builder for constructing TableOptions.

options

Underlying table options populated by the builder.

column

Appends a column definition to the table.

new

Creates a new Table builder with default styling.

row

Appends a data row of cell strings to the table.

// Configuration for rendering a multi-page table via `Document.table`.
+ struct TableOptions {
    // Grid/border stroke color (`null` disables borders).
    + border_color: ?Color
    // Grid/border stroke width in points.
    + border_width: float
    // Horizontal inner cell padding in points.
    + cell_padding_x: float
    // Vertical inner cell padding in points.
    + cell_padding_y: float
    // Text style for body cells.
    + cell_style: TextStyle
    // Column definitions.
    + columns: Array[Column]
    // Fill color for the header row (`null` for transparent).
    + header_bg: ?Color
    // Text style for header cells.
    + header_style: TextStyle
    // Whether to repeat the header row automatically at the top of continuation pages.
    + repeat_header: bool
    // Fill color for even-indexed body rows (`null` for transparent).
    + row_bg: ?Color
    // Data rows; each row is an array of cell strings matching `columns`.
    + rows: Array[Array[String]]
    // Whether to render the header row.
    + show_header: bool
    // Extra vertical spacing added below the table in points.
    + space_after: float
    // Alternating fill color for odd-indexed body rows (`null` disables striping).
    + stripe_bg: ?Color
    // Explicit table width in points (`0.0` fills the document's `content_width()`).
    + width: float
}

TableOptions

Configuration for rendering a multi-page table via Document.table.

border_color

Grid/border stroke color (null disables borders).

border_width

Grid/border stroke width in points.

cell_padding_x

Horizontal inner cell padding in points.

cell_padding_y

Vertical inner cell padding in points.

cell_style

Text style for body cells.

columns

Column definitions.

header_bg

Fill color for the header row (null for transparent).

header_style

Text style for header cells.

repeat_header

Whether to repeat the header row automatically at the top of continuation pages.

row_bg

Fill color for even-indexed body rows (null for transparent).

rows

Data rows; each row is an array of cell strings matching columns.

show_header

Whether to render the header row.

space_after

Extra vertical spacing added below the table in points.

stripe_bg

Alternating fill color for odd-indexed body rows (null disables striping).

width

Explicit table width in points (0.0 fills the document's content_width()).

// Styling options for rendered text.
+ struct TextStyle {
    // Horizontal alignment within the target box.
    + align: TextAlign
    // Text fill color.
    + color: Color
    // Standard PDF Type1 font to use.
    + font: Font
    // Line height multiplier applied to `size`.
    + line_height: float
    // Font size in points.
    + size: float
}

TextStyle

Styling options for rendered text.

align

Horizontal alignment within the target box.

color

Text fill color.

font

Standard PDF Type1 font to use.

line_height

Line height multiplier applied to size.

size

Font size in points.