renderer

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package renderer is the Go port of the pptx-glimpse-renderer package (SVG/PNG rendering, fonts, the intermediate model, and unit helpers). Ported 1:1 from the upstream TypeScript project, hirokisakabe/pptx-glimpse. JS Math.round(x) == int(math.Floor(x+0.5)); ${n} number stringify == an _n helper.

Index

Constants

View Source
const (
	EMUPerInch  = 914400.0 // 1 inch = 914,400 EMU
	EMUPerPoint = 12700.0  // 1 pt = 12,700 EMU
	DefaultDPI  = 96.0

	DefaultOutputWidth = 960

	// RotationUnit: rotation angle unit = 1/60,000 degree (ECMA-376 §20.1.10.3).
	RotationUnit = 60000.0
)

OOXML units (ECMA-376 §20.1.2.1). EMU (English Metric Units) is the OOXML internal coordinate unit; a 16:9 slide = 9,144,000 × 5,143,500 EMU = 960 × 540 px at 96 DPI.

Variables

View Source
var CollectFontFilePaths = func(additionalDirs []string, skipSystemFonts bool) []string {
	dirs := additionalDirs
	if dirs == nil {
		dirs = []string{}
	}
	dirsKey := strings.Join(dirs, "\x00")

	if sflCache != nil && sflCache.dirsKey == dirsKey && sflCache.skip == skipSystemFonts {
		return sflCache.paths
	}

	var allDirs []string
	if skipSystemFonts {
		allDirs = dirs
	} else {
		allDirs = append(append([]string{}, systemFontDirs()...), dirs...)
	}

	result := []string{}
	for _, dir := range allDirs {
		sflWalk(dir, &result)
	}

	sflCache = &sflCacheEntry{paths: result, dirsKey: dirsKey, skip: skipSystemFonts}
	return result
}

CollectFontFilePaths collects .ttf/.otf (and selected CJK .ttc) paths from the OS system font dirs plus additionalDirs. When skipSystemFonts is true, only additionalDirs are scanned. Results are cached at module scope; a call with the same (dirs, skipSystemFonts) returns instantly.

Exposed as an overridable package var so opentype-helpers' tests can substitute a fixed path list (mirrors the JS vi.spyOn on this function).

View Source
var DefaultFontMapping = FontMapping{

	"Calibri":         "Carlito",
	"Calibri Light":   "Carlito",
	"Arial":           "Arimo",
	"Times New Roman": "Tinos",
	"Courier New":     "Cousine",
	"Cambria":         "Caladea",

	"メイリオ":       "Noto Sans JP",
	"Meiryo":     "Noto Sans JP",
	"游ゴシック":      "Noto Sans JP",
	"Yu Gothic":  "Noto Sans JP",
	"MS ゴシック":    "Noto Sans JP",
	"MS Gothic":  "Noto Sans JP",
	"MS Pゴシック":   "Noto Sans JP",
	"MS PGothic": "Noto Sans JP",

	"MS 明朝":      "Noto Serif CJK JP",
	"MS Mincho":  "Noto Serif CJK JP",
	"MS P明朝":     "Noto Serif CJK JP",
	"MS PMincho": "Noto Serif CJK JP",
	"游明朝":        "Noto Serif CJK JP",
	"Yu Mincho":  "Noto Serif CJK JP",
}

DefaultFontMapping is the default font mapping table.

Functions

func BuildFontFaceStyle

func BuildFontFaceStyle(usages map[string]*FontUsage, fontResolver TextPathFontResolver) string

BuildFontFaceStyle subsets each used font and returns a <style> element of @font-face definitions, or "" when no font can be embedded.

func BuildFontFamilyValue

func BuildFontFamilyValue(fonts []*string) (string, bool)

BuildFontFamilyValue builds the SVG font-family list (+ mapped/fallback fonts + generic). Returns ("", false) when no fonts resolve (JS null).

func BuildTransformAttr

func BuildTransformAttr(t Transform) string

BuildTransformAttr builds the SVG transform attribute for a shape transform.

func ClearFontCache

func ClearFontCache()

ClearFontCache resets the system-font setup cache.

func Debug

func Debug(feature, message string, context ...string)

Debug records a debug-level note (only at debug level).

func EmuToPixels

func EmuToPixels(emu Emu, dpi ...float64) float64

EmuToPixels converts EMU to pixels at the given DPI (default DefaultDPI, mirroring the JS default arg).

func EmuToPoints

func EmuToPoints(emu Emu) float64

func ExtractTtcFonts

func ExtractTtcFonts(data []byte) [][]byte

ExtractTtcFonts re-packs each embedded font's OffsetTable + table data into an independent TTF/OTF buffer. Returns nil when data is not a TTC or parsing fails; individual font failures are skipped.

func FormatAutoNum

func FormatAutoNum(scheme AutoNumScheme, index int) string

FormatAutoNum formats an auto-numbered bullet index per the scheme.

func GetAscenderRatio

func GetAscenderRatio(fontFamily, fontFamilyEa string) float64

GetAscenderRatio returns ascender / unitsPerEm, or 1.0 when no metrics are found.

func GetCjkFallbackFonts

func GetCjkFallbackFonts(mappedFontName string) []string

GetCjkFallbackFonts returns the OS-specific CJK fallback chain for a mapped font name, or an empty slice when none is defined.

func GetLineHeightRatio

func GetLineHeightRatio(fontFamily, fontFamilyEa string) float64

GetLineHeightRatio returns the natural line-height ratio (ascender + |descender|) / unitsPerEm, or 1.2 when no metrics are found.

func GetMappedFont

func GetMappedFont(fontFamily string, mapping FontMapping) (string, bool)

GetMappedFont looks up the OSS substitute font name, case-insensitively. Returns (name, true) on a hit, ("", false) when no mapping applies (JS null).

func GetMetricsFallbackFont

func GetMetricsFallbackFont(fontFamily string) string

func GetPresetGeometrySvg

func GetPresetGeometrySvg(preset string, width, height float64, adjustValues map[string]float64) string

GetPresetGeometrySvg returns the SVG element for a preset shape, falling back to a rect.

func InitWarningLogger

func InitWarningLogger(level LogLevel)

InitWarningLogger sets the log level and clears recorded state.

func IsCjkCodePoint

func IsCjkCodePoint(cp rune) bool

IsCjkCodePoint reports whether a code point is CJK (per the Unicode ranges used upstream).

func IsTtcBuffer

func IsTtcBuffer(data []byte) bool

IsTtcBuffer reports whether data is a TTC: the first 4 bytes are "ttcf".

func MeasureTextWidth

func MeasureTextWidth(text string, fontSizePt float64, bold bool, fontFamily, fontFamilyEa string) float64

MeasureTextWidth estimates the rendered width of text in pixels. When fontFamily resolves to known metrics it is metrics-based; otherwise it falls back to the per-category heuristic.

func NumberToString

func NumberToString(x float64) string

NumberToString renders a float64 the way JS `${number}` does (integers without a fraction), for the SVG-path/geometry consumers in other packages.

func RenderSlideToSvg

func RenderSlideToSvg(slide Slide, slideSize SlideSize) string

RenderSlideToSvg renders a parsed Slide to a complete SVG document string.

func RenderTextBody

func RenderTextBody(textBody TextBody, transform Transform) string

RenderTextBody renders a text body to an SVG <text> (or vertical <g>) fragment.

func ResetFontMapping

func ResetFontMapping()

ResetFontMapping restores the default mapping.

func ResetFontUsageCollector

func ResetFontUsageCollector()

ResetFontUsageCollector clears the installed collector.

func ResetScriptFonts

func ResetScriptFonts()

ResetScriptFonts clears the Jpan fonts.

func ResetTextMeasurer

func ResetTextMeasurer()

ResetTextMeasurer restores the default measurer.

func ResetTextPathFontResolver

func ResetTextPathFontResolver()

ResetTextPathFontResolver clears the resolver (back to tspan rendering).

func RotationToDegrees

func RotationToDegrees(rotation float64) float64

RotationToDegrees converts 1/60,000-degree units to degrees.

func SetFontMapping

func SetFontMapping(m FontMapping)

SetFontMapping installs a font-mapping table for rendering.

func SetFontUsageCollector

func SetFontUsageCollector(c *FontUsageCollector)

SetFontUsageCollector installs a collector for rendering.

func SetScriptFonts

func SetScriptFonts(majorJpan, minorJpan *string)

SetScriptFonts sets the theme Jpan major/minor fonts.

func SetTextMeasurer

func SetTextMeasurer(m TextMeasurer)

SetTextMeasurer installs a custom measurer.

func SetTextPathFontResolver

func SetTextPathFontResolver(resolver TextPathFontResolver)

SetTextPathFontResolver installs a resolver, switching rendering to glyph-path mode.

func SetWarnOutput

func SetWarnOutput(w io.Writer) func()

SetWarnOutput redirects console output (test seam mirroring a spy on console.warn). Returns a restore func that reinstates the previous writer.

func SubsetFont

func SubsetFont(font OpentypeFullFont, chars map[string]bool, familyName string) []byte

SubsetFont subsets font to only the glyphs covering chars and returns an sfnt, or nil. Characters not in the font (.notdef, glyph index 0) are excluded so the browser falls back to the next font. Returns nil for empty input, no covered characters, or a non-subsettable font.

func Uint8ArrayToBase64

func Uint8ArrayToBase64(data []byte) string

Uint8ArrayToBase64 — port of utils/base64.ts. (The upstream base64.test.ts is empty.)

func Warn

func Warn(feature, message string, context ...string)

Warn records an unsupported-feature warning at warn/debug levels.

Types

type ArrowEndpoint

type ArrowEndpoint struct {
	Type   string
	Width  string
	Length string
}

Line/outline model — port of model/line.ts. String unions (ArrowType/ArrowSize/DashStyle/ LineCap/LineJoin) are plain strings.

type AutoNumScheme

type AutoNumScheme = string

AutoNumScheme is an auto-numbered bullet scheme (a string union upstream).

type Background

type Background struct {
	Fill *Fill
}

Background is a slide background fill (port of model Background).

type BiLevelEffect

type BiLevelEffect struct {
	Threshold float64
}

Blip (picture) effects — port of model/effect.ts. BlipEffects fields are pointers (nullable).

type BlipEffectRenderResult

type BlipEffectRenderResult struct {
	FilterAttr string
	FilterDefs string
}

BlipEffectRenderResult holds the filter attribute + the <filter> defs for a picture's blip effects.

func RenderBlipEffects

func RenderBlipEffects(blipEffects *BlipEffects) BlipEffectRenderResult

RenderBlipEffects builds the SVG filter for a blip-effect list (or empty for nil / no effects).

type BlipEffects

type BlipEffects struct {
	Grayscale bool
	BiLevel   *BiLevelEffect
	Blur      *BlurEffect
	Lum       *LumEffect
	Duotone   *DuotoneEffect
	ClrChange *ClrChangeEffect
}

type BlurEffect

type BlurEffect struct {
	Radius Emu
	Grow   bool
}

type BodyProperties

type BodyProperties struct {
	Anchor         string
	MarginLeft     Emu
	MarginRight    Emu
	MarginTop      Emu
	MarginBottom   Emu
	Wrap           string
	AutoFit        string
	FontScale      float64
	LnSpcReduction float64
	NumCol         int
	Vert           string
}

BodyProperties — port of model/text.ts BodyProperties (not read by the ported code; minimal).

type BulletType

type BulletType struct {
	Type    string        // "none" | "char" | "autoNum"
	Char    string        // for "char"
	Scheme  AutoNumScheme // for "autoNum"
	StartAt float64       // for "autoNum"
}

BulletType is the {type:"none"} | {type:"char",char} | {type:"autoNum",scheme,startAt} union.

type CellBorders

type CellBorders struct {
	Top    *Outline
	Bottom *Outline
	Left   *Outline
	Right  *Outline
}

CellBorders holds a cell's four edge outlines (nil == none).

type ChartData

type ChartData struct {
	ChartType     ChartType
	Title         *string // string | null
	Series        []ChartSeries
	Categories    []string
	BarDirection  *string
	HoleSize      *float64
	RadarStyle    *string
	OfPieType     *string
	SecondPieSize *float64
	SplitPos      *float64
	Legend        *ChartLegend // null
}

type ChartElement

type ChartElement struct {
	Type      string // "chart"
	Transform Transform
	Chart     ChartData
}

ChartElement is a chart shape on a slide (port of model/chart.ts ChartElement).

type ChartLegend

type ChartLegend struct {
	Position string // "b"|"t"|"l"|"r"|"tr"
}

type ChartSeries

type ChartSeries struct {
	Name        *string // string | null
	Values      []float64
	XValues     []float64 // nil == undefined
	BubbleSizes []float64 // nil == undefined
	Color       ResolvedColor
}

type ChartType

type ChartType = string

Chart model — port of model/chart.ts. ChartType is a string union; optional fields are pointers.

type ClrChangeEffect

type ClrChangeEffect struct {
	ClrFrom ResolvedColor
	ClrTo   ResolvedColor
}

type ColorMap

type ColorMap = map[string]string

ColorMap maps slide color-map names (bg1, tx1, bg2, tx2, accent1..6, hlink, folHlink) to ColorScheme keys — port of model/theme.ts ColorMap.

type ColorScheme

type ColorScheme = map[string]string

ColorScheme maps theme color keys (dk1, lt1, dk2, lt2, accent1..6, hlink, folHlink) to hex strings — port of model/theme.ts ColorScheme. Modeled as a map because the color resolver indexes and tests membership dynamically.

type ColorSchemeKey

type ColorSchemeKey = string

ColorSchemeKey is a key into a ColorScheme.

type ConnectorElement

type ConnectorElement struct {
	Type      string // "connector"
	Transform Transform
	Geometry  *Geometry
	Outline   *Outline
	Effects   *EffectList
}

ConnectorElement — port of model/shape.ts ConnectorElement (line/connector shapes).

type CustomGeometryPath

type CustomGeometryPath struct {
	Width    float64
	Height   float64
	Commands string
}

CustomGeometryPath — port of model/shape.ts CustomGeometryPath.

type DefaultParagraphLevelProperties

type DefaultParagraphLevelProperties struct {
	Alignment            *string
	MarginLeft           *Emu
	Indent               *Emu
	Bullet               *BulletType
	BulletFont           *string
	BulletColor          *ResolvedColor
	BulletSizePct        *float64
	DefaultRunProperties *DefaultRunProperties
}

DefaultParagraphLevelProperties is a default paragraph level's properties.

type DefaultRunProperties

type DefaultRunProperties struct {
	FontSize      *float64 // Pt
	FontFamily    *string
	FontFamilyEa  *string
	FontFamilyCs  *string
	Bold          *bool
	Italic        *bool
	Underline     *bool
	Strikethrough *bool
	Color         *ResolvedColor
}

DefaultRunProperties is defRPr-derived run formatting.

type DefaultTextMeasurer

type DefaultTextMeasurer struct{}

DefaultTextMeasurer uses the static font metrics.

func (DefaultTextMeasurer) GetAscenderRatio

func (DefaultTextMeasurer) GetAscenderRatio(fontFamily, fontFamilyEa string) float64

func (DefaultTextMeasurer) GetLineHeightRatio

func (DefaultTextMeasurer) GetLineHeightRatio(fontFamily, fontFamilyEa string) float64

func (DefaultTextMeasurer) MeasureTextWidth

func (DefaultTextMeasurer) MeasureTextWidth(text string, fontSizePt float64, bold bool, fontFamily, fontFamilyEa string) float64

type DefaultTextPathFontResolver

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

DefaultTextPathFontResolver resolves by exact name → font mapping → CJK fallback chain.

func NewDefaultTextPathFontResolver

func NewDefaultTextPathFontResolver(fonts map[string]OpentypeFullFont, defaultFont OpentypeFullFont) *DefaultTextPathFontResolver

NewDefaultTextPathFontResolver builds a resolver over the given font table + optional default font.

type DefaultTextStyle

type DefaultTextStyle struct {
	DefaultParagraph *DefaultParagraphLevelProperties
	Levels           []*DefaultParagraphLevelProperties
}

DefaultTextStyle is defPPr + lvl1pPr..lvl9pPr (index 0 == lvl1pPr).

type DuotoneEffect

type DuotoneEffect struct {
	Color1 ResolvedColor
	Color2 ResolvedColor
}

type EffectList

type EffectList struct {
	OuterShadow *OuterShadow
	InnerShadow *InnerShadow
	Glow        *Glow
	SoftEdge    *SoftEdge
}

type EffectRenderResult

type EffectRenderResult struct {
	FilterAttr string
	FilterDefs string
}

EffectRenderResult holds the filter attribute + the <filter> defs for a shape's effects.

func RenderEffects

func RenderEffects(effects *EffectList) EffectRenderResult

RenderEffects builds the SVG filter for an effect list (or empty for nil / no effects).

type EmbeddedFont

type EmbeddedFont struct {
	Typeface    string
	Panose      *string
	PitchFamily *float64
	Charset     *float64
}

type Emu

type Emu = float64

Branded OOXML unit types — port of utils/unit-types.ts. The TypeScript upstream uses compile-time branded types to prevent unit confusion; Go has no branded numerics, so these are plain float64 aliases and the As* constructors are identity passthroughs (kept for parity with the upstream API).

func AsEmu

func AsEmu(v float64) Emu

func ComputeSpAutofitHeight

func ComputeSpAutofitHeight(textBody TextBody, transform Transform) (Emu, bool)

ComputeSpAutofitHeight returns the EMU height the shape needs to fit its text, or (0,false) when the text already fits (JS null).

type Fill

type Fill struct {
	Type string // "none"|"solid"|"gradient"|"image"|"pattern"
	// solid
	Color *ResolvedColor
	// gradient
	Stops        []GradientStop
	Angle        float64
	GradientType string // "linear"|"radial"
	CenterX      *float64
	CenterY      *float64
	// image
	ImageData string
	MimeType  string
	Tile      *ImageFillTile
	// pattern
	Preset          string
	ForegroundColor *ResolvedColor
	BackgroundColor *ResolvedColor
}

type FillAttrs

type FillAttrs struct {
	Attrs string
	Defs  string
}

FillAttrs holds an SVG attribute string plus any <defs> content the fill needs.

func RenderFillAttrs

func RenderFillAttrs(fill *Fill) FillAttrs

RenderFillAttrs converts a Fill model into SVG fill="" attributes (+ defs).

func RenderOutlineAttrs

func RenderOutlineAttrs(outline *Outline) FillAttrs

RenderOutlineAttrs converts an Outline model into SVG stroke="" attributes (+ defs).

type FontBuffer

type FontBuffer struct {
	Name string // "" == no name
	Data []byte
}

FontBuffer is a caller-supplied font: optional Name (registration key for plain TTF/OTF; ignored for TTC, which uses the font's internal name-table families) + raw bytes.

type FontMapping

type FontMapping = map[string]string

FontMapping maps a PPTX font name to an OSS substitute font name.

func CreateFontMapping

func CreateFontMapping(userMapping ...FontMapping) FontMapping

CreateFontMapping merges the default mapping with an optional user mapping (user wins). Always returns a fresh copy so the default table is never mutated.

type FontMetrics

type FontMetrics struct {
	UnitsPerEm   float64
	Ascender     float64
	Descender    float64
	DefaultWidth float64
	CJKWidth     float64
	Widths       map[rune]float64
}

func GetFontMetrics

func GetFontMetrics(fontFamily string) *FontMetrics

type FontScheme

type FontScheme struct {
	MajorFont     string
	MinorFont     string
	MajorFontEa   string
	MinorFontEa   string
	MajorFontCs   string
	MinorFontCs   string
	MajorFontJpan string
	MinorFontJpan string
}

FontScheme is the theme font scheme — port of model/theme.ts. "" == null for the nullable fields.

type FontUsage

type FontUsage struct {
	Fonts []*string
	Chars map[rune]bool
	Order int // first-encountered index, so @font-face emits in JS Map insertion order (not sorted)
}

FontUsage records the resolveFont priority list + the set of characters drawn with it.

type FontUsageCollector

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

FontUsageCollector accumulates font usage keyed by the primary (first non-null) font name.

func NewFontUsageCollector

func NewFontUsageCollector() *FontUsageCollector

NewFontUsageCollector creates an empty collector.

func (*FontUsageCollector) GetUsages

func (c *FontUsageCollector) GetUsages() map[string]*FontUsage

GetUsages returns the accumulated font→usage map.

func (*FontUsageCollector) Reset

func (c *FontUsageCollector) Reset()

Reset clears the collector.

type FormatScheme

type FormatScheme struct {
	FillStyles   []Fill
	LnStyles     []Outline
	EffectStyles []*EffectList // (EffectList | null)[]
	BgFillStyles []Fill
}

FormatScheme is the theme fmtScheme — port of model/theme.ts.

type Geometry

type Geometry struct {
	Type         string // "preset" | "custom"
	Preset       string
	AdjustValues map[string]float64
	Paths        []CustomGeometryPath // for "custom"
}

Geometry — port of model/shape.ts Geometry (minimal; not read by the text-style resolver).

type Glow

type Glow struct {
	Radius Emu
	Color  ResolvedColor
}

type GradientStop

type GradientStop struct {
	Position float64
	Color    ResolvedColor
}

Fill model — port of model/fill.ts. The JS Fill union (none/solid/gradient/image/pattern) is represented as one tagged struct; only the fields relevant to Type are populated.

type GroupElement

type GroupElement struct {
	Type           string // "group"
	Transform      Transform
	ChildTransform Transform
	Children       []SlideElement
	Effects        *EffectList
}

GroupElement — port of model/shape.ts GroupElement.

type HundredthPt

type HundredthPt = float64

Branded OOXML unit types — port of utils/unit-types.ts. The TypeScript upstream uses compile-time branded types to prevent unit confusion; Go has no branded numerics, so these are plain float64 aliases and the As* constructors are identity passthroughs (kept for parity with the upstream API).

func AsHundredthPt

func AsHundredthPt(v float64) HundredthPt
type Hyperlink struct {
	Url     string
	Tooltip string // "" == undefined
}

Hyperlink — port of model/text.ts Hyperlink.

type ImageElement

type ImageElement struct {
	Type        string // "image"
	Transform   Transform
	ImageData   string
	MimeType    string
	Effects     *EffectList
	BlipEffects *BlipEffects
	SrcRect     *SrcRect
	AltText     string
	Stretch     *StretchFillRect
	Tile        *TileInfo
}

ImageElement — port of model/image.ts ImageElement. AltText "" == undefined.

type ImageFillTile

type ImageFillTile struct {
	Tx    Emu
	Ty    Emu
	Sx    float64
	Sy    float64
	Flip  string // "none"|"x"|"y"|"xy"
	Align string
}

type InnerShadow

type InnerShadow struct {
	BlurRadius Emu
	Distance   Emu
	Direction  float64
	Color      ResolvedColor
}

type LineSegment

type LineSegment struct {
	Text       string
	Properties *RunProperties
}

LineSegment is a contiguous run of text sharing one RunProperties on a wrapped line.

type LogLevel

type LogLevel string
const (
	LogOff   LogLevel = "off"
	LogWarn  LogLevel = "warn"
	LogDebug LogLevel = "debug"
)

func GetLogLevel

func GetLogLevel() LogLevel

GetLogLevel returns the current level.

type LumEffect

type LumEffect struct {
	Brightness float64
	Contrast   float64
}

type MarkerResult

type MarkerResult struct {
	Defs      string
	StartAttr string
	EndAttr   string
}

MarkerResult holds marker <defs> plus the marker-start / marker-end attributes.

func RenderMarkers

func RenderMarkers(outline *Outline) MarkerResult

RenderMarkers builds line-end arrow markers for an outline.

type ModifyVerifier

type ModifyVerifier struct {
	AlgorithmName *string
	HashValue     *string
	SaltValue     *string
	SpinCount     *float64
}

type OpentypeFont

type OpentypeFont interface {
	UnitsPerEm() float64
	Ascender() float64
	Descender() float64
	// StringToGlyphs returns one glyph per code point (GSUB ligatures may collapse, hence per-char).
	StringToGlyphs(text string) []OpentypeGlyph
}

OpentypeFont is the metric surface the measurer needs from a parsed font.

type OpentypeFullFont

type OpentypeFullFont interface {
	UnitsPerEm() float64
	Ascender() float64
	Descender() float64
	GetPath(text string, x, y, fontSize float64) OpentypePath
	GetAdvanceWidth(text string, fontSize float64) float64
}

OpentypeFullFont is a glyph-path-capable font (subset of the opentype.js Font API). unitsPerEm/ascender/descender are exposed as methods (Go interfaces can't hold fields).

type OpentypeGlyph

type OpentypeGlyph struct {
	AdvanceWidth *float64
}

OpentypeGlyph is one glyph's advance. AdvanceWidth == nil mirrors JS `advanceWidth` undefined (the `glyph?.advanceWidth ?? unitsPerEm * 0.6` fallback path).

type OpentypePath

type OpentypePath interface {
	ToPathData(decimalPlaces ...int) string
}

OpentypePath is a resolved glyph path that serializes to SVG path data.

type OpentypeSetup

type OpentypeSetup struct {
	Measurer     *OpentypeTextMeasurer
	FontResolver TextPathFontResolver
}

OpentypeSetup bundles the measurer + the text-path resolver built from the same parsed fonts.

func CreateOpentypeSetupFromBuffers

func CreateOpentypeSetupFromBuffers(fontBuffers []FontBuffer, fontMapping FontMapping) *OpentypeSetup

CreateOpentypeSetupFromBuffers parses each font buffer and registers it under its name (or, for a TTC, its name-table families) plus the reverse font-mapping. Returns nil for empty input or when nothing parses.

func CreateOpentypeSetupFromSystem

func CreateOpentypeSetupFromSystem(additionalFontDirs []string, fontMapping FontMapping, skipSystemFonts bool) *OpentypeSetup

CreateOpentypeSetupFromSystem builds (and caches) a setup from the system font dirs + additional dirs. The result is memoized on (sorted dirs, canonical mapping JSON, skipSystemFonts).

type OpentypeTextMeasurer

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

OpentypeTextMeasurer measures text width / line metrics using real font advances.

func CreateOpentypeTextMeasurerFromBuffers

func CreateOpentypeTextMeasurerFromBuffers(fontBuffers []FontBuffer, fontMapping FontMapping) *OpentypeTextMeasurer

CreateOpentypeTextMeasurerFromBuffers builds the full setup from buffers and returns just the measurer (or nil).

func NewOpentypeTextMeasurer

func NewOpentypeTextMeasurer(fonts map[string]OpentypeFont, defaultFont OpentypeFont) *OpentypeTextMeasurer

NewOpentypeTextMeasurer builds a measurer from a name→font map and an optional default font (nil).

func (*OpentypeTextMeasurer) GetAscenderRatio

func (m *OpentypeTextMeasurer) GetAscenderRatio(fontFamily, fontFamilyEa string) float64

GetAscenderRatio returns ascender / unitsPerEm, or 1.0 when no font resolves.

func (*OpentypeTextMeasurer) GetLineHeightRatio

func (m *OpentypeTextMeasurer) GetLineHeightRatio(fontFamily, fontFamilyEa string) float64

GetLineHeightRatio returns (ascender + |descender|) / unitsPerEm, or the CSS default 1.2 when no font resolves.

func (*OpentypeTextMeasurer) MeasureTextWidth

func (m *OpentypeTextMeasurer) MeasureTextWidth(text string, fontSizePt float64, bold bool, fontFamily, fontFamilyEa string) float64

MeasureTextWidth measures the rendered width (px) of text at fontSizePt, honouring bold + the Latin/East-Asian font split. Falls back to the static-metric measurer when no font resolves.

type OuterShadow

type OuterShadow struct {
	BlurRadius      Emu
	Distance        Emu
	Direction       float64
	Color           ResolvedColor
	Alignment       string
	RotateWithShape bool
}

Effect model — port of model/effect.ts. EffectList fields are pointers (nullable).

type Outline

type Outline struct {
	Width      Emu
	Fill       *Fill // solid | gradient | null
	DashStyle  string
	CustomDash []float64 // nil == undefined
	LineCap    *string   // nil == undefined
	LineJoin   *string   // nil == undefined
	HeadEnd    *ArrowEndpoint
	TailEnd    *ArrowEndpoint
}

type Paragraph

type Paragraph struct {
	Runs                 []TextRun
	Properties           *ParagraphProperties
	EndParaRunProperties *RunProperties // nil == undefined
}

Paragraph is a sequence of runs with paragraph properties. (text-wrap reads only Runs.)

type ParagraphProperties

type ParagraphProperties struct {
	Alignment     *string       // "l"|"ctr"|"r"|"just" | null
	LineSpacing   *SpacingValue // nil == null
	SpaceBefore   SpacingValue
	SpaceAfter    SpacingValue
	Level         int
	Bullet        *BulletType
	BulletFont    *string
	BulletColor   *ResolvedColor
	BulletSizePct *float64
	MarginLeft    *Emu
	Indent        *Emu
	TabStops      []TabStop
}

ParagraphProperties — port of model/text.ts ParagraphProperties. Nullable fields are pointers. (lineSpacing/spaceBefore/spaceAfter/tabStops exist in the model but aren't read by the ported code yet, so they're omitted here.)

type ParsedOpentypeFont

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

ParsedOpentypeFont is a parsed font exposing the metrics + names the renderer needs. It satisfies both OpentypeFont (the measurer) and OpentypeFullFont (the text-path resolver).

func ParseOpentypeFont

func ParseOpentypeFont(data []byte) (*ParsedOpentypeFont, error)

ParseOpentypeFont parses an sfnt (single TTF/OTF; TTC must be split first via ExtractTtcFonts). It first tries the hand-rolled table reader (head/hhea/maxp/cmap/hmtx/name + glyf), then attaches a go-text face for outlines. If the hand-rolled reader rejects the font (e.g. a CFF .otf with a cmap subtable the hand-rolled cmap parser doesn't support) but go-text CAN parse it, we build a go-text-backed font so CFF/odd fonts still render (metrics/cmap/advances then come from go-text).

func (*ParsedOpentypeFont) Ascender

func (f *ParsedOpentypeFont) Ascender() float64

func (*ParsedOpentypeFont) Bold added in v0.0.2

func (f *ParsedOpentypeFont) Bold() bool

Bold reports whether this face is a bold weight (used to pick the matching CJK fallback weight).

func (*ParsedOpentypeFont) CharToGlyphIndex

func (f *ParsedOpentypeFont) CharToGlyphIndex(char string) int

CharToGlyphIndex resolves the first rune of char to a glyph id (opentype.js charToGlyph().index).

func (*ParsedOpentypeFont) Descender

func (f *ParsedOpentypeFont) Descender() float64

func (*ParsedOpentypeFont) GetAdvanceWidth

func (f *ParsedOpentypeFont) GetAdvanceWidth(text string, fontSize float64) float64

GetAdvanceWidth sums per-glyph advances scaled to fontSize (px), mirroring opentype.js getAdvanceWidth. (Not exercised by opentype-helpers; provided for OpentypeFullFont completeness.)

func (*ParsedOpentypeFont) GetPath

func (f *ParsedOpentypeFont) GetPath(text string, x, y, fontSize float64) OpentypePath

GetPath builds the outline path for text laid out from baseline (x, y) at fontSize px. Outlines come from go-text (glyf simple+composite + CFF); if go-text couldn't parse the font, it falls back to the hand-rolled simple-glyf reader.

func (*ParsedOpentypeFont) GlyphAdvance

func (f *ParsedOpentypeFont) GlyphAdvance(gid int) float64

GlyphAdvance returns the advance width for a glyph id (0 if out of range).

func (*ParsedOpentypeFont) GlyphOutlineBytes

func (f *ParsedOpentypeFont) GlyphOutlineBytes(gid int) []byte

GlyphOutlineBytes returns the raw glyf bytes for a glyph id (nil when absent / no glyf table).

func (*ParsedOpentypeFont) HasGlyf

func (f *ParsedOpentypeFont) HasGlyf() bool

HasGlyf reports whether the font has a TrueType (glyf) outline table. False for CFF/OTF fonts, which the glyf-copying subsetter can't handle — SubsetFont returns nil for them so the embedder falls back to embedding the full font (RawBytes).

func (*ParsedOpentypeFont) HasGlyph added in v0.0.2

func (f *ParsedOpentypeFont) HasGlyph(r rune) bool

HasGlyph reports whether the font has a real glyph for r (cmap maps it to a non-.notdef id).

func (*ParsedOpentypeFont) Names

func (f *ParsedOpentypeFont) Names() (fontFamily, prefFamily []string)

Names returns the font-family + typographic-family name strings (name table IDs 1 and 16).

func (*ParsedOpentypeFont) NumGlyphs

func (f *ParsedOpentypeFont) NumGlyphs() int

NumGlyphs returns the glyph count (maxp), the Go stand-in for opentype.js font.glyphs.length.

func (*ParsedOpentypeFont) RawBytes

func (f *ParsedOpentypeFont) RawBytes() []byte

RawBytes returns the original font bytes, retained only for CFF/no-glyf fonts (else nil).

func (*ParsedOpentypeFont) StringToGlyphs

func (f *ParsedOpentypeFont) StringToGlyphs(text string) []OpentypeGlyph

StringToGlyphs returns one glyph per rune, mirroring opentype.js stringToGlyphs (unmapped runes resolve to .notdef = glyph 0, which still carries an advanceWidth).

func (*ParsedOpentypeFont) UnitsPerEm

func (f *ParsedOpentypeFont) UnitsPerEm() float64

type PlaceholderStyleInfo

type PlaceholderStyleInfo struct {
	PlaceholderType string
	PlaceholderIdx  *int
	LstStyle        *DefaultTextStyle
	Transform       *Transform // nil == undefined
	Geometry        *Geometry  // nil == undefined
}

PlaceholderStyleInfo — port of model/text.ts PlaceholderStyleInfo.

type PngConvertOptions

type PngConvertOptions struct {
	Width       int      // fit-to-width px; 0 == unset
	Height      int      // fit-to-height px (used only when Width == 0); 0 == unset
	FontBuffers [][]byte // raw TTF/OTF bytes for <text> rendering
}

PngConvertOptions mirrors png-converter.ts PngConvertOptions.

type PngResult

type PngResult struct {
	Png    []byte
	Width  int
	Height int
}

PngResult is the rendered PNG plus its actual pixel dimensions.

func SvgToPng

func SvgToPng(svgString string, options PngConvertOptions) (PngResult, error)

SvgToPng rasterises an SVG document string to a PNG. The rasterisation is delegated to resvg.RenderSVG, which selects the wazero (default) or native libresvg (-tags cgo_resvg) backend.

type Protection

type Protection struct {
	ModifyVerifier *ModifyVerifier
}

type Pt

type Pt = float64

Branded OOXML unit types — port of utils/unit-types.ts. The TypeScript upstream uses compile-time branded types to prevent unit confusion; Go has no branded numerics, so these are plain float64 aliases and the As* constructors are identity passthroughs (kept for parity with the upstream API).

func AsPt

func AsPt(v float64) Pt

func HundredthPointToPoint

func HundredthPointToPoint(value HundredthPt) Pt

HundredthPointToPoint converts 1/100-point units to points.

type RenderResult

type RenderResult struct {
	Content string
	Defs    []string
}

RenderResult — port of renderer/render-result.ts: SVG content plus any <defs> fragments.

func RenderChart

func RenderChart(element *ChartElement) RenderResult

RenderChart renders a chart element to SVG.

func RenderConnector

func RenderConnector(connector *ConnectorElement) RenderResult

RenderConnector renders a connector/line element to SVG.

func RenderImage

func RenderImage(image *ImageElement) RenderResult

RenderImage renders an image element to SVG content (+ defs).

func RenderShape

func RenderShape(shape *ShapeElement) RenderResult

RenderShape renders a shape element (geometry + fill/outline + optional text body) to SVG.

func RenderTable

func RenderTable(element *TableElement) RenderResult

RenderTable renders a table element (cell backgrounds, borders, and text) to SVG.

type ResolvedColor

type ResolvedColor struct {
	Hex   string
	Alpha float64
}

ResolvedColor is a resolved color — port of model/fill.ts ResolvedColor.

type RunProperties

type RunProperties struct {
	FontSize      *float64 // Pt | null
	FontFamily    *string  // string | null
	FontFamilyEa  *string
	FontFamilyCs  *string
	Bold          bool
	Italic        bool
	Underline     bool
	Strikethrough bool
	Color         *ResolvedColor // ResolvedColor | null
	Baseline      float64
	Hyperlink     *Hyperlink   // nil == null
	Outline       *TextOutline // nil == null
}

RunProperties holds the formatting of a text run — port of model/text.ts RunProperties. Nullable fields (fontSize/fontFamily/.../color) are pointers (nil == JS null), so the text-style inheritance pass can detect "unset" and fill them.

type ScriptSegment

type ScriptSegment struct {
	Text string
	IsEa bool
}

ScriptSegment is a contiguous run of latin or east-asian characters.

type ShapeElement

type ShapeElement struct {
	Type            string // "shape"
	Transform       Transform
	Geometry        *Geometry
	Fill            *Fill
	Outline         *Outline
	TextBody        *TextBody
	Effects         *EffectList
	PlaceholderType string
	PlaceholderIdx  *int
	AltText         string     // "" == undefined (aria-label / source name)
	Hyperlink       *Hyperlink // nil == undefined (shape-level hyperlink from cNvPr.hlinkClick)
}

ShapeElement — port of model/shape.ts ShapeElement. PlaceholderType "" == undefined; PlaceholderIdx nil == undefined.

type Slide

type Slide struct {
	SlideNumber  int
	Background   *Background
	Elements     []SlideElement
	ShowMasterSp bool
}

Slide is a parsed slide (port of model Slide).

type SlideElement

type SlideElement interface {
	// contains filtered or unexported methods
}

SlideElement is the shape/group/... union — port of model/shape.ts SlideElement.

type SlideSize

type SlideSize struct {
	Width  Emu
	Height Emu
}

Presentation model — port of model/presentation.ts. Optional fields are pointers (nil == unset).

type SoftEdge

type SoftEdge struct {
	Radius Emu
}

type SpacingValue

type SpacingValue struct {
	Type  string // "pts" | "pct"
	Value float64
}

SpacingValue — port of model/text.ts SpacingValue: pts (1/100 pt) or pct (1/1000 %).

type SrcRect

type SrcRect struct {
	Left   float64
	Top    float64
	Right  float64
	Bottom float64
}

SrcRect — fractional crop insets (a:srcRect).

type StretchFillRect

type StretchFillRect struct {
	Left   float64
	Top    float64
	Right  float64
	Bottom float64
}

StretchFillRect — fractional stretch fillRect insets (a:stretch/a:fillRect).

type TabStop

type TabStop struct {
	Position  Emu
	Alignment string // "l"|"ctr"|"r"|"dec"
}

TabStop — port of model/text.ts TabStop.

type TableCell

type TableCell struct {
	TextBody *TextBody
	Fill     *Fill
	Borders  *CellBorders
	GridSpan int
	RowSpan  int
	HMerge   bool
	VMerge   bool
}

TableCell is one cell.

type TableColumn

type TableColumn struct {
	Width Emu
}

TableColumn is one column (width).

type TableData

type TableData struct {
	Rows    []TableRow
	Columns []TableColumn
}

TableData holds the table's rows + columns.

type TableElement

type TableElement struct {
	Type      string // "table"
	Transform Transform
	Table     TableData
}

TableElement is a table shape on a slide.

type TableRow

type TableRow struct {
	Height Emu
	Cells  []TableCell
}

TableRow is one row (height + cells).

type TextBody

type TextBody struct {
	Paragraphs     []Paragraph
	BodyProperties BodyProperties
}

TextBody — port of model/text.ts TextBody.

type TextMeasurer

type TextMeasurer interface {
	MeasureTextWidth(text string, fontSizePt float64, bold bool, fontFamily, fontFamilyEa string) float64
	GetLineHeightRatio(fontFamily, fontFamilyEa string) float64
	GetAscenderRatio(fontFamily, fontFamilyEa string) float64
}

TextMeasurer measures text width and line/ascender ratios. fontFamily / fontFamilyEa use "" to mean null (JS `string | null | undefined`).

func GetTextMeasurer

func GetTextMeasurer() TextMeasurer

GetTextMeasurer returns the currently installed measurer.

type TextOutline

type TextOutline struct {
	Width Emu
	Color ResolvedColor
}

TextOutline — port of model/text.ts TextOutline (run-level text stroke).

type TextPathFontResolver

type TextPathFontResolver interface {
	// contains filtered or unexported methods
}

TextPathFontResolver resolves a font for glyph-path rendering (nil interface if none).

type TextRun

type TextRun struct {
	Text       string
	Properties *RunProperties
}

TextRun is one run of text with its properties.

type Theme

type Theme struct {
	ColorScheme ColorScheme
	FontScheme  FontScheme
	FmtScheme   *FormatScheme
}

Theme is a parsed theme part — port of model/theme.ts. FmtScheme nil == undefined.

type TileInfo

type TileInfo struct {
	Tx    Emu
	Ty    Emu
	Sx    float64
	Sy    float64
	Flip  string // "none"|"x"|"y"|"xy"
	Align string
}

TileInfo — image tile fill (a:tile). Mirrors model/image.ts TileInfo.

type Transform

type Transform struct {
	OffsetX      float64 // Emu
	OffsetY      float64 // Emu
	ExtentWidth  float64 // Emu
	ExtentHeight float64 // Emu
	Rotation     float64 // degrees
	FlipH        bool
	FlipV        bool
}

Transform is a shape's position/size/orientation — port of model/shape.ts Transform.

type TxStyles

type TxStyles struct {
	TitleStyle *DefaultTextStyle
	BodyStyle  *DefaultTextStyle
	OtherStyle *DefaultTextStyle
}

TxStyles — port of model/text.ts TxStyles (slideMaster title/body/other styles).

type WarningEntry

type WarningEntry struct {
	Feature    string
	Message    string
	Context    string
	HasContext bool
}

WarningEntry is one recorded warning. HasContext distinguishes JS `undefined` from "".

func GetWarningEntries

func GetWarningEntries() []WarningEntry

GetWarningEntries returns the recorded entries.

type WarningSummary

type WarningSummary struct {
	TotalCount int
	Features   []WarningSummaryFeature
}

WarningSummary aggregates recorded warnings.

func FlushWarnings

func FlushWarnings() WarningSummary

FlushWarnings prints a summary (unless off / empty), then resets and returns it.

func GetWarningSummary

func GetWarningSummary() WarningSummary

GetWarningSummary returns the current aggregate, features in insertion order.

type WarningSummaryFeature

type WarningSummaryFeature struct {
	Feature string
	Message string
	Count   int
}

WarningSummaryFeature is a per-feature occurrence count.

type WrappedLine

type WrappedLine struct {
	Segments []LineSegment
}

WrappedLine is one output line of segments.

func WrapParagraph

func WrapParagraph(paragraph Paragraph, availableWidth float64, opts ...float64) []WrappedLine

WrapParagraph wraps a paragraph's runs into lines. Optional opts: opts[0] = defaultFontSize (default 18), opts[1] = fontScale (default 1) — mirroring the JS default args.

Jump to

Keyboard shortcuts

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