render

package module
v0.0.0-...-422bc7f Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-remarkable-render is a Go library for compositing reMarkable tablet background PDFs with vector .rm stroke layers to produce crisp, publication-quality PNG images.

What It Does

  • Layered page compositing: Merges stationery background PDFs with vector stylus handwriting and 24-bit Paper Pro color washes into standard PNG images.
  • Configurable resolution: Renders composited pages at any target DPI (default 200 DPI for screen, 300+ for print).
  • Planner date indexing: Reads the text of every page of an annual planner template and maps each calendar date (YYYY-MM-DD) to the 0-based indexes of its day and notes pages.
  • High-fidelity vector rasterization: Combines resvg-go and go-rmscene for physics-based stylus dynamics and painter's order layering.
  • Flexible document inputs: Accepts a *Document from OpenDocumentFromBytes for reuse across calls, raw byte slices, file paths, or readers.

How It Works

  • Loads the background PDF stationery and renders the requested page to a high-resolution bitmap.
  • Decodes the corresponding .rm binary stroke file into layered vector SVG paths.
  • Rasterizes the vector SVG layer at the exact pixel dimensions of the background bitmap.
  • Composites the semi-transparent ink over the background using alpha blending and encodes the result as PNG.

How it Really Works

  • The compositing pipeline evaluates highlighters and shader washes beneath pen ink in painter's order, ensuring opaque pen handwriting remains sharp over color fills.
  • PDFs are parsed, rendered, and read by PDFium compiled to WebAssembly and run in-process by the wazero runtime, and strokes are rasterized by resvg in WebAssembly the same way, so the library needs no cgo or system PDF libraries.
  • A *Document from OpenDocumentFromBytes stays parsed until you call the cleanup function returned with it, so many pages can be rendered or read without reloading the PDF. A path, byte slice, or reader is read fully into memory, opened, and released again on every call.
  • Open documents draw on a process-wide pool of at most four PDFium instances. Each open *Document, and each call given a path, byte slice, or reader, holds one instance until it is released; when all four are held, the next open waits up to 30 seconds and then returns an error.
  • RenderPlannerPage returns the PNG as a byte slice and writes nothing to disk.

Prerequisites

  • Go 1.26.2 or newer, the minimum Go version declared by the go line in go.mod.

Installation

go get github.com/alexgorbatchev/go-remarkable-render

Quick Start

package main

import (
	"os"

	render "github.com/alexgorbatchev/go-remarkable-render"
)

func main() {
	pdfBytes, err := os.ReadFile("template.pdf")
	if err != nil {
		panic(err)
	}

	rmBytes, err := os.ReadFile("page.rm")
	if err != nil {
		panic(err)
	}

	// Composite page 0 at 200 DPI
	pngBytes, err := render.RenderPlannerPage(pdfBytes, 0, rmBytes, 200)
	if err != nil {
		panic(err)
	}

	if err := os.WriteFile("rendered.png", pngBytes, 0644); err != nil {
		panic(err)
	}
}

API

Export Signature Description
RenderPlannerPage (pdfDocOrPath any, pageIdx int, rmBytes []byte, dpi int) ([]byte, error) Composites a page with strokes to PNG bytes. Empty strokes return the background alone. With strokes, unreadable, nonpositive or nonfinite PDF page dimensions return an error naming the page; no default viewport is substituted
IndexPlannerDates (pdfDocOrPath any, year int) (map[string]map[string]int, error) Maps valid calendar dates in year to 0-based page indexes in map["YYYY-MM-DD"]["day"|"notes"]. Uses the header rules below. Nonmatching pages are skipped. Duplicate date/view pairs return an error naming both pages; text extraction failures return an error naming the failing page. Both failures return no map. Zero or negative year returns ErrInvalidYear
OpenDocumentFromBytes (data []byte) (*Document, func(), error) Opens a PDF for reuse across calls; call the returned function to release it. Returns an error, and releases everything it acquired, when the PDF cannot be opened or its page count cannot be read
Document struct (unexported fields) An open PDF held by one PDFium instance until the cleanup function from OpenDocumentFromBytes is called. Pass it as pdfDocOrPath to reuse it; the library never closes it
Document.NumPage () int Returns the number of pages, read once when the document is opened
Document.Text (pageIdx int) (string, error) Returns the plain text of a 0-based page, or "" when the page has no text. Returns ErrPageOutOfBounds for an invalid index and an error when a PDFium request fails
Document.Links (pageIdx int) ([]PageLink, error) Returns the link annotations of a 0-based page in order. A link to a page of the document has its 0-based TargetPage and the URI #page=N (TargetPage+1). An external URI link has TargetPage -1 and the URI PDFium reports: the raw bytes of its /URI string, not validated as UTF-8. When the catalog has a /URI /Base and the /URI string contains no : or starts with one, the base is concatenated in front of it; this is string concatenation, not RFC 3986 resolution, so it can produce a malformed URL. Without a /Base, a relative URI is returned as written. Any other link (remote go-to, launch, named, or unresolvable destination) has TargetPage -1 and an empty URI, as does a URI action whose /URI string is empty in a document without a /Base. Each link also carries its Rect and the page Text inside it. A page without links returns an empty list; a failed PDFium request returns an error and no links
PageLink struct { Index, TargetPage int; URI string; Rect Rect; Text string } One link from Document.Links. Text is the page text PDFium reports inside Rect, in the page's text order, with every run of white space (including the line breaks PDFium inserts between text lines) replaced by one space and leading and trailing white space removed. A character whose box overlaps Rect counts in full even when only part of it is inside, while the rest of its word does not, so a rectangle that cuts through a word yields part of the word. Text is empty when the rectangle covers no text, such as a link over handwriting or an image
Rect struct { Left, Bottom, Right, Top float32 } A link annotation's /Rect in the page's default user space, as written in the PDF: points (1/72 inch unless the page sets /UserUnit), y growing upwards, without the page's /MediaBox or /CropBox origin or /Rotate applied; on a page whose media box starts at [0 0], (0, 0) is the bottom-left corner. Fields follow the PDF array order [Left Bottom Right Top] and are normalized so that Left <= Right and Bottom <= Top. A missing /Rect, or one that is not a four-element array, is the zero Rect
DefaultDPI const int = 200 Standard default rendering resolution in dots per inch
ErrInvalidDocument error Wrapped in the error RenderPlannerPage and IndexPlannerDates return when pdfDocOrPath is nil, a nil *Document, or a type other than *Document, string, []byte, or io.Reader; match it with errors.Is
ErrInvalidYear error Returned by IndexPlannerDates when year is zero or negative
ErrPageOutOfBounds error Wrapped in the error RenderPlannerPage, Document.Text, and Document.Links return for a page index below 0 or at or above NumPage(); match it with errors.Is

Configuration

Date indexing reads the first nonempty text line, beginning with an English month abbreviation (Jan to Dec) and a day number. It requires a full weekday name and the word Notes (the day view) or Day (the notes view); Notes takes precedence, including in holiday names. For templates whose first line contains weekday navigation pairs such as Oct 1 Fri 2 Mon 5, the immediately following line also belongs to the header if it starts with a full weekday. Other body lines are ignored. Month and day must form a valid date in the supplied year. Printed years and weekday/date agreement are not checked.

Option Type Default Description
dpi int 200 Resolution for rasterizing background and vector layers; zero or a negative value uses DefaultDPI
pdfDocOrPath any required Accepts a *Document from OpenDocumentFromBytes, a string file path, a []byte PDF, or an io.Reader; anything else returns ErrInvalidDocument

License

MIT License (c) 2026 Alex Gorbatchev

Documentation

Index

Constants

View Source
const (
	// DefaultDPI is the standard rasterization density (200 DPI).
	DefaultDPI = 200
)

Variables

View Source
var (
	// ErrInvalidDocument indicates an unsupported document parameter type or nil document.
	ErrInvalidDocument = errors.New("unsupported pdfDocOrPath: expected *Document, string (file path), []byte, or io.Reader")

	// ErrInvalidYear indicates a non-positive year was provided.
	ErrInvalidYear = errors.New("year must be positive")

	// ErrPageOutOfBounds indicates a requested page index exceeds document bounds.
	ErrPageOutOfBounds = errors.New("page index out of bounds")
)

Functions

func IndexPlannerDates

func IndexPlannerDates(pdfDocOrPath any, year int) (map[string]map[string]int, error)

IndexPlannerDates scans the pages of a reMarkable planner template PDF and indexes dates matching "Month Day Weekday Notes/Day" into a nested mapping: map[YYYY-MM-DD]map[day|notes]pageIdx.

Accepts *Document, string (file path), []byte, or io.Reader. For each matching date: - A page containing "Notes" in its header represents the "day" view (pointing to its notes companion). - A page containing "Day" in its header represents the "notes" view (pointing back to its day companion).

The header is the first nonempty text line. When that line starts with a month and day followed only by abbreviated weekday/day navigation pairs, the next line also belongs to the header if it starts with a full weekday. Dates must be valid in year; printed years and weekday/date agreement are not checked. Notes takes precedence over Day, including holiday names. Duplicate views return an error naming both page indexes and no index. A page whose text carries no valid header is skipped. A failed PDFium text request for any page, including one that returns no response or one made on a released *Document, returns an error naming the 0-based page index and no index.

func RenderPlannerPage

func RenderPlannerPage(pdfDocOrPath any, pageIdx int, rmBytes []byte, dpi int) ([]byte, error)

RenderPlannerPage renders a specific background PDF page at the target DPI. If rmBytes is provided (non-empty), it converts the .rm stroke data to SVG using rmscene.RenderRMToSVG, rasterizes the SVG to exact page pixel dimensions with resvg-go, and composites the stroke layer over the PDF background using image/draw. Returns the final composited image as encoded PNG bytes. With strokes, unreadable, nonpositive or nonfinite PDF page dimensions return an error instead of substituting a default SVG viewport.

Accepts *Document, string (file path), []byte, or io.Reader for pdfDocOrPath.

Types

type Document

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

Document wraps an open PDFium document instance.

func OpenDocumentFromBytes

func OpenDocumentFromBytes(data []byte) (*Document, func(), error)

OpenDocumentFromBytes opens a PDF document from raw byte slice using PDFium WebAssembly. Call the returned cleanup function to release the document. A failure to open the document or to read its page count returns an error and releases everything acquired.

func (d *Document) Links(pageIdx int) ([]PageLink, error)

Links extracts internal link targets and external hyperlinks from a page, with each link's rectangle and the page text inside it. A page without links yields an empty list and a nil error. Any failed PDFium request returns an error and no links.

func (*Document) NumPage

func (d *Document) NumPage() int

NumPage returns the total page count of the document.

func (*Document) Text

func (d *Document) Text(pageIdx int) (string, error)

Text extracts the plain text content of a page. A page without text yields an empty string and a nil error. A failed PDFium request, including one that returns no response, returns an error.

type PageLink struct {
	// Index is the 0-based position of the link among the page's links.
	Index int

	// TargetPage is the 0-based page of this document the link leads to, or
	// -1 when it leads to no page of this document.
	TargetPage int

	// URI is "#page=N" (TargetPage+1) for a link to a page of this document.
	// For a URI action it is the URI PDFium reports: the raw bytes of the
	// /URI string, not validated as UTF-8. When the document catalog has a
	// /URI /Base and the /URI string contains no ':' or starts with one,
	// PDFium concatenates the base in front of it. That is plain string
	// concatenation, not RFC 3986 reference resolution, so it can produce a
	// malformed URL (base "https://a/b.html" and "c.html" yield
	// "https://a/b.htmlc.html"), and a URI with ':' after its first byte is
	// never prefixed. Without a /Base, a relative URI is returned as written.
	// URI is empty for a URI action whose /URI string is empty in a document
	// without a /Base, and for any other link, such as a remote go-to,
	// launch, or named action, or a link whose destination does not resolve.
	URI string

	// Rect is the link annotation's /Rect, the area that activates the link.
	// PDFium reports a missing /Rect, or one that is not a four-element
	// array, as the zero Rect.
	Rect Rect

	// Text is the page text PDFium reports inside Rect, in the page's text
	// order, with every run of white space (unicode.IsSpace, including the
	// "\r\n" PDFium inserts between text lines) replaced by one space and
	// leading and trailing white space removed. PDFium includes every
	// character whose box overlaps Rect with a non-zero area, so a character
	// partly inside Rect counts in full while the rest of its word does not.
	// Text is empty when Rect covers no text, such as a link drawn over
	// handwriting or an image.
	Text string
}

PageLink represents a resolved link annotation on a page.

type Rect

type Rect struct {
	Left   float32
	Bottom float32
	Right  float32
	Top    float32
}

Rect is a rectangle in the page's default user space, as written in the PDF: units are points (1/72 inch unless the page sets /UserUnit), y grows upwards, and the page's /MediaBox or /CropBox origin and /Rotate are not applied. On a page whose media box starts at [0 0], (0, 0) is the bottom-left corner. The fields follow the order of a PDF rectangle array, [Left Bottom Right Top], and are normalized so that Left <= Right and Bottom <= Top whichever pair of opposite corners the PDF lists.

Jump to

Keyboard shortcuts

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