pdfrenderer

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 5, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractAnchorPositions

func ExtractAnchorPositions(ctx context.Context, pdfPath string, anchors []string) (map[string]AnchorPosition, error)

ExtractAnchorPositions finds anchor texts in PDF and returns their positions. Uses the Go dslipak/pdf library first; falls back to pdftotext for Typst PDFs that cause the Go library to panic or fail.

Types

type AnchorPosition

type AnchorPosition struct {
	Page       int
	X          float64 // points, left to right
	Y          float64 // points, bottom to top (PDF standard)
	Width      float64 // points (anchor text width)
	PageWidth  float64 // points
	PageHeight float64 // points
}

AnchorPosition represents coordinates of anchor text in PDF.

type ConverterFactory

type ConverterFactory func(
	injectables map[string]any,
	injectableDefaults map[string]string,
	signerRoleValues map[string]port.SignerRoleValue,
	signerRoles []portabledoc.SignerRole,
	fieldResponses map[string]json.RawMessage,
) TypstConverter

ConverterFactory creates a TypstConverter for a given render request. This allows each render call to have its own converter state (page tracking, images, etc.).

func NewTypstConverterFactory

func NewTypstConverterFactory(tokens TypstDesignTokens) ConverterFactory

NewTypstConverterFactory returns a ConverterFactory that creates real Typst converters.

type ImageCache

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

ImageCache provides a shared disk-based cache for downloaded images. Files are keyed by SHA-256 of the URL and cleaned up periodically by age.

func NewImageCache

func NewImageCache(opts ImageCacheOptions) (*ImageCache, error)

NewImageCache creates and starts an image cache with periodic cleanup. If dir is empty, a temp directory is created.

func (*ImageCache) Close

func (ic *ImageCache) Close()

Close stops the cleanup goroutine.

func (*ImageCache) Dir

func (ic *ImageCache) Dir() string

Dir returns the cache directory path for use as Typst --root.

func (*ImageCache) Lookup

func (ic *ImageCache) Lookup(url string) (string, bool)

Lookup checks if an image for the given URL exists in cache. Returns the file path and true if found, or empty string and false if not.

func (*ImageCache) ResolveImages

func (ic *ImageCache) ResolveImages(ctx context.Context, images map[string]string, httpClient *http.Client) map[string]string

ResolveImages downloads images that are not cached, stores them, and returns a map of typst placeholder filenames to actual filenames in the cache dir.

func (*ImageCache) Store

func (ic *ImageCache) Store(url string, ext string, data []byte) (string, error)

Store saves image data to the cache, returning the stored file path.

type ImageCacheOptions

type ImageCacheOptions struct {
	Dir             string
	MaxAge          time.Duration
	CleanupInterval time.Duration
}

ImageCacheOptions configures the image cache.

type Service

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

Service implements the PDFRenderer interface using Typst.

func NewService

func NewService(opts TypstOptions, imageCache *ImageCache, factory ConverterFactory, tokens TypstDesignTokens, storageAdapter port.StorageAdapter) (*Service, error)

NewService creates a new Typst-based PDF renderer service. storageAdapter is optional (may be nil); when provided, storage:// image URLs in documents are resolved directly from storage rather than failing during PDF rendering.

func (*Service) Close

func (s *Service) Close() error

Close releases resources held by the service.

func (*Service) RenderPreview

RenderPreview generates a preview PDF with injected values.

type TypstBuilder

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

TypstBuilder constructs complete Typst documents from portable documents. It generates the document preamble (page setup, fonts, heading styles) and delegates node-by-node conversion to a TypstConverter.

func NewTypstBuilder

func NewTypstBuilder(converter TypstConverter, tokens TypstDesignTokens) *TypstBuilder

NewTypstBuilder creates a new Typst builder with the given converter and design tokens.

func (*TypstBuilder) Build

Build creates a complete Typst document from a portable document. Returns the Typst source, page count, and signature fields.

func (*TypstBuilder) RemoteImages

func (b *TypstBuilder) RemoteImages() map[string]string

RemoteImages returns the map of remote image URLs to local filenames collected during build by the converter.

type TypstConverter

type TypstConverter interface {
	// ConvertNodes converts a slice of portable document nodes to Typst markup.
	// Returns the Typst source string and any signature fields found during conversion.
	ConvertNodes(nodes []portabledoc.Node) (string, []port.SignatureField)

	// GetCurrentPage returns the current page number (1-indexed).
	// This accounts for page breaks encountered during conversion.
	GetCurrentPage() int

	// RemoteImages returns a map of remote image URLs to their placeholder filenames
	// used in the generated Typst source. These images need to be resolved (downloaded
	// or served from cache) before the Typst source can be compiled.
	RemoteImages() map[string]string

	// SetContentWidthPx sets the page content area width in pixels.
	// Used for computing proportional table column widths.
	SetContentWidthPx(width float64)

	// SetPageWidthPx sets the full page width in pixels (including margins).
	// Used for computing signature field width as a percentage of full page.
	SetPageWidthPx(width float64)

	// RegisterRemoteImage registers a URL or data URI for deferred download and
	// returns the local filename to reference in the Typst source.
	RegisterRemoteImage(url string) string

	// ResolveImageSource resolves the final image source after injectable substitution.
	ResolveImageSource(attrs map[string]any) string
}

TypstConverter defines the interface for converting portable document nodes to Typst markup.

type TypstDesignTokens

type TypstDesignTokens struct {
	// Base typography
	FontStack        []string // Default font family chain
	BaseFontSize     string   // Base font size (e.g., "12pt")
	BaseTextColor    string   // Default text color hex (e.g., "#333333")
	ParagraphLeading string   // Line spacing within paragraphs (e.g., "0.50em")
	ParagraphSpacing string   // Spacing between paragraphs (e.g., "1.5em")

	// Heading styles (level 1-6)
	HeadingSizes  [6]string // Font sizes per heading level
	HeadingWeight string    // Font weight for all headings

	// Block elements
	BlockquoteFill        string // Blockquote background color
	BlockquoteStrokeColor string // Blockquote left border color
	HRStrokeColor         string // Horizontal rule color
	HighlightDefaultColor string // Default highlight/marker color

	// Table defaults
	TableStrokeColor       string // Table border color
	TableHeaderFillDefault string // Default table header background
	TableCellInset         string // Cell padding (e.g., "(x: 6pt, y: 12pt)") - fallback for editable tables
	TableHeaderCellInset   string // Header cell padding for injector tables (e.g., "(x: 8pt, y: 12pt)")
	TableBodyCellInset     string // Body cell padding for injector tables (e.g., "(x: 8pt, y: 10pt)")

	// Placeholder styling (missing injectable)
	PlaceholderFillBg    string // Placeholder block background
	PlaceholderStroke    string // Placeholder block border color
	PlaceholderTextColor string // Placeholder text color
}

TypstDesignTokens holds all configurable design values for Typst output.

func DefaultDesignTokens

func DefaultDesignTokens() TypstDesignTokens

DefaultDesignTokens returns the built-in design tokens matching the current rendering output.

type TypstOptions

type TypstOptions struct {
	// BinPath is the path to the typst binary (default: "typst").
	BinPath string

	// Timeout is the maximum time to wait for PDF compilation.
	Timeout time.Duration

	// FontDirs are additional directories to search for fonts.
	FontDirs []string

	// MaxConcurrent limits simultaneous typst processes (0 = unlimited).
	MaxConcurrent int

	// AcquireTimeout is the max wait time to acquire a render slot.
	AcquireTimeout time.Duration
}

TypstOptions configures the Typst renderer.

func DefaultTypstOptions

func DefaultTypstOptions() TypstOptions

DefaultTypstOptions returns sensible default options.

type TypstRenderer

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

TypstRenderer handles PDF generation using the Typst CLI.

func NewTypstRenderer

func NewTypstRenderer(opts TypstOptions) (*TypstRenderer, error)

NewTypstRenderer creates a new Typst-based PDF renderer.

func (*TypstRenderer) Close

func (r *TypstRenderer) Close() error

Close is a no-op for Typst (no persistent processes to clean up).

func (*TypstRenderer) GeneratePDF

func (r *TypstRenderer) GeneratePDF(ctx context.Context, typstSource string, rootDir string) ([]byte, error)

GeneratePDF compiles Typst source to PDF bytes. rootDir is optional; if set, it is passed as --root to typst for resolving local file paths.

Jump to

Keyboard shortcuts

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