Grav v1.14.0

pdf

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.

grav
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")
}
Output
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) and wrap measure with the font's real widths.
  • Text: text, textRight, textCenter, and textBox(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, setFillColor and setStrokeColor (0xRRGGBB), setLineWidth, setDash. raw takes PDF operators directly.
  • Images: doc.addImage(img) stores an Image once, compressed, with transparency as a soft mask. doc.addJpeg(bytes) embeds a JPEG as it is. page.image draws either into a box, keeping the aspect ratio when the height is 0. drawImage(img, …) does both steps at once.
  • Tables: PdfTable takes 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's lastTableBottom says 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 and save(path) writes it. Page contents, images and fonts are Flate-compressed when zlib is present (compress = false turns 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: int
  • capHeight: int
  • objectNumber: 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 of text at size points.
  • fn encode(text: string) -> string — text as 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: int
  • height: int
  • id: string
  • objectNumber: int = 0

Methods

  • fn objectCount() -> int
  • fn 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> = null
  • rows: Array<Array<string>> = new Array<Array<string>>()
  • fontSize: double = 9.0
  • padding: double = 4.0
  • headerFill: long = 0xeeeeee — Colours as 0xRRGGBB; -1 for none.
  • stripeFill: long = -1
  • borderColor: long = 0xbbbbbb
  • textColor: long = 0x000000
  • font: PdfFont = null
  • boldFont: PdfFont = null

Methods

  • fn header(cells: Array<string>) -> PdfTable
  • fn row(cells: Array<string>) -> PdfTable
  • fn align(col: int, how: string) -> PdfTable — Column col (0-based) aligned "left", "right" or "center".
  • fn alignRight(col: int) -> PdfTable
  • fn alignCenter(col: int) -> PdfTable
  • fn stripes(color: long) -> PdfTable — Every other row shaded with color (0xRRGGBB).
  • fn alignOf(col: int) -> string
  • fn 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) -> string
  • static fn rgb(c: long) -> string

Fields

  • width: double
  • height: double
  • content: 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() -> double
  • fn 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, off points); 0, 0 for solid ones.
  • fn text(x: double, y: double, s: string) -> PdfPage — s with the top of its line at (x, y).
  • fn textRight(x: double, y: double, s: string) -> PdfPage — s ending at x (right-aligned).
  • fn textCenter(x: double, y: double, s: string) -> PdfPage — s centred on x.
  • fn textWidth(s: string) -> double — The width of s in the current font and size.
  • fn textBox(x: double, y: double, width: double, s: string, align: string = "left", lineHeight: double = 1.25) -> double — s wrapped to width (at spaces; a word longer than a line is split; "\n" starts a new line), aligned "left", "right", "center" or "justify", lineHeight times 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) -> PdfPage
  • fn 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 in rgb (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 by r.
  • 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 the w x h box 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, size points wide (quiet zone included).
  • fn link(x: double, y: double, w: double, h: double, url: string) -> PdfPage — A clickable area that opens url.
  • 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 of t from row from at (x, y) until bottom (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 are width x height points (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: double
  • pageHeight: double
  • marginTop: 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 (or width x height).
  • fn pageCount() -> int
  • fn page(i: int) -> PdfPage
  • fn 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) on page, 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.

Edit this page on GitHub