Documentation
¶
Overview ¶
Package utils — crypto.go implements AES encryption/decryption compatible with the FastReport .NET Crypter class (Utils/Crypter.cs).
FastReport uses AES-128-CBC with ISO10126 padding. The key and IV are derived via a .NET PasswordDeriveBytes-compatible PBKDF1:
base = SHA1^100(password || salt) — 20 bytes (SHA-1 output)
key = base[0:16]
iv = base[16:20] || SHA1("1" || base || password || salt)[0:12]
Encrypted FRX streams are prefixed with the 3-byte "rij" signature (114 105 106). Encrypted strings are prefixed with the literal string "rij" followed by the base64-encoded ciphertext.
Package utils is part of the go-fastreport library, a pure Go port of FastReport .NET.
Package utils provides shared utility types and helpers used throughout go-fastreport.
Package utils provides image loading, resizing, and encoding helpers equivalent to FastReport's Utils/ImageHelper.cs.
Package utils — murmur3.go implements Murmur3-based hash helpers ported from FastReport.Utils.Crypter.ComputeHash (Utils/Crypter.cs) and default-password helpers for EncryptStringDefault / DecryptStringDefault.
Package utils provides report validation for go-fastreport. The Validator checks report definitions for common structural errors.
Index ¶
- Constants
- Variables
- func AbbrevPropName(s string) string
- func ApplyGrayscale(src image.Image) image.Image
- func ApplyTransparency(src image.Image, transparency float32) image.Image
- func BoolFromString(s string) bool
- func BoolToString(v bool) string
- func BytesToImage(data []byte) (image.Image, error)
- func CRC32(data []byte) uint32
- func CRC32String(data []byte) string
- func CalcTextHeight(text string, f style.Font, displayWidth, displayHeight float32) (height float32, charsFit int)
- func CalcTextWidth(text string, f style.Font, maxWidth float32) float32
- func CalculateSpaceWidth(f style.Font) float32
- func CharsFitInWidth(text string, f style.Font, maxWidth float32) int
- func ColorEqual(a, b color.RGBA) bool
- func Compress(data []byte) (string, error)
- func ComputeHashBytes(input []byte) string
- func ComputeHashReader(r io.Reader) (string, error)
- func ComputeHashString(input string) string
- func CreateTempFileInDir(dir string) (string, error)
- func DecodeICOImage(data []byte) image.Image
- func Decompress(s string) ([]byte, error)
- func DecryptStream(source io.Reader, password string) (io.Reader, error)
- func DecryptString(data, password string) (string, error)
- func DecryptStringDefault(data string) (string, error)
- func DefaultFace() font.Face
- func EncryptStream(dest io.Writer, password string) (io.WriteCloser, error)
- func EncryptString(plaintext, password string) (string, error)
- func EncryptStringDefault(plaintext string) (string, error)
- func EstimateTextWidth(text string, charWidth float32) float32
- func ExpandPropName(s string) string
- func ExtractBracketExpressions(text string) []string
- func Float32FromString(s string) float32
- func Float32ToString(v float32) string
- func FontHeight(face font.Face) float32
- func FontLineHeight(f style.Font) float32
- func FormatColor(c color.RGBA) string
- func GDIMeasureStringPadding(f style.Font) float32
- func GetEffectiveTempFolder() string
- func GetStream(assembly, name string) (io.ReadCloser, error)
- func GetStreamFR(name string) (io.ReadCloser, error)
- func GetTabPosition(pos, tabOffset, tabSize float32) float32
- func HasUnresolvedExpression(text string, knownNames map[string]bool) bool
- func ImageToBytes(img image.Image, fmt ImageFormat) ([]byte, error)
- func InchesToPixels(in float32) float32
- func IntFromString(s string) int
- func IntToString(v int) string
- func IsStreamEncrypted(r io.Reader) (bool, error)
- func IsStringEncrypted(data string) bool
- func LoadImage(source string) (image.Image, error)
- func LoadLocale(filename string) error
- func LoadLocaleReader(r io.Reader) error
- func LocaleName() string
- func MMToPixels(mm float32) float32
- func MeasureLine(line string, face font.Face) (width, height float32)
- func MeasureLines(text string, f style.Font, maxWidth float32) int
- func MeasureStringAdvance(text string, f style.Font) float32
- func MeasureStringSize(text string, f style.Font) (width, height float32)
- func MeasureText(text string, f style.Font, maxWidth float32) (width, height float32)
- func NormalizeBoundsF(left, top, width, height float32) (float32, float32, float32, float32)
- func ParseColor(s string) (color.RGBA, error)
- func PeekAndDecrypt(r io.Reader, password string) (io.Reader, bool, error)
- func PixelsToInches(px float32) float32
- func PixelsToMM(px float32) float32
- func PixelsToPoints(pixels float32) float32
- func PointsToPixels(points float32) float32
- func RGBAFromString(s string) color.RGBA
- func RGBAToString(c color.RGBA) string
- func RTFToHTML(rtf string) string
- func RectContainInOtherF(outerL, outerT, outerW, outerH float32, innerL, innerT, innerW, innerH float32) bool
- func RectsIntersectF(l1, t1, w1, h1, l2, t2, w2, h2 float32) bool
- func RegisterResource(assembly, name string, provider func() (io.ReadCloser, error))
- func RegisterResourceBytes(assembly, name string, data []byte)
- func RenderWatermarkText(text string, f style.Font, textColor color.RGBA, rotation int, w, h int) image.Image
- func ResGet(key string) string
- func ResSet(key, value string)
- func ResetToBuiltin()
- func ResizeImage(src image.Image, dstW, dstH int, mode SizeMode) image.Image
- func RoundFloat64(v float64, places int) float64
- func ScaleWidth(measuredWidth float32, f style.Font) float32
- func ScreenDpi() int
- func ScreenDpiFX() float32
- func SetDefaultPassword(pwd string)
- func SetUIScale(v float32)
- func ShortPropCode(fullName string) (code string, ok bool)
- func ShortPropName(code string) (name string, ok bool)
- func StripHtmlTags(s string) string
- func StripRTF(rtf string) string
- func TabStopPositions(tabOffset, tabSize float32, n int) []float32
- func UIScale() float32
- func UnpackStream(assembly, name string) (io.ReadCloser, error)
- func UnpackStreamFR(name string) (io.ReadCloser, error)
- func UnzipData(data []byte) ([]byte, error)
- func UnzipStream(w io.Writer, r io.Reader) error
- func WingdingsToUnicode(s string) string
- func WrapText(text string, face font.Face, maxWidth float32) []string
- func ZipData(data []byte) ([]byte, error)
- func ZipStream(w io.Writer, r io.Reader) error
- type AncestorError
- type BaselineType
- type ClassError
- type Collection
- func (c *Collection[T]) Add(item T)
- func (c *Collection[T]) All() iter.Seq2[int, T]
- func (c *Collection[T]) Clear()
- func (c *Collection[T]) Contains(item T, eq func(a, b T) bool) bool
- func (c *Collection[T]) Get(i int) T
- func (c *Collection[T]) IndexOf(item T, eq func(a, b T) bool) int
- func (c *Collection[T]) Insert(index int, item T)
- func (c *Collection[T]) Len() int
- func (c *Collection[T]) Remove(item T, eq func(a, b T) bool) bool
- func (c *Collection[T]) RemoveAt(i int)
- func (c *Collection[T]) SetOrder(item T, order int, eq func(a, b T) bool)
- func (c *Collection[T]) Slice() []T
- type CompilerError
- type CompilerErrorInfo
- type Config
- func (c *Config) CreateTempFile(dir string) (string, error)
- func (c *Config) GetConfiguredTempFolder() string
- func (c *Config) GetForbidLocalData() bool
- func (c *Config) GetPreparedCompressed() bool
- func (c *Config) GetRightToLeft() bool
- func (c *Config) GetTempFolder() string
- func (c *Config) SetForbidLocalData(v bool)
- func (c *Config) SetPreparedCompressed(v bool)
- func (c *Config) SetRightToLeft(v bool)
- func (c *Config) SetTempFolder(path string)
- func (c *Config) TempFilePath() (string, error)
- type DataNotInitializedError
- type DataTableError
- type DecryptError
- type DuplicateNameError
- type FRColumnInfo
- type FRRandom
- func (r *FRRandom) GetRandomValue(source any) (result any)
- func (r *FRRandom) NextByte() byte
- func (r *FRRandom) NextBytes(number int) []byte
- func (r *FRRandom) NextChar() rune
- func (r *FRRandom) NextDay(start time.Time) time.Time
- func (r *FRRandom) NextDigit() int
- func (r *FRRandom) NextDigitMax(max int) int
- func (r *FRRandom) NextDigitRange(min, max int) int
- func (r *FRRandom) NextDigits(number int) string
- func (r *FRRandom) NextLetter(source rune) rune
- func (r *FRRandom) NextTimeSpanBetweenHours(startHour, endHour int) time.Duration
- func (r *FRRandom) RandomizeDecimal(source float64) float64
- func (r *FRRandom) RandomizeDouble(source float64) float64
- func (r *FRRandom) RandomizeFloat32(source float32) float32
- func (r *FRRandom) RandomizeInt16(source int16) int16
- func (r *FRRandom) RandomizeInt32(source int32) int32
- func (r *FRRandom) RandomizeInt64(source int64) int64
- func (r *FRRandom) RandomizeSByte(source int8) int8
- func (r *FRRandom) RandomizeString(source string) string
- func (r *FRRandom) RandomizeUInt16(source uint16) uint16
- func (r *FRRandom) RandomizeUInt32(source uint32) uint32
- func (r *FRRandom) RandomizeUInt64(source uint64) uint64
- type FRRandomFieldValue
- type FRRandomFieldValueCollection
- type FastNameCreator
- type FastString
- type FileFormatError
- type FileStorageService
- func (f *FileStorageService) Exists(path string) bool
- func (f *FileStorageService) Load(path string) ([]byte, error)
- func (f *FileStorageService) Reader(path string) (io.ReadCloser, error)
- func (f *FileStorageService) Save(path string, data []byte) error
- func (f *FileStorageService) Writer(path string) (io.WriteCloser, error)
- type FloatCollection
- func (fc *FloatCollection) Add(v float32)
- func (fc *FloatCollection) AddRange(values []float32)
- func (fc *FloatCollection) Assign(src FloatCollection)
- func (fc *FloatCollection) Clear()
- func (fc FloatCollection) Contains(value float32) bool
- func (fc FloatCollection) Get(i int) float32
- func (fc FloatCollection) IndexOf(value float32) int
- func (fc *FloatCollection) Insert(index int, value float32)
- func (fc FloatCollection) Len() int
- func (fc *FloatCollection) Remove(value float32)
- func (fc *FloatCollection) RemoveAt(index int)
- func (fc FloatCollection) String() string
- type FontDescriptor
- type FontManager
- type FontStyle
- type GroupHeaderNoConditionError
- type HtmlLine
- type HtmlRun
- type HtmlTextRenderer
- type ImageFormat
- type ImageLoadError
- type MemoryStorageService
- func (m *MemoryStorageService) Exists(path string) bool
- func (m *MemoryStorageService) Load(path string) ([]byte, error)
- func (m *MemoryStorageService) Put(path string, data []byte)
- func (m *MemoryStorageService) Reader(path string) (io.ReadCloser, error)
- func (m *MemoryStorageService) Save(path string, data []byte) error
- func (m *MemoryStorageService) Writer(path string) (io.WriteCloser, error)
- type Namer
- type NotValidIdentifierError
- type ObjectNamer
- type ParentError
- type PointF
- type RectF
- type ReportValidator
- type SizeF
- type SizeMode
- type StorageService
- type TextMeasurement
- type UnknownNameError
- type Validatable
- type ValidatableReport
- type ValidationIssue
- type ValidationRule
- type ValidationSeverity
- type Value
- type ZipArchive
Constants ¶
const ( WatermarkRotationHorizontal = 0 WatermarkRotationVertical = 1 WatermarkRotationForwardDiagonal = 2 WatermarkRotationBackward = 3 )
Watermark text rotation constants matching preview.WatermarkTextRotation.
const Version = "1.0.0"
Version is the go-fastreport library version. Mirrors C# Config.Version (Config.cs line 199), which returns the assembly version string.
Variables ¶
var ( // ColorTransparent matches C# Color.Transparent = Color.FromArgb(0, 255, 255, 255): // white with alpha=0. The RGB values are 255 to match the .NET definition. ColorTransparent = color.RGBA{R: 255, G: 255, B: 255, A: 0} // ColorBlack is fully opaque black. ColorBlack = color.RGBA{R: 0, G: 0, B: 0, A: 255} // ColorWhite is fully opaque white. ColorWhite = color.RGBA{R: 255, G: 255, B: 255, A: 255} // ColorRed is fully opaque red. ColorRed = color.RGBA{R: 255, G: 0, B: 0, A: 255} // ColorGreen is fully opaque green (HTML green, not lime). ColorGreen = color.RGBA{R: 0, G: 128, B: 0, A: 255} // ColorBlue is fully opaque blue. ColorBlue = color.RGBA{R: 0, G: 0, B: 255, A: 255} )
Predefined colors for common use.
var DefaultConfig = &Config{ PreparedCompressed: true, }
DefaultConfig is the global configuration instance.
var DefaultFontManager = NewFontManager()
DefaultFontManager is the global font manager.
Functions ¶
func AbbrevPropName ¶
AbbrevPropName returns the short code for s, or s unchanged if no abbreviation is registered.
func ApplyGrayscale ¶
ApplyGrayscale converts img to grayscale using the NTSC luminance weights (R×0.299 + G×0.587 + B×0.114), matching C# ImageHelper.GetGrayscaleBitmap. The alpha channel is preserved unchanged. C# ref: FastReport.Base/Utils/ImageHelper.cs GetGrayscaleBitmap
func ApplyTransparency ¶
ApplyTransparency multiplies the alpha channel of every pixel by (1 - transparency), matching C# ImageHelper.GetTransparentBitmap where Matrix33 = 1 - transparency. transparency 0.0 → fully opaque (no change); 1.0 → fully invisible. C# ref: FastReport.Base/Utils/ImageHelper.cs GetTransparentBitmap
func BoolFromString ¶
BoolFromString parses a boolean from a string. It returns true when s (trimmed, case-insensitive) equals "true" and false for any other value, including empty strings.
func BoolToString ¶
BoolToString converts a bool to its canonical lowercase string representation ("true" or "false").
func BytesToImage ¶
BytesToImage decodes raw bytes (PNG or JPEG) into an image.Image.
func CRC32 ¶
CRC32 computes a CRC32 checksum of data using the IEEE polynomial, which is the standard polynomial used by most CRC32 implementations including the FastReport .NET Crc32 class.
func CRC32String ¶
CRC32String computes a CRC32 checksum of data and returns it as an eight-character lowercase hexadecimal string.
func CalcTextHeight ¶
func CalcTextHeight(text string, f style.Font, displayWidth, displayHeight float32) (height float32, charsFit int)
CalcTextHeight returns the total pixel height occupied by text when rendered inside a box of the given displayWidth. It sums line heights for all wrapped lines and stops accumulating once height exceeds displayHeight (returns the full content height regardless, matching C# CalcHeight behaviour).
charsFit is set to the character index at which the text first overflows displayHeight (0 means the entire text fits).
Ref: TextRenderer.cs AdvancedTextRenderer.CalcHeight (line ~340)
func CalcTextWidth ¶
CalcTextWidth returns the maximum pixel width of any wrapped line of text plus a trailing space width (matching C# CalcWidth which adds spaceWidth).
Ref: TextRenderer.cs AdvancedTextRenderer.CalcWidth (line ~375)
func CalculateSpaceWidth ¶
CalculateSpaceWidth returns the pixel width of a single space character for the given font. This matches C# AdvancedTextRenderer.CalculateSpaceSize:
w_ab = MeasureString("abcdefabcdef", font)
w_a40b= MeasureString("abcdef{40 spaces}abcdef", font)
space = (w_a40b - w_ab) / 40
Ref: TextRenderer.cs CalculateSpaceSize (line ~241)
func CharsFitInWidth ¶
CharsFitInWidth returns how many leading characters (runes) of text fit within maxWidth pixels when rendered with font f.
This matches the inner MeasureString loop in C# Paragraph.WrapLines: it progressively adds characters until the measured width exceeds maxWidth, then returns the count that fit. The minimum return value is 1 (a single character always "fits" even if it overflows, to prevent infinite loops).
Ref: TextRenderer.cs Paragraph.WrapLines + MeasureString (line ~550)
func ColorEqual ¶
ColorEqual reports whether a and b represent the same color.
func Compress ¶
Compress compresses data using GZip (the same format as the FastReport .NET Compressor class, which uses GZipStream) and returns the result as a standard base64-encoded string.
func ComputeHashBytes ¶
ComputeHashBytes returns the 32-char uppercase hex Murmur3 hash of input. Mirrors C# Crypter.ComputeHash(byte[]).
func ComputeHashReader ¶
ComputeHashReader reads all bytes from r and returns the Murmur3 hash. Mirrors C# Crypter.ComputeHash(Stream).
func ComputeHashString ¶
ComputeHashString returns the Murmur3 hash of the UTF-8 bytes of input. Mirrors C# Crypter.ComputeHash(string).
func CreateTempFileInDir ¶
CreateTempFileInDir creates a temporary file in the specified directory using DefaultConfig. Convenience wrapper around DefaultConfig.CreateTempFile.
func DecodeICOImage ¶
DecodeICOImage extracts and decodes the first image from ICO format data. ICO files embed BMP or PNG image data. C# System.Drawing.Image.FromStream handles ICO natively; this provides equivalent Go decoding. Returns nil if the data is not valid ICO or cannot be decoded.
func Decompress ¶
Decompress decodes a base64-encoded string produced by Compress and returns the original uncompressed bytes. If the decoded bytes do not begin with the GZip magic number the raw decoded bytes are returned unchanged, matching the behaviour of the .NET Compressor.Decompress(byte[]) method.
func DecryptStream ¶
DecryptStream reads from source assuming AES-128-CBC encryption and the "rij" signature has already been consumed. Use PeekAndDecrypt for transparent handling.
func DecryptString ¶
DecryptString decrypts a "rij"-prefixed base64 string produced by EncryptString (or the C# Crypter.EncryptString equivalent). Returns plaintext unchanged if not encrypted or either argument is empty.
func DecryptStringDefault ¶
DecryptStringDefault decrypts a "rij"-prefixed string using the default password.
func DefaultFace ¶
DefaultFace returns the default font face (basicfont.Face7x13).
func EncryptStream ¶
EncryptStream wraps dest so that writes are AES-128-CBC encrypted. It writes the "rij" signature to dest before returning the writer. The caller must Close the returned WriteCloser to flush the final block.
func EncryptString ¶
EncryptString encrypts plaintext using the given password and returns "rij" + base64(ciphertext), matching C# Crypter.EncryptString.
func EncryptStringDefault ¶
EncryptStringDefault encrypts plaintext using the default password.
func EstimateTextWidth ¶
EstimateTextWidth returns a quick character-count-based width estimate (monospace approximation) when no font metrics are available. charWidth is the assumed width per character in pixels.
func ExpandPropName ¶
ExpandPropName returns the full property name for s, or s unchanged if s is not a registered short code.
func ExtractBracketExpressions ¶
ExtractBracketExpressions returns all [bracket] sub-strings found in text. Nested brackets are returned as the outermost span.
func Float32FromString ¶
Float32FromString parses a 32-bit floating-point number from s using the invariant (dot) decimal separator. On parse failure it returns 0.
func Float32ToString ¶
Float32ToString converts a float32 to a string using the shortest representation that round-trips back to the same value (invariant locale).
func FontHeight ¶
FontHeight returns the height of the font face in pixels.
func FontLineHeight ¶
FontLineHeight returns the pixel line height for the given font. Exposed so callers outside the utils package can obtain consistent values without importing internal helpers.
func FormatColor ¶
FormatColor formats c as an "#AARRGGBB" uppercase hex string, which is the canonical FRX serialisation format.
func GDIMeasureStringPadding ¶
GDIMeasureStringPadding returns the extra height that .NET's Graphics.MeasureString adds with the default StringFormat (GenericDefault). This is fontSize_pt / 6 pixels (≡ fontPx / 8). It should be added to the measured height only when the C# simple MeasureString path is used (i.e. IsAdvancedRendererNeeded is false).
func GetEffectiveTempFolder ¶
func GetEffectiveTempFolder() string
GetEffectiveTempFolder returns the effective temp folder from DefaultConfig. Convenience top-level function mirroring C# Config.GetTempFolder().
func GetStream ¶
func GetStream(assembly, name string) (io.ReadCloser, error)
GetStream returns a stream for the named resource in the given assembly. Returns (nil, nil) when the resource is not registered, mirroring the C# behaviour where GetManifestResourceStream returns null for unknown names.
C# equivalent: ResourceLoader.GetStream(assembly, resource)
func GetStreamFR ¶
func GetStreamFR(name string) (io.ReadCloser, error)
GetStreamFR returns a stream for a named resource in the default "FastReport" assembly. Returns (nil, nil) when the resource is not registered.
C# equivalent: ResourceLoader.GetStream(resource)
func GetTabPosition ¶
GetTabPosition returns the X position of the next tab stop after pos. tabOffset is the position of the first tab stop; tabSize is the distance between consecutive tab stops (both in pixels).
Ref: TextRenderer.cs AdvancedTextRenderer.GetTabPosition (line ~391)
tabPosition = int((pos - tabOffset) / tabSize) if pos < tabOffset → return tabOffset return (tabPosition + 1) * tabSize + tabOffset
func HasUnresolvedExpression ¶
HasUnresolvedExpression returns true if text contains at least one [bracket] expression whose content is not in the knownNames set.
func ImageToBytes ¶
func ImageToBytes(img image.Image, fmt ImageFormat) ([]byte, error)
ImageToBytes encodes an image.Image to PNG or JPEG bytes.
func InchesToPixels ¶
InchesToPixels converts inches to pixels (96 dpi).
func IntFromString ¶
IntFromString parses a decimal integer from s. On parse failure it returns 0.
func IntToString ¶
IntToString converts an int to its decimal string representation.
func IsStreamEncrypted ¶
IsStreamEncrypted reports whether the stream begins with the "rij" signature. It reads 3 bytes from r; the caller must not rewind r afterwards — use DetachOrDecrypt instead if transparent decryption is needed.
func IsStringEncrypted ¶
IsStringEncrypted reports whether data begins with the "rij" prefix.
func LoadImage ¶
LoadImage loads an image from:
- a file path
- a data URI (data:image/...;base64,<b64>)
- an HTTP/HTTPS URL
- raw base64 (no prefix, tried last)
func LoadLocale ¶
LoadLocale loads a .frl (XML) locale file and sets it as the active locale. Falls back to the built-in English locale if the file cannot be read.
func LoadLocaleReader ¶
LoadLocaleReader parses a locale XML from r and sets it as the active locale.
func LocaleName ¶
func LocaleName() string
LocaleName returns the name attribute of the current locale root (e.g. "en").
func MMToPixels ¶
MMToPixels converts millimetres to pixels (96 dpi). Uses the same 96 DPI base as standardDPI in text.go.
func MeasureLine ¶
MeasureLine measures a single line of text (no wrapping). Returns width and height in pixels.
func MeasureLines ¶
MeasureLines returns the number of visual lines produced by word-wrapping text at maxWidth pixels using the given font. If maxWidth <= 0, each \n-delimited paragraph is one line.
func MeasureStringAdvance ¶
MeasureStringAdvance returns the pixel width of text using the font.Face advance metrics. It is the low-level primitive underlying CharsFitInWidth and CalcTextWidth. Tab characters are treated as zero-width.
func MeasureStringSize ¶
MeasureStringSize returns (width, height) for a single line of text (no word-wrap). Height is exactly one line height. This is the simplest form matching GDI+ Graphics.MeasureString with no bounding rectangle.
func MeasureText ¶
MeasureText measures the rendered width and height of text when drawn with the given font, optionally wrapping at maxWidth pixels (0 = no wrap). The returned width is the maximum line width; height is lineHeight * lineCount.
func NormalizeBoundsF ¶
NormalizeBoundsF ensures the width and height of a rectangle are non-negative. If width < 0 the left edge is moved to the right edge and width is negated. If height < 0 the top edge is moved to the bottom edge and height is negated. Equivalent to the C# internal Validator.NormalizeBounds(ref RectangleF).
func ParseColor ¶
ParseColor parses a color from various string formats:
- "#RGB" — 3-digit shorthand; each digit is doubled; alpha = 0xFF.
- "#RRGGBB" — 6-digit RGB; alpha = 0xFF.
- "#AARRGGBB" — 8-digit ARGB; the first two hex digits are alpha.
- "R, G, B" — .NET ColorConverter 3-component format; alpha = 0xFF.
- "A, R, G, B" — .NET ColorConverter 4-component format.
- A CSS/Windows named color (case-insensitive, e.g. "White", "LightGray").
- A decimal integer string representing a signed 32-bit ARGB value (compatible with .NET's Color.ToArgb()).
Returns an error when the string cannot be recognised as any of those formats.
func PeekAndDecrypt ¶
PeekAndDecrypt reads the first 3 bytes from r. If they are the "rij" signature, it decrypts the remainder using password and returns the plaintext reader. Otherwise it returns a reader that prepends the 3 bytes back and returns all original content unmodified.
func PixelsToInches ¶
PixelsToInches converts pixels (96 dpi) to inches.
func PixelsToMM ¶
PixelsToMM converts pixels (96 dpi) to millimetres. Uses the same 96 DPI base as standardDPI in text.go.
func PixelsToPoints ¶
PixelsToPoints converts pixel measurements to points (at 96 DPI).
func PointsToPixels ¶
PointsToPixels converts points to pixels (at 96 DPI).
func RGBAFromString ¶
RGBAFromString parses a color.RGBA from s. Accepted formats are the same as ParseColor: "#RGB", "#RRGGBB", "#AARRGGBB", or a decimal ARGB integer string. On parse failure it returns a zero color.RGBA (transparent black).
func RGBAToString ¶
RGBAToString converts c to its "#AARRGGBB" canonical hex string, which is the FRX serialisation format understood by RGBAFromString.
func RTFToHTML ¶
RTFToHTML converts RTF-formatted text to an HTML fragment preserving basic formatting: bold (\b), italic (\i), underline (\ul / \ulnone), paragraph breaks (\par), line breaks (\line), tabs (\tab), font size (\fsN), and special characters (\'XX hex escapes, \uN Unicode, named dashes/quotes).
The output is a minimal HTML fragment (no <html> or <body> wrapper). Unknown control words are silently discarded.
func RectContainInOtherF ¶
func RectContainInOtherF( outerL, outerT, outerW, outerH float32, innerL, innerT, innerW, innerH float32, ) bool
RectContainInOtherF returns true when the inner rectangle is fully contained within the outer rectangle. Both rectangles are normalized first, and the inner rectangle is shrunk by 0.01 units on all sides to compensate for designer grid-fit inaccuracy, matching the C# implementation exactly. C# reference: Validator.cs lines 79–88.
func RectsIntersectF ¶
RectsIntersectF reports whether two (normalized) rectangles overlap. The 0.01-unit inset applied by GetIntersectingObjects in C# is not applied here; callers that need it should shrink r1 by -0.01 before calling. C# reference: Validator.cs line 70 — bounds.IntersectsWith(bounds1).
func RegisterResource ¶
func RegisterResource(assembly, name string, provider func() (io.ReadCloser, error))
RegisterResource registers a named resource under the given assembly and resource name. The provider function is called each time GetStream is invoked for that resource; it must return a fresh, independently readable io.ReadCloser.
Calling RegisterResource with an already-registered key replaces the existing provider.
func RegisterResourceBytes ¶
RegisterResourceBytes is a convenience wrapper around RegisterResource that registers a static byte slice as a resource. Each call to GetStream returns a fresh reader over a copy of the bytes.
func RenderWatermarkText ¶
func RenderWatermarkText(text string, f style.Font, textColor color.RGBA, rotation int, w, h int) image.Image
RenderWatermarkText rasterizes watermark text onto a transparent RGBA image, matching C# Watermark.DrawText() which renders via TextObject.DrawText onto a Graphics surface (Watermark.cs line 253-276). The C# HTML exporter then embeds this rasterised image as a PictureObject.
Since Go uses basicfont.Face7x13 as fallback (13px tall), the text is first drawn at basicfont scale onto a small image, then scaled up to the target font size and composited onto the output image with rotation.
func ResGet ¶
ResGet returns the locale string for the given comma-separated key path. Falls back to the built-in English locale, then returns "<key> NOT LOCALIZED!".
func ResSet ¶
func ResSet(key, value string)
ResSet overrides a locale string for the given comma-separated key path. The value is applied to the current locale. If intermediate nodes are missing they are created.
func ResetToBuiltin ¶
func ResetToBuiltin()
ResetToBuiltin resets the active locale to the built-in English strings.
func ResizeImage ¶
ResizeImage scales src to fit within the target (dstW × dstH) box according to mode. The returned image is exactly dstW×dstH (with transparent/white padding where required).
func RoundFloat64 ¶
RoundFloat64 rounds v to the given number of decimal places. This is a convenience wrapper used by exporters and matches the rounding logic in C# ExportUtils.FloatToString.
func ScaleWidth ¶
ScaleWidth converts a width measured by MeasureText (using the basicfont fallback) to the approximate width at the target font's proportions. This compensates for the monospace basicfont being wider than proportional fonts like Tahoma or Arial.
func ScreenDpi ¶
func ScreenDpi() int
ScreenDpi returns the screen DPI used by the report engine. In the Go port this is always 96 (the report internal unit is 96-dpi pixels). Matches C# DrawUtils.ScreenDpi (DrawUtils.cs:24-31).
func ScreenDpiFX ¶
func ScreenDpiFX() float32
ScreenDpiFX returns the DPI scaling factor relative to 96 dpi. Formula: 96 / ScreenDpi. Because ScreenDpi is always 96 in the Go port, this returns 1.0. The function is provided so that ported C# code that references DrawUtils.ScreenDpiFX compiles without change. Matches C# DrawUtils.ScreenDpiFX (DrawUtils.cs:34-42).
func SetDefaultPassword ¶
func SetDefaultPassword(pwd string)
SetDefaultPassword changes the default encryption password.
func SetUIScale ¶
func SetUIScale(v float32)
SetUIScale sets the additional UI scale factor. The value is clamped to [1.0, 1.5]. Matches C# DrawUtils.UIScale setter (DrawUtils.cs:62-68).
func ShortPropCode ¶
ShortPropCode returns the short code for a full property name. Returns ("", false) if no abbreviation is registered.
func ShortPropName ¶
ShortPropName returns the full property name for a short code. Returns ("", false) if the code is not recognised.
func StripHtmlTags ¶
StripHtmlTags removes all HTML tags from s and decodes basic entities. Use this when you need plain text from an HTML-markup string.
func StripRTF ¶
StripRTF converts RTF-formatted text to plain text by removing all RTF control words, control symbols, and group delimiters. It preserves the visible text content and converts \par / \line to newlines.
It handles the basic subset used by FastReport RichObject:
- Nested groups { … }
- Control words: \rtf1, \ansi, \b, \i, \u, \par, \pard, \line, \tab, etc.
- Unicode escapes: \uN? (N = UTF-16 code point)
- Hex escapes: \'XX
- Destination groups: {\*\keyword …} are skipped entirely
The caller should evaluate bracket expressions AFTER stripping RTF, so that the expression evaluator only sees plain text.
func TabStopPositions ¶
TabStopPositions returns the positions (in pixels) of n evenly spaced tab stops given a tabOffset (position of the first stop) and tabSize (spacing).
This is a convenience helper — the C# equivalent is StringFormat.GetTabStops.
func UIScale ¶
func UIScale() float32
UIScale returns the additional UI scale factor applied to report forms. Valid range is 1.0 to 1.5. Defaults to 1.0. Matches C# DrawUtils.UIScale (DrawUtils.cs:53-69).
func UnpackStream ¶
func UnpackStream(assembly, name string) (io.ReadCloser, error)
UnpackStream returns the gzip-decompressed content of the named resource in the given assembly as an in-memory reader. The decompressed bytes are fully buffered in memory, matching the C# implementation which copies to a MemoryStream before returning.
Returns (nil, nil) when the resource is not registered.
C# equivalent: ResourceLoader.UnpackStream(assembly, resource)
func UnpackStreamFR ¶
func UnpackStreamFR(name string) (io.ReadCloser, error)
UnpackStreamFR returns the gzip-decompressed content of a named resource in the default "FastReport" assembly.
C# equivalent: ResourceLoader.UnpackStream(resource)
func UnzipData ¶
UnzipData decompresses raw DEFLATE-compressed data produced by ZipData or any compatible DeflateStream writer.
func UnzipStream ¶
UnzipStream reads raw DEFLATE-compressed data from r and writes the decompressed bytes to w.
func WingdingsToUnicode ¶
WingdingsToUnicode converts a string encoded in the Wingdings or Webdings symbol font to its Unicode Private Use Area equivalents. Each character in the range U+0020–U+00FF is shifted to U+F020–U+F0FF. Mirrors C# WingdingsToUnicodeConverter.Convert (HtmlTextRenderer.cs line 3210).
func WrapText ¶
WrapText wraps text to fit within maxWidth pixels using the given font face. Returns a slice of lines. Hard newlines in the source are always honoured.
Types ¶
type AncestorError ¶
type AncestorError struct {
Name string
}
AncestorError is returned when trying to rename an object from an ancestor report.
func (*AncestorError) Error ¶
func (e *AncestorError) Error() string
type BaselineType ¶
type BaselineType int
BaselineType indicates character vertical placement relative to the line baseline. Mirrors HtmlTextRenderer.BaseLine in C# (HtmlTextRenderer.cs, line 1304).
const ( // BaselineNormal is the default baseline (no vertical shift). BaselineNormal BaselineType = iota // BaselineSubscript places the run below the normal baseline (via <sub>). BaselineSubscript // BaselineSuperscript places the run above the normal baseline (via <sup>). BaselineSuperscript )
type ClassError ¶
type ClassError struct {
Name string
}
ClassError is returned when deserializing an unknown object type.
func (*ClassError) Error ¶
func (e *ClassError) Error() string
type Collection ¶
type Collection[T any] struct { // contains filtered or unexported fields }
Collection is a generic ordered collection of report objects. It is the Go equivalent of FRCollectionBase.
func (*Collection[T]) All ¶
func (c *Collection[T]) All() iter.Seq2[int, T]
All returns an iterator over all items (Go 1.23 range-over-func).
func (*Collection[T]) Clear ¶
func (c *Collection[T]) Clear()
Clear removes all items from the collection.
func (*Collection[T]) Contains ¶
func (c *Collection[T]) Contains(item T, eq func(a, b T) bool) bool
Contains returns true if item is in the collection using eq.
func (*Collection[T]) Get ¶
func (c *Collection[T]) Get(i int) T
Get returns the item at index i. Panics if i is out of range.
func (*Collection[T]) IndexOf ¶
func (c *Collection[T]) IndexOf(item T, eq func(a, b T) bool) int
IndexOf returns the index of item using eq, or -1 if not found.
func (*Collection[T]) Insert ¶
func (c *Collection[T]) Insert(index int, item T)
Insert inserts item at position index, shifting subsequent items right.
func (*Collection[T]) Len ¶
func (c *Collection[T]) Len() int
Len returns the number of items in the collection.
func (*Collection[T]) Remove ¶
func (c *Collection[T]) Remove(item T, eq func(a, b T) bool) bool
Remove removes the first occurrence of item from the collection using the provided equality function eq.
func (*Collection[T]) RemoveAt ¶
func (c *Collection[T]) RemoveAt(i int)
RemoveAt removes the item at index i.
func (*Collection[T]) SetOrder ¶
func (c *Collection[T]) SetOrder(item T, order int, eq func(a, b T) bool)
SetOrder moves item to the specified position in the collection. Uses eq to find the item.
func (*Collection[T]) Slice ¶
func (c *Collection[T]) Slice() []T
Slice returns a copy of the underlying slice.
type CompilerError ¶
type CompilerError struct {
Msg string
Errors []CompilerErrorInfo
}
CompilerError is returned when an expression cannot be compiled.
func (*CompilerError) Error ¶
func (e *CompilerError) Error() string
type CompilerErrorInfo ¶
CompilerErrorInfo holds a single expression compiler error location.
type Config ¶
type Config struct {
// PreparedCompressed enables compression in prepared report files (fpx).
// Mirrors C# Config.PreparedCompressed (Config.cs line 99-103). Default: true.
PreparedCompressed bool
// ForbidLocalData prevents local file paths in XML/CSV data sources.
// Mirrors C# Config.ForbidLocalData (Config.cs line 80-84).
ForbidLocalData bool
// TempFolder overrides the system temporary directory.
// When empty, GetTempFolder() returns os.TempDir().
// Mirrors C# Config.TempFolder (Config.cs line 181-185) where null means use system temp.
TempFolder string
// RightToLeft enables right-to-left text direction.
// Mirrors C# Config.RightToLeft (Config.cs line 161-165).
RightToLeft bool
// contains filtered or unexported fields
}
Config holds global configuration settings for the go-fastreport library. Access via the package-level DefaultConfig variable. Ported from C# FastReport.Utils.Config (Config.cs) and its Core/OpenSource partial files.
func (*Config) CreateTempFile ¶
CreateTempFile creates a temporary file and returns its path. When dir is empty, the file is created in GetTempFolder(). Mirrors C# Config.CreateTempFile(string dir) (Config.cs lines 284-289):
if (String.IsNullOrEmpty(dir)) return GetTempFileName(); return Path.Combine(dir, Path.GetRandomFileName());
func (*Config) GetConfiguredTempFolder ¶
GetConfiguredTempFolder returns the raw TempFolder field without the os.TempDir() fallback. An empty string means "use the system temp dir". Use GetTempFolder() to get the effective path.
func (*Config) GetForbidLocalData ¶
GetForbidLocalData returns whether local data file paths are forbidden.
func (*Config) GetPreparedCompressed ¶
GetPreparedCompressed returns whether prepared reports are compressed.
func (*Config) GetRightToLeft ¶
GetRightToLeft returns whether right-to-left mode is enabled.
func (*Config) GetTempFolder ¶
GetTempFolder returns the effective temporary folder path. When TempFolder has not been set (empty string), it returns os.TempDir(). Mirrors C# Config.GetTempFolder() (Config.cs lines 291-293):
return TempFolder == null ? GetTempPath() : TempFolder;
func (*Config) SetForbidLocalData ¶
SetForbidLocalData sets whether local data file paths are forbidden.
func (*Config) SetPreparedCompressed ¶
SetPreparedCompressed sets whether prepared reports are compressed.
func (*Config) SetRightToLeft ¶
SetRightToLeft sets whether right-to-left mode is enabled.
func (*Config) SetTempFolder ¶
SetTempFolder sets the temporary folder path override. Pass an empty string to revert to the system temp directory.
func (*Config) TempFilePath ¶
TempFilePath creates a unique temporary file inside GetTempFolder() and returns its path. The name embeds a timestamp for human readability, matching C# Config.GetTempFileName() (Config.cs lines 411-414):
return Path.Combine(GetTempFolder(),
SystemFake.DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss-") + Path.GetRandomFileName());
type DataNotInitializedError ¶
type DataNotInitializedError struct {
Alias string
}
DataNotInitializedError is returned when accessing a data source that has not been initialized.
func (*DataNotInitializedError) Error ¶
func (e *DataNotInitializedError) Error() string
type DataTableError ¶
type DataTableError struct {
Alias string
}
DataTableError is returned when a table data source is not properly configured.
func (*DataTableError) Error ¶
func (e *DataTableError) Error() string
type DecryptError ¶
type DecryptError struct{}
DecryptError is returned when loading an encrypted report with the wrong password.
func (*DecryptError) Error ¶
func (e *DecryptError) Error() string
type DuplicateNameError ¶
type DuplicateNameError struct {
Name string
}
DuplicateNameError is returned when an object with the same name already exists.
func (*DuplicateNameError) Error ¶
func (e *DuplicateNameError) Error() string
type FRColumnInfo ¶
type FRColumnInfo struct {
// TypeName is a Go type descriptor string (e.g. "string", "int32").
TypeName string
// Length is the number of rows.
Length int
}
FRColumnInfo holds the type name and row count for a data column. Mirrors FRColumnInfo in FRRandom.cs.
type FRRandom ¶
type FRRandom struct {
// contains filtered or unexported fields
}
FRRandom is a pseudo-random generator used for test-data generation. It is safe for concurrent use.
func NewFRRandom ¶
func NewFRRandom() *FRRandom
NewFRRandom creates a new FRRandom instance seeded with the current time. Mirrors the C# constructor: random = new Random()
func NewFRRandomSeed ¶
NewFRRandomSeed creates a new FRRandom instance with an explicit seed. Useful in tests to produce deterministic output.
func (*FRRandom) GetRandomValue ¶
GetRandomValue returns a randomized value of the same type as source. Supported types: string, int, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64, time.Time, time.Duration, []byte. For unsupported types the original source value is returned unchanged. Mirrors FRRandom.GetRandomObject(object source, Type type).
func (*FRRandom) NextByte ¶
NextByte returns a random byte in [0, 254]. Mirrors FRRandom.NextByte() — C# uses random.Next(byte.MaxValue) which is exclusive upper bound 255, so the range is [0, 254].
func (*FRRandom) NextBytes ¶
NextBytes returns a slice of n random bytes. Mirrors FRRandom.NextBytes(int number).
func (*FRRandom) NextChar ¶
NextChar returns a random rune in [0, 65534]. Mirrors FRRandom.NextChar() — C# uses random.Next(char.MaxValue) which is exclusive upper bound 65535, so the range is [0, 65534].
func (*FRRandom) NextDay ¶
NextDay returns a random day between start and today (inclusive of start, exclusive of today because C# uses random.Next(range) which is [0, range-1]). If start is after today, today is returned. Mirrors FRRandom.NextDay(DateTime start).
func (*FRRandom) NextDigit ¶
NextDigit returns a random int in [0, 9]. Mirrors FRRandom.NextDigit().
func (*FRRandom) NextDigitMax ¶
NextDigitMax returns a random int in [0, max]. Mirrors FRRandom.NextDigit(int max).
func (*FRRandom) NextDigitRange ¶
NextDigitRange returns a random int in [min, max]. Mirrors FRRandom.NextDigit(int min, int max).
func (*FRRandom) NextDigits ¶
NextDigits returns a string of n random digits 0–9. Returns "" when number <= 0. Mirrors FRRandom.NextDigits(int number).
func (*FRRandom) NextLetter ¶
NextLetter returns a random letter in the same case as source. Non-letter runes are returned unchanged. Mirrors FRRandom.NextLetter(char source).
func (*FRRandom) NextTimeSpanBetweenHours ¶
NextTimeSpanBetweenHours returns a random duration between startHour and endHour (clamped to [0, 24]). The returned duration is relative to midnight. Mirrors FRRandom.NextTimeSpanBetweenHours(int start, int end).
func (*FRRandom) RandomizeDecimal ¶
RandomizeDecimal returns a random float64 with the same digit layout as source (same integer-part length, same fractional-part length, same sign). Mirrors FRRandom.RandomizeDecimal(decimal source).
The C# implementation builds a string representation that respects the digit count and scientific notation suffix of the source value. We mirror that algorithm using float64 and strconv.
func (*FRRandom) RandomizeDouble ¶
RandomizeDouble returns a random float64 with the same digit layout as source. Mirrors FRRandom.RandomizeDouble(double source).
func (*FRRandom) RandomizeFloat32 ¶
RandomizeFloat32 returns a random float32 with the same digit layout as source. Mirrors FRRandom.RandomizeFloat(float source).
func (*FRRandom) RandomizeInt16 ¶
RandomizeInt16 returns a random int16 with the same number of digits as source. Mirrors FRRandom.RandomizeInt16(Int16 source).
func (*FRRandom) RandomizeInt32 ¶
RandomizeInt32 returns a random int32 with the same number of digits as source. Mirrors FRRandom.RandomizeInt32(Int32 source).
func (*FRRandom) RandomizeInt64 ¶
RandomizeInt64 returns a random int64 with the same number of digits as source. Mirrors FRRandom.RandomizeInt64(Int64 source).
func (*FRRandom) RandomizeSByte ¶
RandomizeSByte returns a random int8 with the same number of digits as source. Mirrors FRRandom.RandomizeSByte(SByte source).
func (*FRRandom) RandomizeString ¶
RandomizeString returns a string of the same length as source where:
- whitespace is preserved,
- letters are replaced by random letters of the same case,
- digits are replaced by random digits 0–9,
- all other characters are preserved.
Mirrors FRRandom.RandomizeString(string source).
func (*FRRandom) RandomizeUInt16 ¶
RandomizeUInt16 returns a random uint16 with the same number of digits as source. Mirrors FRRandom.RandomizeUInt16(UInt16 source).
func (*FRRandom) RandomizeUInt32 ¶
RandomizeUInt32 returns a random uint32 with the same number of digits as source. Mirrors FRRandom.RandomizeUInt32(UInt32 source).
func (*FRRandom) RandomizeUInt64 ¶
RandomizeUInt64 returns a random uint64 with the same number of digits as source. Mirrors FRRandom.RandomizeUInt64(UInt64 source).
type FRRandomFieldValue ¶
FRRandomFieldValue stores the original and randomized value for a field. Mirrors FRRandomFieldValue in FRRandom.cs.
type FRRandomFieldValueCollection ¶
type FRRandomFieldValueCollection struct {
// contains filtered or unexported fields
}
FRRandomFieldValueCollection is an ordered list of FRRandomFieldValue entries. Mirrors FRRandomFieldValueCollection in FRRandom.cs.
func (*FRRandomFieldValueCollection) Add ¶
func (c *FRRandomFieldValueCollection) Add(v FRRandomFieldValue)
Add appends a value to the collection.
func (*FRRandomFieldValueCollection) ContainsOrigin ¶
func (c *FRRandomFieldValueCollection) ContainsOrigin(origin any) bool
ContainsOrigin returns true if an entry with the same origin exists. Uses == for equality (mirrors C# reference / value equality).
func (*FRRandomFieldValueCollection) ContainsRandom ¶
func (c *FRRandomFieldValueCollection) ContainsRandom(randVal any) bool
ContainsRandom returns true if an entry with the same random value exists.
func (*FRRandomFieldValueCollection) GetRandom ¶
func (c *FRRandomFieldValueCollection) GetRandom(origin any) any
GetRandom returns the random value stored for the given origin. If not found, origin itself is returned.
type FastNameCreator ¶
type FastNameCreator struct {
// contains filtered or unexported fields
}
FastNameCreator generates unique component names efficiently. It works by tracking the highest numbered suffix seen for each base name.
Usage:
creator := NewFastNameCreator(existingNames) creator.CreateUniqueName(obj)
func NewFastNameCreator ¶
func NewFastNameCreator(objects []ObjectNamer) *FastNameCreator
NewFastNameCreator creates a FastNameCreator pre-seeded with the names of the provided objects so that generated names do not clash with existing ones.
func (*FastNameCreator) CreateUniqueName ¶
func (nc *FastNameCreator) CreateUniqueName(obj ObjectNamer)
CreateUniqueName assigns a unique name to obj based on its BaseName(). For example, if BaseName() == "Text" and names "Text1" and "Text2" exist, it will set the name to "Text3".
type FastString ¶
type FastString struct {
// contains filtered or unexported fields
}
FastString is an optimized string builder that wraps strings.Builder. It is the Go equivalent of FastReport's FastString class and provides a fluent API for building strings incrementally without repeated allocations.
func (*FastString) Append ¶
func (fs *FastString) Append(s string) *FastString
Append appends s to the builder and returns the receiver for chaining.
func (*FastString) AppendLine ¶
func (fs *FastString) AppendLine(s string) *FastString
AppendLine appends s followed by a newline character ("\n") and returns the receiver for chaining.
func (*FastString) AppendRune ¶
func (fs *FastString) AppendRune(r rune) *FastString
AppendRune appends the Unicode code point r and returns the receiver for chaining.
func (*FastString) IsEmpty ¶
func (fs *FastString) IsEmpty() bool
IsEmpty reports whether the builder contains no characters.
func (*FastString) Len ¶
func (fs *FastString) Len() int
Len returns the number of bytes currently accumulated.
func (*FastString) Reset ¶
func (fs *FastString) Reset()
Reset clears the builder so it can be reused without allocating a new one.
func (*FastString) String ¶
func (fs *FastString) String() string
String returns the accumulated string.
type FileFormatError ¶
type FileFormatError struct {
Detail string
}
FileFormatError is returned when loading a malformed FRX report file.
func (*FileFormatError) Error ¶
func (e *FileFormatError) Error() string
type FileStorageService ¶
type FileStorageService struct {
// BaseDir is prepended to relative paths. If empty, paths are used as-is.
BaseDir string
}
FileStorageService is a StorageService backed by the local filesystem. The optional BaseDir is prepended to all relative paths.
func NewFileStorageService ¶
func NewFileStorageService(baseDir string) *FileStorageService
NewFileStorageService creates a FileStorageService rooted at baseDir.
func (*FileStorageService) Exists ¶
func (f *FileStorageService) Exists(path string) bool
Exists reports whether the file at path exists.
func (*FileStorageService) Load ¶
func (f *FileStorageService) Load(path string) ([]byte, error)
Load reads the file at path (relative to BaseDir) and returns its bytes.
func (*FileStorageService) Reader ¶
func (f *FileStorageService) Reader(path string) (io.ReadCloser, error)
Reader opens the file at path for reading.
func (*FileStorageService) Save ¶
func (f *FileStorageService) Save(path string, data []byte) error
Save writes data to path (relative to BaseDir), creating parent directories as needed.
func (*FileStorageService) Writer ¶
func (f *FileStorageService) Writer(path string) (io.WriteCloser, error)
Writer opens the file at path for writing, creating it or truncating it.
type FloatCollection ¶
type FloatCollection []float32
FloatCollection is a serializable slice of float32 values. It is the Go equivalent of FastReport.Utils.FloatCollection.
The string format is a comma-separated list of decimal values, e.g. "2,4,2,4". Leading/trailing whitespace around values is trimmed during parsing.
func MustParseFloatCollection ¶
func MustParseFloatCollection(s string) FloatCollection
MustParseFloatCollection parses s and panics on error (use in tests/constants).
func ParseFloatCollection ¶
func ParseFloatCollection(s string) (FloatCollection, error)
ParseFloatCollection parses a comma-separated string into a FloatCollection. Empty string returns an empty collection without error.
func (*FloatCollection) Add ¶
func (fc *FloatCollection) Add(v float32)
Add appends a value to the collection.
func (*FloatCollection) AddRange ¶
func (fc *FloatCollection) AddRange(values []float32)
AddRange appends all values from values to the collection. Mirrors C# FloatCollection.AddRange (FloatCollection.cs line 28-33).
func (*FloatCollection) Assign ¶
func (fc *FloatCollection) Assign(src FloatCollection)
Assign replaces the collection contents with a copy of src. Mirrors C# FloatCollection.Assign (FloatCollection.cs line 97-103).
func (FloatCollection) Contains ¶
func (fc FloatCollection) Contains(value float32) bool
Contains returns true when value is in the collection (within 0.01). Mirrors C# FloatCollection.Contains (FloatCollection.cs line 88-90).
func (FloatCollection) Get ¶
func (fc FloatCollection) Get(i int) float32
Get returns the element at index i.
func (FloatCollection) IndexOf ¶
func (fc FloatCollection) IndexOf(value float32) int
IndexOf returns the zero-based index of the first element within 0.01 of value, or -1 if not found. Mirrors C# FloatCollection.IndexOf (FloatCollection.cs line 73-81).
func (*FloatCollection) Insert ¶
func (fc *FloatCollection) Insert(index int, value float32)
Insert inserts value at the given index, shifting later elements right. Mirrors C# FloatCollection.Insert (FloatCollection.cs line 51-53).
func (FloatCollection) Len ¶
func (fc FloatCollection) Len() int
Len returns the number of elements.
func (*FloatCollection) Remove ¶
func (fc *FloatCollection) Remove(value float32)
Remove removes the first occurrence of value (within 0.01) from the collection. Mirrors C# FloatCollection.Remove (FloatCollection.cs line 60-64).
func (*FloatCollection) RemoveAt ¶
func (fc *FloatCollection) RemoveAt(index int)
RemoveAt removes the element at the given index. Mirrors C# FloatCollection.RemoveAt (inherited from CollectionBase).
func (FloatCollection) String ¶
func (fc FloatCollection) String() string
String returns the comma-separated string representation.
type FontDescriptor ¶
FontDescriptor identifies a font by name, size and style.
type FontManager ¶
type FontManager struct {
// contains filtered or unexported fields
}
FontManager manages font loading and caching. It is the Go equivalent of FastReport's FontManager.
func NewFontManager ¶
func NewFontManager() *FontManager
NewFontManager creates a new FontManager with an empty cache.
func (*FontManager) AddFace ¶
func (fm *FontManager) AddFace(desc FontDescriptor, face font.Face)
AddFace registers a font face for a descriptor.
func (*FontManager) GetFace ¶
func (fm *FontManager) GetFace(desc FontDescriptor) font.Face
GetFace returns a font.Face for the given descriptor. It attempts to load the actual TrueType font from the system to match C# GDI+ MeasureString metrics. Falls back to basicfont.Face7x13 if the font cannot be loaded.
type GroupHeaderNoConditionError ¶
type GroupHeaderNoConditionError struct {
Name string
}
GroupHeaderNoConditionError is returned when a GroupHeader has no group condition.
func (*GroupHeaderNoConditionError) Error ¶
func (e *GroupHeaderNoConditionError) Error() string
type HtmlLine ¶
type HtmlLine struct {
Runs []HtmlRun
}
HtmlLine is one visual line produced by the HTML text renderer.
type HtmlRun ¶
type HtmlRun struct {
// Text is the plain-text content of this run.
Text string
// Font is the font to use for this run.
Font style.Font
// Color is the text foreground color.
Color color.RGBA
// BackgroundColor is the text background highlight color (from CSS background-color).
// An alpha of 0 means no background is applied.
BackgroundColor color.RGBA
// Underline indicates underlined text.
Underline bool
// Strikeout indicates struck-out text.
Strikeout bool
// LineBreak is true when this run ends with an explicit line break.
LineBreak bool
// Baseline indicates subscript/superscript placement.
// Mirrors HtmlTextRenderer.BaseLine (HtmlTextRenderer.cs, line 1304).
Baseline BaselineType
}
HtmlRun is a styled run of text produced by the HTML text renderer. It represents a contiguous span of text with uniform styling.
type HtmlTextRenderer ¶
type HtmlTextRenderer struct {
// contains filtered or unexported fields
}
HtmlTextRenderer parses inline HTML markup in text objects and produces styled runs for measurement and rendering. It is the Go equivalent of FastReport.Utils.HtmlTextRenderer.
Supported tags: <b>, <i>, <u>, <s>, <strike>, <br>, <font>, <span>, <sub>, <sup>, plus style="color:…;font-size:…" on span/font. Entities: & < > "
func NewHtmlTextRenderer ¶
func NewHtmlTextRenderer(htmlText string, baseFont style.Font, baseColor color.RGBA) *HtmlTextRenderer
NewHtmlTextRenderer creates a renderer for the given HTML text, base font, and base foreground colour. Call Lines() to access the parsed output.
func (*HtmlTextRenderer) Lines ¶
func (r *HtmlTextRenderer) Lines() []HtmlLine
Lines returns the parsed visual lines.
func (*HtmlTextRenderer) MeasureHeight ¶
func (r *HtmlTextRenderer) MeasureHeight(width float32) float32
MeasureHeight returns the total height in pixels needed to render the HTML text in a box of the given width using the base font.
func (*HtmlTextRenderer) PlainText ¶
func (r *HtmlTextRenderer) PlainText() string
PlainText returns the plain-text content with all HTML tags removed.
type ImageFormat ¶
type ImageFormat int
ImageFormat identifies the output encoding for ImageToBytes.
const ( ImageFormatPNG ImageFormat = iota ImageFormatJPEG // quality 90 )
type ImageLoadError ¶
type ImageLoadError struct {
Cause error
}
ImageLoadError is returned when an image cannot be loaded.
func (*ImageLoadError) Error ¶
func (e *ImageLoadError) Error() string
func (*ImageLoadError) Unwrap ¶
func (e *ImageLoadError) Unwrap() error
type MemoryStorageService ¶
type MemoryStorageService struct {
// contains filtered or unexported fields
}
MemoryStorageService is a StorageService backed by an in-memory map. Useful for testing and embedded scenarios.
func NewMemoryStorageService ¶
func NewMemoryStorageService() *MemoryStorageService
NewMemoryStorageService creates an empty MemoryStorageService.
func (*MemoryStorageService) Exists ¶
func (m *MemoryStorageService) Exists(path string) bool
Exists reports whether path exists in the memory store.
func (*MemoryStorageService) Load ¶
func (m *MemoryStorageService) Load(path string) ([]byte, error)
Load returns the bytes stored at path, or an error if not found.
func (*MemoryStorageService) Put ¶
func (m *MemoryStorageService) Put(path string, data []byte)
Put adds or replaces the resource at path with data.
func (*MemoryStorageService) Reader ¶
func (m *MemoryStorageService) Reader(path string) (io.ReadCloser, error)
Reader returns an io.ReadCloser over the stored bytes.
func (*MemoryStorageService) Save ¶
func (m *MemoryStorageService) Save(path string, data []byte) error
Save stores data under path.
func (*MemoryStorageService) Writer ¶
func (m *MemoryStorageService) Writer(path string) (io.WriteCloser, error)
Writer returns an io.WriteCloser that commits to the memory store when closed.
type Namer ¶
type Namer interface {
Name() string
}
Namer is the minimal interface that collection items must implement. Any report object that has a Name satisfies this.
type NotValidIdentifierError ¶
type NotValidIdentifierError struct {
Value string
}
NotValidIdentifierError is returned when an object name is not a valid identifier.
func (*NotValidIdentifierError) Error ¶
func (e *NotValidIdentifierError) Error() string
type ObjectNamer ¶
type ObjectNamer interface {
// BaseName returns the base name prefix (e.g. "Text" for "Text1").
BaseName() string
// Name returns the current object name.
Name() string
// SetName sets the object name.
SetName(name string)
}
ObjectNamer is the minimal interface required by FastNameCreator.
type ParentError ¶
ParentError is returned when a child object cannot be added to a parent.
func (*ParentError) Error ¶
func (e *ParentError) Error() string
type PointF ¶
type PointF struct {
X, Y float32
}
PointF represents a floating-point point, matching C# System.Drawing.PointF.
type RectF ¶
type RectF struct {
X, Y, Width, Height float32
}
RectF represents a floating-point rectangle, matching C# System.Drawing.RectangleF.
type ReportValidator ¶
type ReportValidator struct {
// contains filtered or unexported fields
}
ReportValidator validates a report definition by applying a set of rules. Rules are functions that receive a generic "report snapshot" via the ValidatableReport interface and return any issues found.
func NewReportValidator ¶
func NewReportValidator() *ReportValidator
NewReportValidator creates a ReportValidator with the default rule set.
func (*ReportValidator) AddRule ¶
func (rv *ReportValidator) AddRule(rule ValidationRule)
AddRule appends a custom validation rule.
func (*ReportValidator) Validate ¶
func (rv *ReportValidator) Validate(r ValidatableReport) []ValidationIssue
Validate runs all rules against r and returns the collected issues.
type SizeF ¶
type SizeF struct {
Width, Height float32
}
SizeF represents a floating-point size, matching C# System.Drawing.SizeF.
type SizeMode ¶
type SizeMode int
SizeMode mirrors object.SizeMode for use in ResizeImage without creating an import cycle.
type StorageService ¶
type StorageService interface {
// Load reads the resource at the given path and returns its bytes.
Load(path string) ([]byte, error)
// Save writes data to the given path.
Save(path string, data []byte) error
// Exists reports whether the resource at path exists.
Exists(path string) bool
// Reader opens the resource at path for streaming reads.
// Callers must close the returned ReadCloser.
Reader(path string) (io.ReadCloser, error)
// Writer opens the resource at path for streaming writes.
// Callers must close the returned WriteCloser.
Writer(path string) (io.WriteCloser, error)
}
StorageService is the report storage abstraction. Implementations may load and save report data from local files, databases, object stores (S3, GCS), or any other backend.
This is the Go equivalent of FastReport.Utils.StorageService.
type TextMeasurement ¶
type TextMeasurement struct {
Width float32 // in pixels
Height float32 // in pixels
Lines int // number of lines
}
TextMeasurement holds the results of text measurement.
func MeasureString ¶
func MeasureString(text string, face font.Face, maxWidth float32) TextMeasurement
MeasureString measures the dimensions of text rendered with the given face. If maxWidth > 0, text is wrapped at word boundaries.
type UnknownNameError ¶
type UnknownNameError struct {
Value string
}
UnknownNameError is returned when an unknown name is supplied.
func (*UnknownNameError) Error ¶
func (e *UnknownNameError) Error() string
type Validatable ¶
type Validatable interface {
Validate() []ValidationIssue
}
Validatable is implemented by report objects that can report their own issues.
type ValidatableReport ¶
type ValidatableReport interface {
// PageCount returns the number of report pages.
PageCount() int
// BandNames returns the names of all bands across all pages.
BandNames() []string
// DataSourceNames returns the registered data source names.
DataSourceNames() []string
// TextExpressions returns all [bracket] expressions found in text objects.
TextExpressions() []string
// ParameterNames returns the registered parameter names.
ParameterNames() []string
// ObjectNames returns the names of all named report objects (components,
// bands, pages). Used for duplicate-name detection, matching the C#
// Validator.ValidateReport duplicate-name loop (Validator.cs lines 127–145).
ObjectNames() []string
}
ValidatableReport is the interface that a report must implement to be validated. Using an interface instead of a concrete type avoids an import cycle between utils and reportpkg.
type ValidationIssue ¶
type ValidationIssue struct {
// Severity is the classification of the finding.
Severity ValidationSeverity
// ObjectName is the name of the report object involved (may be empty).
ObjectName string
// Message describes the problem.
Message string
}
ValidationIssue describes a single validation finding.
func (ValidationIssue) Error ¶
func (v ValidationIssue) Error() string
type ValidationRule ¶
type ValidationRule func(r ValidatableReport) []ValidationIssue
ValidationRule is a single validation check.
type ValidationSeverity ¶
type ValidationSeverity int
ValidationSeverity indicates the severity of a validation finding.
const ( // ValidationError is a problem that will prevent correct report output. ValidationError ValidationSeverity = iota // ValidationWarning is a condition that may produce unexpected output. ValidationWarning // ValidationInfo is an informational hint (not necessarily a problem). ValidationInfo )
func (ValidationSeverity) String ¶
func (s ValidationSeverity) String() string
type Value ¶
type Value struct {
// contains filtered or unexported fields
}
Value is a flexible value container analogous to the C# object/any used for dynamic data binding values in data sources and expressions. A zero Value holds nil.
func (Value) Bool ¶
Bool attempts to extract a bool from the value. The second return value is false when the underlying type is not bool.
func (Value) Equals ¶
Equals reports whether val and other contain equal values using Go's == operator on the underlying any values. For slice/map types that are not comparable, Equals returns false rather than panicking.
func (Value) Float64 ¶
Float64 attempts to extract a float64 from the value. It handles all integer and float types. The second return value is false when conversion is not possible.
func (Value) Int ¶
Int attempts to extract an integer from the value. It handles int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, and float64, truncating fractional parts as needed. The second return value is false when conversion is not possible.
type ZipArchive ¶
type ZipArchive struct {
// contains filtered or unexported fields
}
ZipArchive is a simple in-memory ZIP archive builder. Mirrors the FastReport .NET ZipArchive helper used to construct XLSX/ODS files.
func (*ZipArchive) AddEntry ¶
func (za *ZipArchive) AddEntry(name string, data []byte) error
AddEntry adds a named entry with the given byte content.
func (*ZipArchive) AddEntryFromStream ¶
func (za *ZipArchive) AddEntryFromStream(name string, r io.Reader) error
AddEntryFromStream adds a named entry by reading from r.
func (*ZipArchive) Bytes ¶
func (za *ZipArchive) Bytes() ([]byte, error)
Bytes closes the archive (if not already closed) and returns the ZIP bytes.
Source Files
¶
- collection.go
- color.go
- compressor.go
- config.go
- converter.go
- crc32.go
- crypto.go
- doc.go
- drawutils.go
- errors.go
- faststring.go
- floatcollection.go
- font.go
- frrandom.go
- htmltext.go
- image.go
- locale.go
- murmur3.go
- namecreator.go
- resource_loader.go
- rtf.go
- shortprops.go
- storage.go
- text.go
- textmeasure.go
- textrenderer.go
- validator.go
- variant.go
- watermark_render.go
- zip.go