prawn

package module
v0.0.0-...-a5f2d78 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2026 License: BSD-3-Clause Imports: 16 Imported by: 0

README

go-ruby-prawn/prawn

prawn — go-ruby-prawn

Docs License Go Coverage

A pure-Go (no cgo), MRI-faithful reimplementation of Ruby's prawn PDF-generation gem. It mirrors prawn's document DSL — text, fonts (Core-14 and embedded/subset TrueType), colors (RGB and CMYK), vector graphics, images, transformations, a grid, bounding boxes, repeaters/page numbering, a table, plus the Prawn::Errors tree — and writes the PDF with its own native pure-Go PDF object model and content-stream writer. The emitted content-stream operators match Ruby prawn / PDF::Core operator-for-operator, so the output is validated against the real gem with a PDF::Inspector-style differential oracle. No C PDF library, no Ruby runtime, and no third-party PDF generator: the module has zero non-stdlib runtime dependencies and builds with CGO disabled on every supported 64-bit target (and to WebAssembly).

It is a PDF backend for go-embedded-ruby, but is a standalone, reusable module — a sibling of go-ruby-rqrcode, go-ruby-regexp and go-ruby-yaml.

What it is — and isn't. Emitting a PDF (page layout, text placement, vector graphics, image embedding) is deterministic and needs no interpreter, so it lives here as pure Go. Binding Prawn::Document to live Ruby objects is the host's job; this library hands back a plain, well-formed PDF byte stream.

Ruby → Go

Prawn's block-form generator

Prawn::Document.generate("hello.pdf") do |pdf|
  pdf.text "Hello World", size: 24, style: :bold
  pdf.move_down 20
  pdf.stroke_rectangle [0, pdf.cursor], 200, 100
end

becomes

prawn.Generate("hello.pdf", func(pdf *prawn.Document) error {
    pdf.Text("Hello World", &prawn.TextOptions{Size: 24, Style: prawn.StyleBold, StyleSet: true})
    pdf.MoveDown(20)
    pdf.StrokeRectangle(0, pdf.Cursor(), 200, 100)
    return nil
})

Ruby keyword-argument hashes become option structs (a nil selects prawn's defaults); Ruby symbols become typed Go constants (Style*, Align*, page-size and layout strings). Coordinates are PDF points (1/72 inch) with prawn's origin: the lower-left corner of the margin box (bounds).

Features

Faithful port of the frequently used prawn DSL, verified by generating documents and parsing them back:

  • Document & pagesNew / Generate / GenerateTo / GenerateWith, Render, RenderFile, StartNewPage, Cursor, MoveCursorTo, Bounds, MoveDown / MoveUp, Pad / PadTop / PadBottom, PageCount. Page sizes (LETTER … A0–A10, B0–B6, C0–C6, custom) and portrait / landscape layout, with prawn's 36pt default margins (uniform or per-side).
  • TextText (flowing, wrapping, auto-paginating), DrawText (absolute), TextBox (positioned box with :truncate / :expand / :error overflow), Font / FontSize / Leading, alignment (left / center / right / justify).
  • Fonts — the 14 standard AFM fonts (Font/FontSize/Leading, kerning), plus TrueType embedding with subsetting (RegisterFontTTF): glyf/loca/hmtx subset following composite references, written as a Type0/CIDFontType2 font with Identity-H, a FontFile2 stream, a /W width array and a /ToUnicode CMap.
  • Formatted textFormattedText (styled runs) and TextInline (<b>/<i>/<color> markup).
  • ColorFillColor / StrokeColor (hex "RRGGBB") and CMYK (FillColorCMYK / StrokeColorCMYK), emitted via prawn's cs/scn, CS/SCN operators.
  • GraphicsMoveTo/LineTo/CurveTo, Rectangle, Line, Polygon, Circle/Ellipse, Stroke/Fill/FillAndStroke/CloseAndStroke, StrokeBounds, LineWidth, CapStyle/JoinStyle, Dash/Undash.
  • LayoutBoundingBox, the column/row Grid, Repeat / NumberPages, and affine transforms Rotate / Scale / Translate (with origin), TransformationMatrix, SaveGraphicsState/RestoreGraphicsState, Transparency.
  • ImagesImage (file) / ImageReader (io) for PNG (alpha → SMask) and JPEG (DCTDecode passthrough), with at, width, height and fit.
  • Table — a basic grid (Table): explicit or automatic column widths, optional bold header row, cell padding and borders, positioning.
  • Errors — the Prawn::Errors tree (ErrCannotFit, ErrUnknownFont, ErrInvalidPageLayout, ErrUnsupportedImageType, ErrEmptyGraphicStateStack, ErrIncompatibleStringEncoding, …).

CGO-free, 100% test coverage, gofmt + go vet clean, race-clean, and green across the six 64-bit Go targets (amd64, arm64, riscv64, loong64, ppc64le, s390x), two WebAssembly targets and three OSes.

Differential oracle

The output is validated against the real Ruby prawn gem the way prawn validates itself — with a PDF::Inspector-style parse of the content stream, not raw byte-equality (PDFs carry timestamps and ids). For each scenario, the PDF operators this library emits (BT/Td/Tf/kerned TJ, re/l/m/c, S/f, cs/scn, CS/SCN, cm, Do) are compared operator-for-operator against the gem's for the same script. The gem's operator streams are captured into testdata/oracle/*.content and committed, so the oracle runs in CI without Ruby; a skip-gated test re-verifies them against a live gem when one is installed. See prawn_diff_test.go / prawn_gem_test.go.

Install

go get github.com/go-ruby-prawn/prawn

Usage

package main

import (
	"log"

	"github.com/go-ruby-prawn/prawn"
)

func main() {
	err := prawn.Generate("report.pdf", func(pdf *prawn.Document) error {
		pdf.Font("Times", prawn.StyleBold)
		pdf.Text("Quarterly Report", &prawn.TextOptions{Size: 24, Align: prawn.AlignCenter})
		pdf.MoveDown(12)

		pdf.FillColor("333333")
		pdf.Text("Generated with pure-Go prawn.", nil)

		pdf.Table([][]string{
			{"Item", "Qty", "Price"},
			{"Widget", "3", "9.99"},
			{"Gadget", "1", "19.99"},
		}, prawn.TableOptions{Header: true})

		pdf.StrokeColor("CC0000")
		pdf.StrokeRectangle(0, pdf.Cursor(), pdf.Bounds().Width, 40)
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}

Determinism

The PDF /CreationDate comes from a package clock seam, not the wall clock, so output is reproducible and timezone independent — pin it with SetClock:

defer prawn.SetClock(prawn.SetClock(func() time.Time {
	return time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
}))

PDF is a byte-oriented format and every dependency is pure Go, so the bytes are identical on little- and big-endian architectures alike.

Tests & coverage

The suite is self-contained: it generates PDFs in memory and parses them back with the pure-Go rsc.io/pdf reader, asserting that each document is a well-formed PDF (header, xref, trailer, %%EOF), that the expected text appears on the right page with the right font and size, that images are embedded as image XObjects, and that table cells and vector graphics are drawn. It also runs the committed-fixture differential operator oracle (see above) comparing the emitted operators to the real prawn gem's. No Ruby runtime and no network are needed in CI; the live-gem re-verification skips when Ruby is absent. 100% statement coverage is enforced.

COVERPKG=$(go list ./... | paste -sd, -)
go test -race -coverpkg="$COVERPKG" -coverprofile=cover.out ./...
go tool cover -func=cover.out | tail -1   # 100.0%

Scope

Covered faithfully: document + page management, text (flowing / absolute / box), formatted/inline text, Core-14 AFM fonts and subset-embedded TrueType, color (RGB + CMYK), vector graphics, bounding boxes, grid, transformations, repeaters/page numbering, PNG/JPEG images and a basic table.

Font embedding also has a go-opentype-backed backend (RegisterFontOTF) built on the pure-Go github.com/go-opentype/opentype

  • .../shape stack. On top of the glyf/TrueType path it adds:
  • CFF/OpenType (.otf, "OTTO") embedding as a CIDFontType0 descendant with a FontFile3 (/Subtype /OpenType) program;
  • an opt-in shaped-text path (OTFOptions{Shape: true}) so Arabic joining, Indic reordering, CJK and Latin ligatures/kerning (GSUB + GPOS) render with the correct glyphs and spacing, emitted as a positioned TJ array;
  • variable-font instance selection (OTFOptions{Variation: {"wght": 700}}), so measured widths and the per-CID /W advances follow the chosen axis.

The default Prawn text API (text, formatted_text, font, width_of) is unchanged; shaping and variation are opt-in, so default output stays Prawn-compatible.

Deferred (named in doc.go, not implemented): advanced prawn-table features (row/column spanning, per-cell style callbacks, automatic table pagination), GPOS mark-attachment vertical placement in the PDF (substitution + horizontal advances are applied), glyf/CFF subsetting for the OTF backend (the whole font program is embedded), CJK/soft-hyphen line breaking, and SVG.

License

BSD-3-Clause — see LICENSE. Copyright the go-ruby-prawn/prawn authors.

WebAssembly

Being pure Go (CGO=0), this library also compiles to WebAssembly — both GOOS=js GOARCH=wasm (browser / Node.js) and GOOS=wasip1 GOARCH=wasm (WASI). CI builds both targets on every push, alongside the six 64-bit native/qemu arches.

GOOS=js     GOARCH=wasm go build ./...   # browser / Node
GOOS=wasip1 GOARCH=wasm go build ./...   # WASI (wasmtime, wasmer, wasmedge, …)

Documentation

Overview

Package prawn is a pure-Go (CGO=0), MRI-faithful reimplementation of Ruby's prawn PDF-generation gem.

It mirrors prawn's public DSL — Prawn::Document and its text / font / color / graphics / image / table / transformation / grid / page-management methods, plus the Prawn::Errors tree — and writes the PDF with its own native, pure-Go PDF object model and content-stream writer (see pdfcore.go / content.go). The emitted content-stream operators match Ruby prawn / PDF::Core operator-for-operator (BT/ET, Td, Tf, kerned TJ, re/l/m/c, S/f/b, cs/scn, CS/SCN, cm, Do, gs), so a PDF::Inspector-style parse of the output yields the same operator tree. Nothing here uses cgo or a Ruby runtime, so the whole module builds and runs with CGO disabled on every supported 64-bit target and compiles to WebAssembly.

Mapping from Ruby to Go

Ruby's block-form generator

Prawn::Document.generate("hello.pdf") do |pdf|
  pdf.text "Hello World", size: 24, style: :bold
  pdf.move_down 20
  pdf.stroke_rectangle [0, pdf.cursor], 200, 100
end

becomes

prawn.Generate("hello.pdf", func(pdf *prawn.Document) error {
    pdf.Text("Hello World", &prawn.TextOptions{Size: 24, Style: prawn.StyleBold, StyleSet: true})
    pdf.MoveDown(20)
    pdf.StrokeRectangle(0, pdf.Cursor(), 200, 100)
    return nil
})

Ruby keyword-argument hashes map to option structs (nil selects prawn's defaults); Ruby symbols map to typed Go constants (Style*, Align*, page-size and layout string constants). Coordinates use PDF points (1/72 inch) with prawn's native origin: the lower-left corner of the current bounding box, y up.

Fonts

The 14 standard PDF (AFM/Core-14) fonts are supported with prawn's exact glyph-advance and kerning metrics (WinAnsi/cp1252 encoding, kerned TJ output). TrueType fonts are embedded the way prawn/ttfunk does: parsed, subset down to the used glyphs (following composite-glyph references), and written as a Type0 / CIDFontType2 font with Identity-H encoding, a FontFile2 stream, a per-CID /W width array and a /ToUnicode CMap (see RegisterFontTTF).

Verification

Every PDF is a well-formed PDF that round-trips through the pure-Go rsc.io/pdf reader. The library is validated against the real Ruby prawn gem with a PDF::Inspector-style differential oracle: for a set of scenarios, the content-stream operators this package emits are compared, operator-for-operator (numbers normalized), against the gem's output for the same script. The gem's output is captured into testdata/oracle/*.content and committed so the oracle runs in CI without Ruby; a skip-gated test re-verifies those fixtures against a live gem when one is installed. See prawn_diff_test.go and prawn_gem_test.go.

Determinism

The PDF /CreationDate and file /ID are derived from a package clock seam (see SetClock) rather than the wall clock, so output is reproducible and timezone independent. The bytes are big-endian/little-endian independent (the format is byte-oriented and all binary parsing is explicitly big-endian), so the s390x lane exercises the same code path as the little-endian ones.

Scope

Implemented: document + page management (Generate/New, Render, RenderFile, StartNewPage, Cursor, Bounds, MoveDown/Up, Pad, page sizes and layout, SkipPageCreation, stream compression); text (Text, DrawText, TextBox with truncate/expand/error overflow, Font/FontSize/Leading, alignment, kerning, WidthOfString); formatted text (FormattedText runs and TextInline <b>/<i>/ <color> markup); Core-14 AFM fonts and TrueType embedding with subsetting; color (RGB and CMYK fill/stroke via cs/scn, CS/SCN); vector graphics (MoveTo/LineTo/CurveTo, Rectangle, Line, Polygon, Circle/Ellipse, Stroke/Fill/ FillAndStroke/CloseAndStroke, LineWidth, Cap/Join style, Dash); bounding boxes; the column/row grid; affine transformations (Rotate/Scale/Translate, with origin, and TransformationMatrix) plus save/restore graphics state and transparency; PNG (with alpha → SMask) and JPEG images; repeaters and page numbering; and the Prawn::Errors tree.

Deferred (named): prawn-table's advanced features (row/column spanning, per-cell style callbacks, automatic table pagination); TrueType 'kern'-table and GPOS kerning for embedded fonts (AFM kerning is complete); OpenType/CFF (glyf-based TrueType only); soft-hyphen/CJK line breaking; and SVG.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCannotFit mirrors Prawn::Errors::CannotFit — content is too large for
	// the space it must occupy (e.g. a word wider than the available width).
	ErrCannotFit = &prawnError{kind: "CannotFit"}

	// ErrUnknownFont mirrors Prawn::Errors::UnknownFont — a font was requested
	// by a name that has not been registered.
	ErrUnknownFont = &prawnError{kind: "UnknownFont"}

	// ErrInvalidPageLayout mirrors Prawn::Errors::InvalidPageLayout — a page
	// layout other than :portrait or :landscape was requested.
	ErrInvalidPageLayout = &prawnError{kind: "InvalidPageLayout"}

	// ErrUnsupportedImageType mirrors Prawn::Errors::UnsupportedImageType — an
	// image whose format is neither PNG nor JPEG was supplied.
	ErrUnsupportedImageType = &prawnError{kind: "UnsupportedImageType"}

	// ErrEmptyGraphicStateStack mirrors Prawn::Errors::EmptyGraphicStateStack —
	// restore_graphics_state was called with no matching save_graphics_state.
	ErrEmptyGraphicStateStack = &prawnError{kind: "EmptyGraphicStateStack"}

	// ErrIncompatibleStringEncoding mirrors
	// Prawn::Errors::IncompatibleStringEncoding — a string cannot be rendered
	// with the current font (here: invalid UTF-8).
	ErrIncompatibleStringEncoding = &prawnError{kind: "IncompatibleStringEncoding"}
)

Sentinel errors mirror the parameterless Prawn::Errors classes. They are returned directly (or wrapped) so callers can use errors.Is.

Functions

func Generate

func Generate(path string, block func(*Document) error) error

Generate mirrors Prawn::Document.generate(path) { |pdf| … }.

func GenerateTo

func GenerateTo(w io.Writer, block func(*Document) error) error

GenerateTo mirrors Prawn::Document.generate(io) { |pdf| … } for a writer.

func GenerateWith

func GenerateWith(path string, o Options, block func(*Document) error) error

GenerateWith is Generate with explicit document options.

func SetClock

func SetClock(fn func() time.Time) (previous func() time.Time)

SetClock overrides the time source used for the PDF /CreationDate and returns the previous source. Passing nil resets to the wall clock (time.Now).

Types

type Align

type Align int

Align mirrors a prawn alignment symbol (:left, :center, :right, :justify).

const (
	// AlignLeft left-aligns text (prawn :left, the default).
	AlignLeft Align = iota
	// AlignCenter centers text (prawn :center).
	AlignCenter
	// AlignRight right-aligns text (prawn :right).
	AlignRight
	// AlignJustify justifies text (prawn :justify).
	AlignJustify
)

type Bounds

type Bounds struct {
	Width, Height float64
	Left, Bottom  float64
}

Bounds exposes the current margin/bounding box.

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document mirrors Prawn::Document. It owns a native PDF object model (no cgo, no third-party PDF writer) and tracks prawn's drawing state so the emitted content-stream operators match Ruby prawn's.

func New

func New(o Options) *Document

New creates a Document, mirroring Prawn::Document.new(options).

func (*Document) BoundingBox

func (d *Document) BoundingBox(x, y, width, height float64, block func())

BoundingBox mirrors Prawn::Document#bounding_box([x, y], width:, height:) { … }. (x, y) is the top-left corner in the current bounds' coordinates. Inside the block, bounds and the cursor are relative to the new box; afterwards the document cursor is left at the box's bottom, as prawn does.

func (*Document) Bounds

func (d *Document) Bounds() Bounds

Bounds returns the current bounding box (Prawn::Document#bounds).

func (*Document) CapStyle

func (d *Document) CapStyle(style int)

CapStyle mirrors Prawn::Document#cap_style: 0 butt, 1 round, 2 projecting.

func (*Document) Circle

func (d *Document) Circle(x, y, r float64)

Circle mirrors Prawn::Document#circle([x, y], r).

func (*Document) CloseAndStroke

func (d *Document) CloseAndStroke()

CloseAndStroke mirrors Prawn::Document#close_and_stroke: paints with "s".

func (*Document) ClosePath

func (d *Document) ClosePath()

ClosePath mirrors Prawn::Document#close_path: emits "h".

func (*Document) Cursor

func (d *Document) Cursor() float64

Cursor mirrors Prawn::Document#cursor.

func (*Document) CurveTo

func (d *Document) CurveTo(destX, destY, c1x, c1y, c2x, c2y float64)

CurveTo mirrors Prawn::Document#curve_to(dest, bounds: [c1, c2]): emits the two control points and the destination followed by "c".

func (*Document) Dash

func (d *Document) Dash(on, off, phase float64)

Dash mirrors Prawn::Document#dash(length, space:, phase:): sets a dash of alternating on/off lengths and writes the "[on off] phase d" operator.

func (*Document) DefineGrid

func (d *Document) DefineGrid(columns, rows int, gutter float64) *Grid

DefineGrid mirrors Prawn::Document#define_grid(columns:, rows:, gutter:).

func (*Document) DrawText

func (d *Document) DrawText(s string, x, y float64, opts *TextOptions)

DrawText mirrors Prawn::Document#draw_text(string, at: [x, y]): one line at an absolute (bounds-relative) point, no wrapping, cursor unchanged. The point is the text baseline, as in prawn.

func (*Document) Ellipse

func (d *Document) Ellipse(x, y, rx, ry float64)

Ellipse mirrors Prawn::Document#ellipse([x, y], rx, ry): four Bézier arcs around the centre, ending with a MoveTo back to the centre (prawn's exact construction).

func (*Document) Error

func (d *Document) Error() error

Error reports the first accumulated build error, or nil.

func (*Document) Fill

func (d *Document) Fill()

Fill mirrors Prawn::Document#fill: paints the current path with "f".

func (*Document) FillAndStroke

func (d *Document) FillAndStroke()

FillAndStroke mirrors Prawn::Document#fill_and_stroke: paints with "b".

func (*Document) FillCircle

func (d *Document) FillCircle(x, y, r float64)

FillCircle mirrors Prawn::Document#fill_circle([x, y], r).

func (*Document) FillColor

func (d *Document) FillColor(hex string)

FillColor mirrors Prawn::Document#fill_color = "RRGGBB": it sets the fill color (used for shapes and text) and emits the color-space + scn operators.

func (*Document) FillColorCMYK

func (d *Document) FillColorCMYK(c, m, y, k float64)

FillColorCMYK mirrors Prawn::Document#fill_color(c, m, y, k) with 0..100 components.

func (*Document) FillColorValue

func (d *Document) FillColorValue() string

FillColorValue and StrokeColorValue return the current colors as hex strings.

func (*Document) FillEllipse

func (d *Document) FillEllipse(x, y, rx, ry float64)

FillEllipse mirrors Prawn::Document#fill_ellipse([x, y], rx, ry).

func (*Document) FillPolygon

func (d *Document) FillPolygon(points ...[2]float64)

FillPolygon mirrors Prawn::Document#fill_polygon.

func (*Document) FillRectangle

func (d *Document) FillRectangle(x, y, w, h float64)

FillRectangle mirrors Prawn::Document#fill_rectangle.

func (*Document) Font

func (d *Document) Font(name string, style Style)

Font mirrors Prawn::Document#font(name, style:). It selects a Core-14 built-in family or a previously embedded TTF family by name and an optional style.

func (*Document) FontFamily

func (d *Document) FontFamily() string

FontFamily returns the current font's PostScript/base name.

func (*Document) FontSize

func (d *Document) FontSize(size float64)

FontSize sets the current font size in points (Prawn::Document#font_size=).

func (*Document) FontSizeValue

func (d *Document) FontSizeValue() float64

FontSizeValue returns the current font size (Prawn::Document#font_size).

func (*Document) FontStyle

func (d *Document) FontStyle() Style

FontStyle reports the current style inferred from the base font name.

func (*Document) FormattedText

func (d *Document) FormattedText(frags []FormattedFragment, opts *TextOptions)

FormattedText mirrors Prawn::Document#formatted_text(array): it lays a sequence of styled runs as flowing, wrapping text starting at the cursor, advancing it downward. Runs are laid out inline; a run wraps to the next line when it no longer fits the bounding-box width.

func (*Document) Image

func (d *Document) Image(path string, o ImageOptions) ImageResult

Image mirrors Prawn::Document#image(path, options): embeds a PNG or JPEG.

func (*Document) ImageReader

func (d *Document) ImageReader(r io.Reader, tp string, o ImageOptions) ImageResult

ImageReader mirrors Prawn::Document#image(io, options): embeds an image from a reader. tp is "png", "jpg" or "jpeg".

func (*Document) JoinStyle

func (d *Document) JoinStyle(style int)

JoinStyle mirrors Prawn::Document#join_style: 0 miter, 1 round, 2 bevel.

func (*Document) KerningEnabled

func (d *Document) KerningEnabled() bool

KerningEnabled reports whether kerning is on.

func (*Document) Leading

func (d *Document) Leading(n float64)

Leading sets the document-wide extra leading (Prawn::Document#default_leading).

func (*Document) LeadingValue

func (d *Document) LeadingValue() float64

LeadingValue returns the current default leading.

func (*Document) Line

func (d *Document) Line(x1, y1, x2, y2 float64)

Line mirrors Prawn::Document#line([x1, y1], [x2, y2]): MoveTo then LineTo.

func (*Document) LineTo

func (d *Document) LineTo(x, y float64)

LineTo mirrors Prawn::Document#line_to([x, y]): emits "x y l".

func (*Document) LineWidth

func (d *Document) LineWidth(n float64)

LineWidth mirrors Prawn::Document#line_width = n: sets and writes "n w".

func (*Document) LineWidthValue

func (d *Document) LineWidthValue() float64

LineWidthValue mirrors Prawn::Document#line_width (reader).

func (*Document) MoveCursorTo

func (d *Document) MoveCursorTo(y float64)

MoveCursorTo mirrors Prawn::Document#move_cursor_to.

func (*Document) MoveDown

func (d *Document) MoveDown(n float64)

MoveDown mirrors Prawn::Document#move_down.

func (*Document) MoveTo

func (d *Document) MoveTo(x, y float64)

MoveTo mirrors Prawn::Document#move_to([x, y]): emits "x y m".

func (*Document) MoveUp

func (d *Document) MoveUp(n float64)

MoveUp mirrors Prawn::Document#move_up.

func (*Document) NumberPages

func (d *Document) NumberPages(format string, x, y float64, opts *TextOptions)

NumberPages mirrors Prawn::Document#number_pages(string, options): stamps a page number onto every page. In the format string, "<page>" and "<total>" are replaced with the current page number and total page count. The text baseline is placed at the bounds-relative point (x, y).

func (*Document) Pad

func (d *Document) Pad(n float64, block func())

Pad mirrors Prawn::Document#pad.

func (*Document) PadBottom

func (d *Document) PadBottom(n float64, block func())

PadBottom mirrors Prawn::Document#pad_bottom.

func (*Document) PadTop

func (d *Document) PadTop(n float64, block func())

PadTop mirrors Prawn::Document#pad_top.

func (*Document) PageCount

func (d *Document) PageCount() int

PageCount mirrors Prawn::Document#page_count.

func (*Document) PageHeight

func (d *Document) PageHeight() float64

PageHeight returns the current page height in points.

func (*Document) PageNumber

func (d *Document) PageNumber() int

PageNumber returns the current (1-based) page number.

func (*Document) PageWidth

func (d *Document) PageWidth() float64

PageWidth returns the current page width in points.

func (*Document) Polygon

func (d *Document) Polygon(points ...[2]float64)

Polygon mirrors Prawn::Document#polygon(points…): MoveTo the first point, LineTo the rest and back to the first, then "h".

func (*Document) Rectangle

func (d *Document) Rectangle(x, y, w, h float64)

Rectangle mirrors Prawn::Document#rectangle([x, y], w, h): (x, y) is the upper-left corner; emits "x (y-h) w h re".

func (*Document) RegisterFontOTF

func (d *Document) RegisterFontOTF(name string, data []byte, opts *OTFOptions) error

RegisterFontOTF parses a TrueType or OpenType font with the go-opentype stack and registers it under family name, gaining CFF/OTF embedding plus optional complex-script shaping and variable-font instancing (see OTFOptions). Subsequent Font(name, …) calls select it, exactly like a font registered with RegisterFontTTF. A nil opts means the default, Prawn-compatible behaviour.

func (*Document) RegisterFontTTF

func (d *Document) RegisterFontTTF(name string, data []byte) error

RegisterFontTTF parses a TrueType font and registers it under the given family name (Prawn::Document#font_families/#font with a TTF file). Subsequent Font(name, …) calls select it.

func (*Document) Render

func (d *Document) Render() ([]byte, error)

Render mirrors Prawn::Document#render: it finalizes the document (running any repeaters / page numbering, balancing each page's graphics state) and returns the finished PDF as bytes. Any accumulated build error is returned here.

func (*Document) RenderFile

func (d *Document) RenderFile(path string) error

RenderFile mirrors Prawn::Document#render_file(path).

func (*Document) Repeat

func (d *Document) Repeat(filter func(page, total int) bool, block func())

Repeat mirrors Prawn::Document#repeat(filter) { … }: the block is executed on each page (at render time) for which filter(pageNumber, totalPages) is true.

func (*Document) RepeatPageCount

func (d *Document) RepeatPageCount() int

RepeatPageCount returns the total page count while a repeater block runs.

func (*Document) RepeatPageNumber

func (d *Document) RepeatPageNumber() int

RepeatPageNumber returns the current page number while a repeater/NumberPages block runs (1-based); 0 outside a repeater.

func (*Document) RestoreGraphicsState

func (d *Document) RestoreGraphicsState()

RestoreGraphicsState mirrors Prawn::Document#restore_graphics_state: emits "Q". Calling it without a matching save records ErrEmptyGraphicStateStack.

func (*Document) Rotate

func (d *Document) Rotate(angle float64, block func())

Rotate mirrors Prawn::Document#rotate(angle) { … } (about the origin).

func (*Document) RotateAbout

func (d *Document) RotateAbout(angle, ox, oy float64, block func())

RotateAbout mirrors Prawn::Document#rotate(angle, origin: [ox, oy]) { … }.

func (*Document) SaveGraphicsState

func (d *Document) SaveGraphicsState()

SaveGraphicsState mirrors Prawn::Document#save_graphics_state: emits "q".

func (*Document) Scale

func (d *Document) Scale(factor float64, block func())

Scale mirrors Prawn::Document#scale(factor) { … } (uniform scale about the coordinate origin).

func (*Document) ScaleAbout

func (d *Document) ScaleAbout(factor, ox, oy float64, block func())

ScaleAbout mirrors Prawn::Document#scale(factor, origin: [ox, oy]) { … }.

func (*Document) SetKerning

func (d *Document) SetKerning(on bool)

SetKerning enables or disables kerning for subsequent text (prawn default on).

func (*Document) StartNewPage

func (d *Document) StartNewPage()

StartNewPage mirrors Prawn::Document#start_new_page. Pages are closed (their content balanced) only at render time, so repeaters and page numbering can still draw onto any page.

func (*Document) Stroke

func (d *Document) Stroke()

Stroke mirrors Prawn::Document#stroke: paints the current path with "S".

func (*Document) StrokeBounds

func (d *Document) StrokeBounds()

StrokeBounds mirrors Prawn::Document#stroke_bounds: outline the bounding box.

func (*Document) StrokeCircle

func (d *Document) StrokeCircle(x, y, r float64)

StrokeCircle mirrors Prawn::Document#stroke_circle([x, y], r).

func (*Document) StrokeColor

func (d *Document) StrokeColor(hex string)

StrokeColor mirrors Prawn::Document#stroke_color = "RRGGBB".

func (*Document) StrokeColorCMYK

func (d *Document) StrokeColorCMYK(c, m, y, k float64)

StrokeColorCMYK mirrors Prawn::Document#stroke_color(c, m, y, k).

func (*Document) StrokeColorValue

func (d *Document) StrokeColorValue() string

func (*Document) StrokeEllipse

func (d *Document) StrokeEllipse(x, y, rx, ry float64)

StrokeEllipse mirrors Prawn::Document#stroke_ellipse([x, y], rx, ry).

func (*Document) StrokeLine

func (d *Document) StrokeLine(x1, y1, x2, y2 float64)

StrokeLine mirrors Prawn::Document#stroke_line([x1, y1], [x2, y2]).

func (*Document) StrokePolygon

func (d *Document) StrokePolygon(points ...[2]float64)

StrokePolygon mirrors Prawn::Document#stroke_polygon.

func (*Document) StrokeRectangle

func (d *Document) StrokeRectangle(x, y, w, h float64)

StrokeRectangle mirrors Prawn::Document#stroke_rectangle.

func (*Document) Table

func (d *Document) Table(data [][]string, o TableOptions) TableResult

Table mirrors Prawn::Document#table(data, options): draws a grid of string cells and advances the cursor past it. An empty data set is a no-op.

func (*Document) Text

func (d *Document) Text(s string, opts *TextOptions)

Text mirrors Prawn::Document#text: flowing, wrapping, auto-paginating text that starts at the cursor and advances it downward.

func (*Document) TextBox

func (d *Document) TextBox(s string, o TextBoxOptions) string

TextBox mirrors Prawn::Document#text_box: lays flowing text into a positioned rectangle and returns the portion that did not fit. It leaves the cursor unchanged.

func (*Document) TextInline

func (d *Document) TextInline(s string, opts *TextOptions)

TextInline mirrors Prawn::Document#text(string, inline_format: true): it parses <b>/<i>/<u> and <color rgb="…">/<font size="…"> tags into formatted fragments and renders them.

func (*Document) TransformationMatrix

func (d *Document) TransformationMatrix(a, b, c, e, f, g float64, block func())

TransformationMatrix mirrors Prawn::Document#transformation_matrix(a,b,c,d,e,f): concatenates the matrix onto the CTM. When block is non-nil it is wrapped in q/Q; when nil the caller manages the graphics state.

func (*Document) Translate

func (d *Document) Translate(x, y float64, block func())

Translate mirrors Prawn::Document#translate(x, y) { … }.

func (*Document) Transparency

func (d *Document) Transparency(fill, stroke float64, block func())

Transparency mirrors Prawn::Document#transparency(fill, stroke): sets the alpha for fill (and stroke) drawing within block via an ExtGState.

func (*Document) Undash

func (d *Document) Undash()

Undash mirrors Prawn::Document#undash: clears the dash pattern ("[] 0 d").

func (*Document) WidthOfString

func (d *Document) WidthOfString(s string) float64

WidthOfString measures a UTF-8 string at the current font and size, applying the document kerning flag (Prawn::Document#width_of).

type FormattedFragment

type FormattedFragment struct {
	Text   string
	Bold   bool
	Italic bool
	Size   float64 // 0 = document size
	Color  string  // "" = current fill color
	Font   string  // "" = current family
}

FormattedFragment is one styled run of a formatted-text array (prawn's { text:, styles:, size:, color:, font: } hash).

type Grid

type Grid struct {
	Columns int
	Rows    int
	Gutter  float64
	// contains filtered or unexported fields
}

Grid mirrors Prawn::Document#define_grid / #grid: a regular columns×rows grid with a uniform gutter, laid over the current bounding box.

func (*Grid) Box

func (g *Grid) Box(row, col int, block func())

Box runs block inside the bounding box of grid cell (row, col), 0-indexed from the top-left, mirroring Prawn::Document::Grid::GridBox.

func (*Grid) ColumnWidth

func (g *Grid) ColumnWidth() float64

ColumnWidth returns the width of a single grid column.

func (*Grid) RowHeight

func (g *Grid) RowHeight() float64

RowHeight returns the height of a single grid row.

type ImageOptions

type ImageOptions struct {
	AtX, AtY   float64
	AtSet      bool
	Width      float64
	Height     float64
	FitW, FitH float64
}

ImageOptions mirror the keyword arguments of Prawn::Document#image (:at, :width, :height, :fit).

type ImageResult

type ImageResult struct {
	Width, Height float64
}

ImageResult reports the placed geometry of an embedded image.

type OTFOptions

type OTFOptions struct {
	// Shape enables the complex-text shaper (github.com/go-opentype/shape) for
	// every run drawn with this font: GSUB substitution (ligatures, Arabic
	// joining forms, Indic reordering) and GPOS positioning (kerning, mark
	// attachment). With it off the run is the plain cmap glyph mapping, byte-for
	// -byte the same as the default Prawn text path.
	Shape bool
	// Script forces the shaping script tag ("arab", "deva", "latn", …). Empty
	// auto-detects from the text. Ignored when Shape is false.
	Script string
	// Vertical selects vertical (CJK tategaki) shaping. Ignored when Shape is
	// false.
	Vertical bool
	// Variation, when non-empty, instances a variable font at the given
	// user-space axis coordinates (keyed by axis tag, e.g. {"wght": 700}). Axes
	// absent from the map keep their default. An unknown axis tag is an error.
	Variation map[string]float64
}

OTFOptions mirror the per-font keyword arguments prawn accepts when a TrueType or OpenType file is registered through the go-opentype backend. The zero value selects the default, Prawn-compatible behaviour: no shaping (each rune maps straight through the cmap), no variation (the font's default master).

type Options

type Options struct {
	// PageSize names a standard page size ("LETTER", "LEGAL", "A4", …). Empty
	// means "LETTER". Ignored when PageWidth and PageHeight are both > 0.
	PageSize string
	// PageWidth and PageHeight give an explicit custom page size in points; when
	// both are > 0 they override PageSize (prawn's page_size: [w, h]).
	PageWidth, PageHeight float64
	// PageLayout is "portrait" (default) or "landscape".
	PageLayout string
	// Margin, when non-nil, sets all four margins to the same value in points.
	Margin *float64
	// Margins, when non-nil, sets the four margins explicitly as
	// [top, right, bottom, left] in points (prawn's margin: [t, r, b, l]).
	Margins *[4]float64
	// SkipPageCreation suppresses the initial page (prawn skip_page_creation).
	SkipPageCreation bool
	// CompressStreams enables FlateDecode on content streams (prawn compress).
	CompressStreams bool
}

Options mirror the keyword arguments of Prawn::Document.new (:page_size, :page_layout, :margin). A zero Options selects prawn's defaults: US Letter, portrait, 36pt (0.5in) margins on every side.

type Overflow

type Overflow int

Overflow mirrors prawn's text_box :overflow modes.

const (
	// OverflowTruncate stops at the box boundary, returning unprinted text.
	OverflowTruncate Overflow = iota
	// OverflowExpand draws every line even past the box height.
	OverflowExpand
	// OverflowError records ErrCannotFit if the text does not fit.
	OverflowError
)

type Style

type Style int

Style mirrors a prawn font style symbol (:normal, :bold, :italic, :bold_italic).

const (
	// StyleNormal is the upright roman style (prawn :normal).
	StyleNormal Style = iota
	// StyleBold is the bold style (prawn :bold).
	StyleBold
	// StyleItalic is the italic/oblique style (prawn :italic).
	StyleItalic
	// StyleBoldItalic is the combined bold + italic style (prawn :bold_italic).
	StyleBoldItalic
)

type TableOptions

type TableOptions struct {
	ColumnWidths []float64
	Header       bool
	CellPadding  float64
	BorderWidth  float64
	FontSize     float64
	RowHeight    float64
	AtX, AtY     float64
	AtSet        bool
}

TableOptions mirror the frequently used options of prawn-table's table method.

type TableResult

type TableResult struct {
	Width, Height float64
	ColumnWidths  []float64
	RowHeights    []float64
}

TableResult reports the geometry of a rendered table.

type TextBoxOptions

type TextBoxOptions struct {
	X, Y     float64
	Width    float64
	Height   float64
	Align    Align
	Overflow Overflow
	Size     float64
	Style    Style
	StyleSet bool
	Font     string
	Leading  float64
	Color    string
}

TextBoxOptions mirror the keyword arguments of Prawn::Document#text_box.

type TextOptions

type TextOptions struct {
	Size     float64
	Style    Style
	StyleSet bool
	Font     string
	Align    Align
	Leading  float64
	Color    string
	// Kerning, when KerningSet is true, overrides the document kerning flag.
	Kerning    bool
	KerningSet bool
}

TextOptions mirror the per-call keyword arguments of Prawn::Document#text / #draw_text (:size, :style, :align, :leading, :color, :kerning, and a per-call font family). Zero-value fields keep the document's current settings.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL