pdf

package
v4.0.0-...-f17068d Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Overview

Package pdf provides PDF generation and manipulation functionality. Font-related types have been extracted to the font subpackage. These type aliases maintain backward compatibility within the pdf package.

Index

Constants

This section is empty.

Variables

View Source
var (
	GetFontRegistry                      = font.GetFontRegistry
	NewFontRegistry                      = font.NewFontRegistry
	GetFontMetrics                       = font.GetFontMetrics
	GenerateFontObject                   = font.GenerateFontObject
	GenerateSimpleFontObject             = font.GenerateSimpleFontObject
	GenerateFontDescriptorObject         = font.GenerateFontDescriptorObject
	GenerateWidthsArrayObject            = font.GenerateWidthsArrayObject
	GenerateTrueTypeFontObjects          = font.GenerateTrueTypeFontObjects
	EncodeTextForCustomFont              = font.EncodeTextForCustomFont
	GetHelveticaFontResourceString       = font.GetHelveticaFontResourceString
	GetSimpleHelveticaFontResourceString = font.GetSimpleHelveticaFontResourceString
	GetAvailableFonts                    = font.GetAvailableFonts
	CompressFontData                     = font.CompressFontData
	IsCustomFont                         = font.IsCustomFont
	GetPDFAFontManager                   = font.GetPDFAFontManager
	IsStandardFont                       = font.IsStandardFont
	GetMappedFontName                    = font.GetMappedFontName
	GetLiberationFontPostScriptName      = font.GetLiberationFontPostScriptName
	ParseTTF                             = font.ParseTTF
	LoadTTFFromFile                      = font.LoadTTFFromFile
	LoadTTFFromData                      = font.LoadTTFFromData
	SubsetTTF                            = font.SubsetTTF
	SubsetTTFForText                     = font.SubsetTTFForText
	GetCompressBuffer                    = font.GetCompressBuffer
	GetZlibWriter                        = font.GetZlibWriter
	PutZlibWriter                        = font.PutZlibWriter
	CompressBufPool                      = &font.CompressBufPool
)

Function aliases for backward compatibility within this package.

Functions

func CalculateWrappedTextHeight

func CalculateWrappedTextHeight(lineCount int, fontSize float64, lineSpacing float64) float64

CalculateWrappedTextHeight calculates the total height needed for wrapped text lineCount: number of lines of text fontSize: font size in points lineSpacing: multiplier for line height (e.g., 1.2 for 120% line height) Returns the total height in points

func ConvertHTMLToImage

func ConvertHTMLToImage(req models.HTMLToImageRequest) ([]byte, error)

ConvertHTMLToImage converts HTML content to image using gochromedp.

func ConvertHTMLToPDF

func ConvertHTMLToPDF(req models.HTMLToPDFRequest) ([]byte, error)

ConvertHTMLToPDF converts HTML content to PDF using gochromedp.

func ConvertPDFDateToXMP

func ConvertPDFDateToXMP(pdfDate string) string

ConvertPDFDateToXMP converts a PDF date string (D:YYYYMMDDHHmmSSOHH'mm') to XMP format (YYYY-MM-DDTHH:mm:ss+HH:MM)

func CreateEncryptedImageXObject

func CreateEncryptedImageXObject(imgObj *ImageObject, objectID int, encryptor ImageEncryptor) string

CreateEncryptedImageXObject creates an encrypted PDF XObject for an image

func CreateImageXObject

func CreateImageXObject(imgObj *ImageObject, objectID int) string

CreateImageXObject creates a PDF XObject for an image

func CreateLinkAnnotation

func CreateLinkAnnotation(annot LinkAnnotation, pageManager *PageManager) int

CreateLinkAnnotation creates a PDF link annotation object with PDF/UA-2 structure For external links (URLs), it creates a /URI action For internal links (bookmarks), it creates a /GoTo action with named destination Returns the annotation object ID

func DrawCellLink(link string, cellX, cellY, cellWidth, cellHeight float64, pageManager *PageManager) int

DrawCellLink creates a link annotation for a cell if it has a link Returns the annotation object ID, or 0 if no link

func EstimateTextWidth

func EstimateTextWidth(resolvedName string, text string, fontSize float64, registry *CustomFontRegistry) float64

EstimateTextWidth estimates the width of text in points for a given font and size Uses actual glyph widths for custom fonts, approximation for standard fonts Takes resolvedFontName to avoid repeated lookups

func GenerateGrayICCProfileObject

func GenerateGrayICCProfileObject(objectID int, encryptor ObjectEncryptor) []byte

GenerateGrayICCProfileObject generates the ICC profile stream object for DeviceGray Returns the bytes to write to the PDF buffer

func GenerateICCProfileObject

func GenerateICCProfileObject(objectID int, encryptor ObjectEncryptor) []byte

GenerateICCProfileObject generates the ICC profile stream object for sRGB Returns the bytes to write to the PDF buffer

func GenerateOutputIntentObject

func GenerateOutputIntentObject(objectID int, iccProfileID int, encryptor ObjectEncryptor) string

GenerateOutputIntentObject generates the OutputIntent object for PDF/A-4

func GenerateTemplatePDF

func GenerateTemplatePDF(template models.PDFTemplate) ([]byte, error)

GenerateTemplatePDF generates a PDF document with multi-page support and embedded images. Returns the PDF bytes and any error encountered during generation.

func GenerateXMPMetadata

func GenerateXMPMetadata(documentID string, pdfDateStr string) string

GenerateXMPMetadata generates PDF/A-4 and PDF/UA-2 compliant XMP metadata (PDF 2.0 based) pdfDateStr should be in PDF format: D:YYYYMMDDHHmmSSOHH'mm'

func GenerateXMPMetadataObject

func GenerateXMPMetadataObject(objectID int, documentID string, pdfDateStr string, encryptor ObjectEncryptor) string

GenerateXMPMetadataObject generates the XMP metadata stream object pdfDateStr should be in PDF format: D:YYYYMMDDHHmmSSOHH'mm'

func GetSRGBICCProfile

func GetSRGBICCProfile() []byte

GetSRGBICCProfile returns the complete sRGB ICC profile

func IsFormFieldObject

func IsFormFieldObject(body []byte) bool

isFormFieldObject checks if an object body represents a form field

func MergePDFs

func MergePDFs(files [][]byte) ([]byte, error)

MergePDFs merges multiple PDF byte slices into a single PDF by parsing objects, remapping object numbers and building a new /Pages tree that references all page objects from the inputs. This avoids an external dependency.

func ParseLink(link string) (isExternal bool, uri string, dest string)

ParseLink parses a link string and determines if it's external or internal External links start with http://, https://, mailto:, etc. Internal links start with # followed by a bookmark name

func ResetImageCache

func ResetImageCache()

ResetImageCache clears the image cache (call between PDF generations if needed)

func WrapText

func WrapText(text string, resolvedFontName string, fontSize float64, maxWidth float64, registry *CustomFontRegistry) []string

WrapText splits text into multiple lines that fit within the specified maxWidth. It wraps on word boundaries when possible, and handles long words that exceed maxWidth. Returns a slice of strings, each representing one line of text.

Types

type AnnotStructElem

type AnnotStructElem struct {
	AnnotObjID      int // Annotation object ID
	StructParentIdx int // StructParent index for ParentTree
	PageIndex       int // Page where the annotation appears
}

AnnotStructElem tracks the relationship between an annotation and its structure element

type CustomFontRegistry

type CustomFontRegistry = font.CustomFontRegistry

Type aliases for backward compatibility within this package. External consumers should use the font package directly.

type FontDescriptor

type FontDescriptor = font.FontDescriptor

type FontMetrics

type FontMetrics = font.FontMetrics

type ImageEncryptor

type ImageEncryptor interface {
	EncryptStream(data []byte, objNum, genNum int) []byte
}

ImageEncryptor interface for encrypting image data

type ImageObject

type ImageObject struct {
	ObjectID     int
	Width        int
	Height       int
	ColorSpace   string
	BitsPerComp  int
	Filter       string
	ImageData    []byte
	ImageDataLen int
	IsForm       bool
}

ImageObject represents a PDF image XObject

func DecodeImageData

func DecodeImageData(base64Data string) (*ImageObject, error)

DecodeImageData decodes base64 image data and returns image information Uses caching to avoid re-decoding duplicate images

type LinkAnnotation

type LinkAnnotation struct {
	Rect      [4]float64 // [x1, y1, x2, y2] - annotation rectangle
	URI       string     // External URL (for /URI action)
	Dest      string     // Internal destination name (for /GoTo action)
	PageIndex int        // Target page index for internal links (0-based)
	DestY     float64    // Y coordinate on target page
}

LinkAnnotation represents a hyperlink annotation in a PDF

type LinkElement

type LinkElement struct {
	AnnotObjID int // The annotation object ID this link references
	PageIndex  int // Page where the annotation appears
	ObjectID   int // Assigned object ID for this structure element
}

LinkElement tracks a Link structure element for an annotation

type NamedDest

type NamedDest struct {
	PageIndex    int     // 0-based page index
	Y            float64 // Y position on page
	StructElemID int     // PDF/UA-2: Structure Element ID for /SD
}

NamedDest represents a named destination in the PDF

type ObjectEncryptor

type ObjectEncryptor interface {
	EncryptString(data []byte, objNum, genNum int) []byte
	EncryptStream(data []byte, objNum, genNum int) []byte
	GetEncryptDictionary(encryptObjID int) string
}

ObjectEncryptor defines the interface for encrypting PDF objects

type OutlineBuilder

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

OutlineBuilder builds the PDF outline (bookmarks) tree structure

func NewOutlineBuilder

func NewOutlineBuilder(pm *PageManager, encryptor ObjectEncryptor) *OutlineBuilder

NewOutlineBuilder creates a new outline builder

func (*OutlineBuilder) BuildOutlines

func (ob *OutlineBuilder) BuildOutlines(bookmarks []models.Bookmark) int

BuildOutlines creates the outline tree from bookmarks Returns the root outline object ID, or 0 if no bookmarks

func (*OutlineBuilder) GetNamedDestinations

func (ob *OutlineBuilder) GetNamedDestinations() (int, bool)

GetNamedDestinations returns the names dictionary object content for catalog This enables internal links to work with named destinations

func (*OutlineBuilder) RegisterNamedDest

func (ob *OutlineBuilder) RegisterNamedDest(name string, pageIndex int, y float64)

RegisterNamedDest registers a named destination for internal linking

type OutlineItem

type OutlineItem struct {
	ObjectID         int
	Title            string
	DestKey          string  // Named destination key for PDF/UA-2 compliance
	DestPageID       int     // Page object ID for destination
	DestY            float64 // Y position on destination page
	DestStructElemID int     // PDF/UA-2: Structure element ID for structure destination
	ParentID         int     // Parent outline item object ID
	PrevID           int     // Previous sibling object ID (0 if first)
	NextID           int     // Next sibling object ID (0 if last)
	FirstID          int     // First child object ID (0 if no children)
	LastID           int     // Last child object ID (0 if no children)
	Count            int     // Number of visible descendants (negative if closed)
	Open             bool    // Whether item is open (children visible)
}

OutlineItem represents a single outline entry with its object ID

type PDFAFontConfig

type PDFAFontConfig = font.PDFAFontConfig

type PDFAFontManager

type PDFAFontManager = font.PDFAFontManager

type PDFAHandler

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

PDFAHandler handles PDF/A compliance features, including metadata and color profiles.

func NewPDFAHandler

func NewPDFAHandler(config *models.PDFAConfig, pm *PageManager, encryptor ObjectEncryptor) *PDFAHandler

NewPDFAHandler creates a new PDF/A handler

func (*PDFAHandler) GenerateCatalogExtras

func (h *PDFAHandler) GenerateCatalogExtras() string

GenerateCatalogExtras returns additional catalog entries for PDF/A

func (*PDFAHandler) GenerateOutputIntent

func (h *PDFAHandler) GenerateOutputIntent(iccID, outputIntentID int) (int, []string, []byte)

GenerateOutputIntent generates the OutputIntent for PDF/A with embedded sRGB ICC profile Returns (outputIntentObjID, []strings of objects, compressedICCData)

func (*PDFAHandler) GenerateXMPMetadata

func (h *PDFAHandler) GenerateXMPMetadata(documentID string) (int, string)

GenerateXMPMetadata generates the XMP metadata stream for PDF/A

func (*PDFAHandler) GetConformanceLevel

func (h *PDFAHandler) GetConformanceLevel() (part int, conformance string)

GetConformanceLevel returns the PDF/A part and conformance level

func (*PDFAHandler) GetICCProfileObjID

func (h *PDFAHandler) GetICCProfileObjID() int

GetICCProfileObjID returns the ICC profile object ID

func (*PDFAHandler) GetMetadataObjID

func (h *PDFAHandler) GetMetadataObjID() int

GetMetadataObjID returns the metadata object ID

func (*PDFAHandler) GetOutputIntentObjID

func (h *PDFAHandler) GetOutputIntentObjID() int

GetOutputIntentObjID returns the output intent object ID

type PageDimensions

type PageDimensions struct {
	Width  float64
	Height float64
}

PageDimensions holds the current page dimensions and orientation

type PageManager

type PageManager struct {
	Pages                 []int   // List of page object IDs
	CurrentPageIndex      int     // Current page index (0-based)
	CurrentYPos           float64 // Current Y position on page
	PageDimensions        PageDimensions
	Margins               PageMargins
	ContentStreams        []bytes.Buffer       // Content for each page
	PageAnnots            [][]int              // Annotation Object IDs per page
	ExtraObjects          map[int]string       // Object ID -> Object Content
	NextObjectID          int                  // Counter for new objects
	ArlingtonCompatible   bool                 // Whether to use Arlington Model compliant fonts
	Structure             *StructureManager    // PDF/UA Structure Tree Manager
	NextAnnotStructParent int                  // PDF/UA-2: Counter for annotation StructParent values
	AnnotStructElems      []AnnotStructElem    // PDF/UA-2: Annotation to structure element mapping
	NamedDests            map[string]NamedDest // Map of named destinations for internal linking
	FontRegistry          *CustomFontRegistry  // Per-generation font registry for thread-safe font access
}

PageManager handles multi-page document generation

func NewPageManager

func NewPageManager(pageDims PageDimensions, margins PageMargins, arlingtonCompatible bool, fontRegistry *CustomFontRegistry) *PageManager

NewPageManager creates a new page manager with initial page

func (*PageManager) AddAnnotation

func (pm *PageManager) AddAnnotation(objID int)

AddAnnotation adds an annotation object ID to the current page

func (*PageManager) AddExtraObject

func (pm *PageManager) AddExtraObject(content string) int

AddExtraObject adds an extra object (like a widget) to the manager

func (*PageManager) AddLinkAnnotation

func (pm *PageManager) AddLinkAnnotation(x, y, w, h float64, url string)

AddLinkAnnotation adds a link annotation to the current page

func (*PageManager) AddLinkStructureElement

func (pm *PageManager) AddLinkStructureElement(annotObjID int, structParentIdx int)

AddLinkStructureElement creates a Link structure element for an annotation PDF/UA-2 requires link annotations to be wrapped in Link structure elements

func (*PageManager) AddNewPage

func (pm *PageManager) AddNewPage()

AddNewPage creates a new page when current page is full

func (*PageManager) CheckPageBreak

func (pm *PageManager) CheckPageBreak(requiredHeight float64) bool

CheckPageBreak determines if a new page is needed based on required height

func (*PageManager) ContentWidth

func (pm *PageManager) ContentWidth() float64

ContentWidth returns the available width for content on the current page.

func (*PageManager) GenerateBookmarks

func (pm *PageManager) GenerateBookmarks(bookmarks []models.Bookmark, xrefOffsets map[int]int, pdfBuffer *bytes.Buffer) int

GenerateBookmarks generates the outline hierarchy for the PDF It returns the object ID of the Outlines dictionary (the root)

func (*PageManager) GetCurrentContentStream

func (pm *PageManager) GetCurrentContentStream() *bytes.Buffer

GetCurrentContentStream returns the current page's content stream

func (*PageManager) GetCurrentPageID

func (pm *PageManager) GetCurrentPageID() int

GetCurrentPageID returns the current page object ID

func (*PageManager) GetNextAnnotStructParent

func (pm *PageManager) GetNextAnnotStructParent() int

GetNextAnnotStructParent returns and increments the StructParent counter for annotations PDF/UA-2: Each annotation needs a unique StructParent value for ParentTree lookup

type PageMargins

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

PageMargins represents the margins (left, right, top, bottom) for a PDF page in points.

func DefaultPageMargins

func DefaultPageMargins() PageMargins

DefaultPageMargins returns the standard 1-inch margins (72 points) for all sides.

func ParsePageMargins

func ParsePageMargins(margins string) PageMargins

ParsePageMargins parses margins in "left:right:top:bottom" points format. Missing or invalid values gracefully fall back to defaults.

type RegisteredFont

type RegisteredFont = font.RegisteredFont

type StructElem

type StructElem struct {
	Type     StructureType
	Title    string
	Alt      string
	Lang     string
	Kids     []interface{} // Can be *StructElem or int (MCID reference object)
	Parent   *StructElem
	ObjectID int // Assigned when writing to PDF
	PageID   int // Reference to the page object ID where this element appears
}

StructElem represents a node in the structure tree

type StructureManager

type StructureManager struct {
	Root          *StructElem
	CurrentParent *StructElem
	Elements      []*StructElem
	NextMCID      map[int]int           // Page Index -> Next MCID
	ParentTree    map[int][]*StructElem // Page Index -> Array of struct elements (parents of MCIDs)
	StructParents map[int]int           // Page Object ID -> StructParents index (in ParentTree)
	LinkElements  map[int]*StructElem   // PDF/UA-2: Annotation Object ID -> Link StructElem
}

StructureManager handles the creation and management of the PDF structure tree

func NewStructureManager

func NewStructureManager() *StructureManager

NewStructureManager creates a new structure manager

func (*StructureManager) AddLinkElement

func (sm *StructureManager) AddLinkElement(annotObjID int, _ int)

AddLinkElement adds a Link structure element for an annotation PDF/UA-2 requires link annotations to be wrapped in Link structure elements

func (*StructureManager) BeginMarkedContent

func (sm *StructureManager) BeginMarkedContent(streamBuilder *strings.Builder, pageIndex int, tag StructureType, props map[string]string) int

BeginMarkedContent starts a new structure element and returns the tag, properties strings and MCID

func (*StructureManager) BeginMarkedContentBuf

func (sm *StructureManager) BeginMarkedContentBuf(buf *bytes.Buffer, pageIndex int, tag StructureType, props map[string]string) int

BeginMarkedContentBuf writes directly to a bytes.Buffer (avoids strings.Builder intermediary in hot loops)

func (*StructureManager) BeginStructureElement

func (sm *StructureManager) BeginStructureElement(tag StructureType)

BeginStructureElement starts a grouping element (like Table, TR) that doesn't directly contain content yet

func (*StructureManager) CreateBookmarkSect

func (sm *StructureManager) CreateBookmarkSect(title string) *StructElem

CreateBookmarkSect creates a Sect structure element for a bookmark target PDF/UA-2 requires GoTo actions to use structure destinations (/SD) This creates a section element that can be used as a navigation target

func (*StructureManager) EndMarkedContent

func (sm *StructureManager) EndMarkedContent(streamBuilder *strings.Builder)

EndMarkedContent ends the current marked content sequence

func (*StructureManager) EndMarkedContentBuf

func (sm *StructureManager) EndMarkedContentBuf(buf *bytes.Buffer)

EndMarkedContentBuf writes EMC directly to a bytes.Buffer (avoids strings.Builder intermediary)

func (*StructureManager) EndStructureElement

func (sm *StructureManager) EndStructureElement()

EndStructureElement ends the current grouping element

func (*StructureManager) GenerateStructTreeRoot

func (sm *StructureManager) GenerateStructTreeRoot(_ int, parentTreeObjID int, namespaceObjID int) string

GenerateStructTreeRoot generates the StructTreeRoot object content namespaceObjID is the object ID of the PDF 2.0 namespace dictionary (0 to skip)

func (*StructureManager) GetCurrentDocumentElement

func (sm *StructureManager) GetCurrentDocumentElement() *StructElem

GetCurrentDocumentElement returns the Document element (first child of Root)

func (*StructureManager) GetNextMCID

func (sm *StructureManager) GetNextMCID(pageIndex int) int

GetNextMCID returns the next available MCID for a page

func (*StructureManager) RegisterPageStructParents

func (sm *StructureManager) RegisterPageStructParents(_ int, _ int)

RegisterPageStructParents registers the parent tree mapping for a page

type StructureType

type StructureType string

StructureType represents the standard structure types in PDF/UA

const (
	// StructDocument represents the Document grouping element.
	StructDocument StructureType = "Document"
	// StructPart represents the Part grouping element.
	StructPart StructureType = "Part"
	// StructSect represents the Sect grouping element.
	StructSect StructureType = "Sect"
	// StructDiv represents the Div grouping element.
	StructDiv StructureType = "Div"
	// StructH1 represents the H1 header element.
	StructH1 StructureType = "H1"
	// StructH2 represents the H2 header element.
	StructH2 StructureType = "H2"
	// StructH3 represents the H3 header element.
	StructH3 StructureType = "H3"
	// StructH4 represents the H4 header element.
	StructH4 StructureType = "H4"
	// StructH5 represents the H5 header element.
	StructH5 StructureType = "H5"
	// StructH6 represents the H6 header element.
	StructH6 StructureType = "H6"
	// StructP represents the Paragraph element.
	StructP StructureType = "P"
	// StructL represents the List element.
	StructL StructureType = "L"
	// StructLI represents the List Item element.
	StructLI StructureType = "LI"
	// StructLbl represents the List Label element.
	StructLbl StructureType = "Lbl"
	// StructLBody represents the List Body element.
	StructLBody StructureType = "LBody"
	// StructTable represents the Table element.
	StructTable StructureType = "Table"
	// StructTR represents the Table Row element.
	StructTR StructureType = "TR"
	// StructTH represents the Table Header element.
	StructTH StructureType = "TH"
	// StructTD represents the Table Data element.
	StructTD StructureType = "TD"
	// StructFigure represents the Figure element.
	StructFigure StructureType = "Figure"
	// StructCaption represents the Caption element.
	StructCaption StructureType = "Caption"
	// StructForm represents the Form grouping element.
	StructForm StructureType = "Form"
	// StructLink represents a Link structure element (PDF/UA-2).
	StructLink StructureType = "Link"
	// StructReference represents a Reference structure element (PDF/UA-2).
	StructReference StructureType = "Reference"
)

type TTFFont

type TTFFont = font.TTFFont

Directories

Path Synopsis
Package form provides functionality for parsing XFDF and filling PDF forms.
Package form provides functionality for parsing XFDF and filling PDF forms.
Package merge provides PDF merging functionality without external dependencies.
Package merge provides PDF merging functionality without external dependencies.
Package redact provides functionality for PDF text and image redaction.
Package redact provides functionality for PDF text and image redaction.
Package signature provides digital signature support for PDF documents.
Package signature provides digital signature support for PDF documents.
Package svg provides support for converting simple vector graphics (SVG) to PDF commands.
Package svg provides support for converting simple vector graphics (SVG) to PDF commands.

Jump to

Keyboard shortcuts

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