import "std/data" (included in import "std") · namespace std.data
PDF documents written from code: invoices, receipts, reports and tickets. Text can use the standard fonts or an embedded TrueType font (for any language). There are wrapped and justified paragraphs, lines, rectangles and circles, images (pixels or JPEG files as they are), QR codes as vectors, links, and tables that continue onto new pages with their header repeated.
import "std"
fn main() {
let doc = new PdfDocument()
doc.title = "Invoice INV-0042"
let page = doc.addPage()
page.setFont(doc.font("Helvetica-Bold"), 20).text(50, 50, "Invoice INV-0042")
page.setFont(doc.font("Helvetica"), 10).setFillColor(0x555555)
.text(50, 78, "Issued 15 Jan 2025 · Due 30 Jan 2025")
page.setFillColor(0x000000)
let used = page.textBox(50, 100, 300, "Thank you for your business. Payment is due within fifteen days of the invoice date.")
let t = new PdfTable([250, 60, 120]).header(["Item", "Qty", "Amount"]).alignRight(1).alignRight(2)
t.row(["Hosting, January", "1", "KES 1,200.00"]).row(["Support hours", "3", "KES 4,500.00"])
let last = doc.table(t, page, 50, 100 + used + 20)
last.setFont(doc.font("Helvetica-Bold"), 11).textRight(480, last.lastTableBottom + 10, "Total: KES 5,700.00")
last.qrCode(QrCode.encode("https://pay.example.test/inv/42"), 50, last.lastTableBottom + 40, 90)
last.link(50, last.lastTableBottom + 40, 90, 90, "https://pay.example.test/inv/42")
let bytes = doc.bytes()
print("${doc.pageCount()} page, starts ${bytes.slice(0, 8).toString()}")
let w = doc.font("Helvetica").width("Invoice", 10)
print("'Invoice' is ${w} pt wide in 10 pt Helvetica")
}1 page, starts %PDF-1.7
'Invoice' is 31.68 pt wide in 10 pt Helvetica- Coordinates are points (1/72 inch) from the page's top-left corner, with y downward. Text is placed by the top of its line. The default page is A4 (
new PdfDocument(612, 792)for US Letter;PdfDocument.a4(),a5(),a3(),letter(),legal()give the sizes).addPage(w, h)can mix page sizes. - Fonts:
doc.font(name)gives one of the standard fonts: Helvetica, Times-Roman, Courier, each with Bold and Oblique/Italic. They need nothing embedded and cover Western European text (Windows-1252).doc.loadFont("DejaVuSans.ttf")embeds a TrueType font for any other script, with a ToUnicode map so text can still be copied and searched.textWidth,font.width(text, size)andwrapmeasure with the font's real widths. - Text:
text,textRight,textCenter, andtextBox(x, y, width, text, align, lineHeight), which wraps at spaces, splits words longer than a line, keeps"\n", and aligns left, right, center or justify. It returns the height it used. - Shapes and colour:
line,rect,fillRect,roundRect,circle,setFillColorandsetStrokeColor(0xRRGGBB),setLineWidth,setDash.rawtakes PDF operators directly. - Images:
doc.addImage(img)stores anImageonce, compressed, with transparency as a soft mask.doc.addJpeg(bytes)embeds a JPEG as it is.page.imagedraws either into a box, keeping the aspect ratio when the height is 0.drawImage(img, …)does both steps at once. - Tables:
PdfTabletakes column widths, a header, rows, per-column alignment, stripes, colours and fonts.doc.table(t, page, x, y)adds pages as needed, repeats the header on each, and returns the page it ended on. That page'slastTableBottomsays where the table stopped. - Also:
link(a clickable area),qrCode(vector modules, sharp at any zoom), and metadata (title,author,subject,keywords,creator).bytes()gives the file andsave(path)writes it. Page contents, images and fonts are Flate-compressed when zlib is present (compress = falseturns that off for inspection).
API
class PdfFont
A font a page can write with: one of the 14 standard ones, or an embedded TrueType.
Constructors
new PdfFont(id: string, name: string, std: int, ttf: byte*)
Fields
id: string— The resource name pages use ("F1").name: string— The PostScript name ("Helvetica-Bold").ascent: int— The height above and below the baseline, and of capitals, in 1/1000 em.descent: intcapHeight: intobjectNumber: int = 0
Methods
fn isEmbedded() -> bool— Whether it is embedded (a TrueType file) rather than one of the standard 14.fn width(text: string, size: double) -> double— The width oftextatsizepoints.fn encode(text: string) -> string—textas a string operand for Tj.fn writeTo(w: PdfWriter)— Writes the font's objects.fn objectCount() -> int— Objects the font takes.
class PdfImage
An image placed in the document once and drawn as often as wanted.
Constructors
new PdfImage(id: string, kind: string, data: Bytes, width: int, height: int, components: int, alpha: Bytes)
Fields
width: intheight: intid: stringobjectNumber: int = 0
Methods
fn objectCount() -> intfn writeTo(w: PdfWriter)
class PdfTable
A table's columns, header, rows and look, drawn by PdfPage.table or, across pages, PdfDocument.table.
Constructors
new PdfTable(widths: Array<double>)
Fields
widths: Array<double>headerRow: Array<string> = nullrows: Array<Array<string>> = new Array<Array<string>>()fontSize: double = 9.0padding: double = 4.0headerFill: long = 0xeeeeee— Colours as 0xRRGGBB; -1 for none.stripeFill: long = -1borderColor: long = 0xbbbbbbtextColor: long = 0x000000font: PdfFont = nullboldFont: PdfFont = null
Methods
fn header(cells: Array<string>) -> PdfTablefn row(cells: Array<string>) -> PdfTablefn align(col: int, how: string) -> PdfTable— Columncol(0-based) aligned "left", "right" or "center".fn alignRight(col: int) -> PdfTablefn alignCenter(col: int) -> PdfTablefn stripes(color: long) -> PdfTable— Every other row shaded withcolor(0xRRGGBB).fn alignOf(col: int) -> stringfn totalWidth() -> double
class PdfPage
A page: draw on it with its methods; each returns the page, so calls chain.
Constructors
new PdfPage(doc: PdfDocument, width: double, height: double)
Static members
static fn n(v: double) -> stringstatic fn rgb(c: long) -> string
Fields
width: doubleheight: doublecontent: StringBuilder = new StringBuilder()fontIds: Array<string> = new Array<string>()imageIds: Array<string> = new Array<string>()links: Array<string> = new Array<string>()lastTableBottom: double = 0.0— Where the last table drawn on this page ended.
Methods
fn setFont(font: PdfFont, size: double) -> PdfPage— The font and size for the text that follows (Helvetica 12 until set).fn font() -> PdfFont— The current font and size.fn fontSize() -> doublefn setFillColor(rgb: long) -> PdfPage— The colour text and filled shapes are drawn in (0xRRGGBB).fn setStrokeColor(rgb: long) -> PdfPage— The colour of lines and outlines (0xRRGGBB).fn setLineWidth(w: double) -> PdfPage— The width of lines and outlines, in points.fn setDash(on: double, off: double) -> PdfPage— Dashed lines (on,offpoints); 0, 0 for solid ones.fn text(x: double, y: double, s: string) -> PdfPage—swith the top of its line at (x, y).fn textRight(x: double, y: double, s: string) -> PdfPage—sending at x (right-aligned).fn textCenter(x: double, y: double, s: string) -> PdfPage—scentred on x.fn textWidth(s: string) -> double— The width ofsin the current font and size.fn textBox(x: double, y: double, width: double, s: string, align: string = "left", lineHeight: double = 1.25) -> double—swrapped towidth(at spaces; a word longer than a line is split; "\n" starts a new line), aligned "left", "right", "center" or "justify",lineHeighttimes the font size apart. Returns the height used.fn wrap(s: string, width: double) -> Array<string>— The lines textBox would draw.fn line(x1: double, y1: double, x2: double, y2: double) -> PdfPagefn rect(x: double, y: double, w: double, h: double, fill: bool = false, stroke: bool = true) -> PdfPage— A rectangle, filled with the fill colour, outlined, or both.fn fillRect(x: double, y: double, w: double, h: double, rgb: long) -> PdfPage— A filled rectangle inrgb(0xRRGGBB), leaving the fill colour as it was.fn roundRect(x: double, y: double, w: double, h: double, r: double, fill: bool = false, stroke: bool = true) -> PdfPage— A rectangle with corners rounded byr.fn circle(cx: double, cy: double, r: double, fill: bool = false, stroke: bool = true) -> PdfPage— A circle centred on (cx, cy).fn image(img: PdfImage, x: double, y: double, w: double, h: double = 0.0) -> PdfPage— An image scaled into thewxhbox at (x, y) (h 0: from the aspect ratio).fn drawImage(img: Image, x: double, y: double, w: double, h: double = 0.0) -> PdfPage— An Image added to the document and drawn (add it once with doc.addImage to draw it several times).fn qrCode(qr: QrCode, x: double, y: double, size: double, border: int = 2) -> PdfPage— A QR code drawn as vector squares,sizepoints wide (quiet zone included).fn link(x: double, y: double, w: double, h: double, url: string) -> PdfPage— A clickable area that opensurl.fn raw(operators: string) -> PdfPage— Raw content-stream operators, for what the methods do not cover (PDF coordinates: origin bottom-left).fn table(t: PdfTable, x: double, y: double, from: int = 0, bottom: double = -1.0) -> int— Draws rows oftfrom rowfromat (x, y) untilbottom(a y on this page); returns the index of the first row that did not fit (t.rows.size() when all did).
class PdfWriter
Assembles the file: objects, cross-reference table, trailer.
Constructors
new PdfWriter(compress: bool)
Fields
out: Bytes = new Bytes()offsets: Array<int> = new Array<int>()compress: bool = true
Methods
fn object(n: int, body: string)fn stream(n: int, dict: string, data: Bytes, deflate: bool)
class PdfDocument
A PDF document.
Constructors
new PdfDocument(width: double = 595.28, height: double = 841.89)— A document whose pages arewidthxheightpoints (A4 by default).
Static members
static fn a4() -> Array<double>— Page sizes in points.static fn a5() -> Array<double>static fn a3() -> Array<double>static fn letter() -> Array<double>static fn legal() -> Array<double>
Fields
title: string = ""— Metadata shown in viewers' document properties.author: string = ""subject: string = ""keywords: string = ""creator: string = "Grav"compress: bool = true— Flate-compress page contents, pixel images and fonts (when zlib is present).pageWidth: doublepageHeight: doublemarginTop: double = 40.0— Margins PdfDocument.table keeps from the page edges when it adds pages.marginBottom: double = 40.0
Methods
fn addPage(width: double = 0.0, height: double = 0.0) -> PdfPage— A new page at the document's size (orwidthxheight).fn pageCount() -> intfn page(i: int) -> PdfPagefn font(name: string) -> PdfFont— One of the standard fonts: Helvetica, Helvetica-Bold, Helvetica-Oblique, Helvetica-BoldOblique, Times-Roman, Times-Bold, Times-Italic, Times-BoldItalic, Courier, Courier-Bold, Courier-Oblique, Courier-BoldOblique.fn loadFont(path: string) -> PdfFont— A TrueType font from a .ttf file, embedded so any character it has can be written.fn fontFromBytes(data: Bytes) -> PdfFont— loadFont, from the font file's bytes.fn addImage(img: Image) -> PdfImage— An Image for drawing: compressed once, drawn by reference as often as wanted. Transparency becomes a soft mask.fn addJpeg(data: Bytes) -> PdfImage— A JPEG file's bytes, embedded as they are (no re-encoding, no quality lost).fn table(t: PdfTable, page: PdfPage, x: double, y: double) -> PdfPage— Draws a table from (x, y) onpage, adding pages (at marginTop, with the header again) while rows remain. Returns the page it ended on; that page's lastTableBottom is where it ended.fn bytes() -> Bytes— The finished file.fn save(path: string)— Writes the file.