pdf

package module
v1.1.9 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2026 License: BSD-3-Clause Imports: 25 Imported by: 9

README

Go reference documentation Homepage

baseline logo

baseline-pdf is a low-level PDF writer for the Go language. It is used in the boxes and glue typesetting library but can be used in other projects as well.

This library has a godoc reference and a more verbose manual.

Version 1.1

Starting with version 1.1, baseline-pdf uses textshape for font handling (parsing, shaping, subsetting).

New features in 1.1:

  • Variable font support with instancing (convert variable fonts to static instances)
  • Improved font subsetting

Status

Not yet used in production. Expect API changes.

License

BSD license - see License.md

Contact

Patrick Gundlach, [email protected]

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Logger is initialized to write to io.Discard and the default log level is
	// math.MaxInt, so it should never write anything.
	Logger *slog.Logger
)

Functions

func FloatToPoint

func FloatToPoint(in float64) string

FloatToPoint returns a string suitable as a PDF size value.

func Serialize

func Serialize(item any) string

Serialize returns a string representation of the item as it may appear in the PDF file. Arrays are written with square brackets, Dicts with double angle brackets, Strings (PDF strings) with parentheses or single angle brackets, depending on the contents and all other objects with their respective String() method.

Types

type Annotation

type Annotation struct {
	Dictionary   Dict
	Subtype      Name
	Action       string
	Rect         [4]float64   // x1, y1, x2, y2
	Objectnumber Objectnumber // pre-reserved object number (0 = auto-assign)
}

An Annotation is a PDF element that is additional to the text, such as a hyperlink or a note.

type Array

type Array []any

Array is a list of anything

type Dict

type Dict map[Name]any

Dict is a dictionary where each key begins with a slash (/). Each value can be a string, an array or another dictionary.

type Face

type Face struct {
	Shaper *ot.Shaper

	VariationSettings map[string]float64 // axis tag -> value for variable fonts
	Filename          string
	PostscriptName    string
	FaceID            int
	Scale             float64
	UnitsPerEM        int32
	// contains filtered or unexported fields
}

Face represents a font structure with no specific size. To get the dimensions of a font, you need to create a Font object with a given size.

func (*Face) AdvanceWidth added in v1.1.6

func (face *Face) AdvanceWidth(glyphID int) float64

AdvanceWidth returns the advance width of the glyph with the given ID in PDF text space units (1/1000 of text space, scaled by face.Scale).

func (*Face) Codepoint

func (face *Face) Codepoint(r rune) int

Codepoint tries to find the code point for r. If none found, 0 is returned.

func (*Face) Codepoints

func (face *Face) Codepoints(runes []rune) []int

Codepoints returns the internal code points for the runes.

func (*Face) CompactSubset added in v1.1.0

func (face *Face) CompactSubset() error

CompactSubset enables compact glyph mapping for smaller font files. When called, glyph IDs are renumbered (0, 1, 2, ...) instead of keeping the original positions. Use MapGlyph() to convert old GIDs to new GIDs when writing content streams. Must be called after RegisterCodepoints() and before creating content streams.

func (*Face) InternalName

func (face *Face) InternalName() string

InternalName returns a PDF usable name such as /F1

func (*Face) MapGlyph added in v1.1.0

func (face *Face) MapGlyph(oldGID int) int

MapGlyph maps an old glyph ID to the new glyph ID after compact subsetting. Only useful after calling CompactSubset(). If compact subsetting is not used, returns the original ID unchanged.

func (*Face) OTFace added in v1.1.0

func (face *Face) OTFace() *ot.Face

OTFace returns the underlying ot.Face for direct access.

func (*Face) RegisterChar deprecated

func (face *Face) RegisterChar(codepoint int)

RegisterChar marks the codepoint as used on the page. For font subsetting.

Deprecated: use RegisterCodepoint instead.

func (*Face) RegisterChars deprecated

func (face *Face) RegisterChars(codepoints []int)

RegisterChars marks the codepoints as used on the page. For font subsetting.

Deprecated: use RegisterCodepoints instead.

func (*Face) RegisterCodepoint added in v1.0.11

func (face *Face) RegisterCodepoint(codepoint int)

RegisterCodepoint marks the codepoint as used on the page. For font subsetting.

func (*Face) RegisterCodepoints added in v1.0.11

func (face *Face) RegisterCodepoints(codepoints []int)

RegisterCodepoints marks the codepoints as used on the page. For font subsetting.

type Imagefile

type Imagefile struct {
	PageSizes map[int]map[string]map[string]float64

	Format   string
	Filename string
	Box      string

	NumberOfPages int
	ScaleX        float64
	ScaleY        float64
	W             int
	H             int
	PageNumber    int // The requested page number for PDF images (1-based)
	// contains filtered or unexported fields
}

Imagefile represents a physical image file. Images to be place in the PDF must be derived from the image.

func (*Imagefile) Close added in v1.0.8

func (imgf *Imagefile) Close() error

Close closes the underlying file handle.

func (*Imagefile) GetPDFBoxDimensions

func (imgf *Imagefile) GetPDFBoxDimensions(p int, boxName string) (map[string]float64, error)

GetPDFBoxDimensions returns normalized box dimensions for the given page and box name. It always computes x, y, w, h and clamps non-Media boxes to the MediaBox. Supported names: "/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox". Fallbacks:

  • missing /CropBox -> /MediaBox
  • missing /ArtBox|/BleedBox|/TrimBox -> /CropBox if present, else /MediaBox

func (*Imagefile) InternalName

func (imgf *Imagefile) InternalName() string

InternalName returns a PDF usable name such as /F1

type Name

type Name string

Name represents a PDF name such as Adobe Green. The String() method prepends a / (slash) to the name if not present.

func (Name) String

func (n Name) String() string

type NameDest

type NameDest struct {
	Name             String
	PageObjectnumber Objectnumber
	X                float64
	Y                float64
	// contains filtered or unexported fields
}

NameDest represents a named PDF destination. The origin of X and Y are in the top left corner and expressed in DTP points.

type NameTreeData added in v1.0.6

type NameTreeData map[String]Objectnumber

NameTreeData is a map of strings to object numbers which is sorted by key and converted to an array when written to the PDF. It is suitable for use in a name tree object.

type Object

type Object struct {
	Data       *bytes.Buffer
	Dictionary Dict

	Array        []any
	ObjectNumber Objectnumber
	Raw          bool // Data holds everything between object number and endobj
	ForceStream  bool // Write stream even if Data is empty
	// contains filtered or unexported fields
}

Object has information about a specific PDF object

func (*Object) Dict

func (obj *Object) Dict(d Dict) *Object

Dict writes the dict d to a PDF object

func (*Object) Save

func (obj *Object) Save() error

Save adds the PDF object to the main PDF file.

func (*Object) SetCompression

func (obj *Object) SetCompression(compresslevel uint)

SetCompression turns on stream compression if compresslevel > 0

type Objectnumber

type Objectnumber int

Objectnumber represents a PDF object number

func (Objectnumber) Ref

func (o Objectnumber) Ref() string

Ref returns a reference to the object number

func (Objectnumber) String

func (o Objectnumber) String() string

String returns a reference to the object number

type Outline

type Outline struct {
	Title    string
	Dest     string
	Children []*Outline

	Open bool
	// contains filtered or unexported fields
}

Outline represents PDF bookmarks. To create outlines, you need to assign previously created Dest items to the outline. When Open is true, the PDF viewer shows the child outlines.

type PDF

type PDF struct {
	Catalog          Dict
	InfoDict         Dict
	NameDestinations map[String]*NameDest

	Colorspaces       []*Separation
	Outlines          []*Outline
	DefaultOffsetX    float64
	DefaultOffsetY    float64
	DefaultPageWidth  float64
	DefaultPageHeight float64
	Major             uint
	Minor             uint
	NoPages           int // set when PDF is finished
	// contains filtered or unexported fields
}

PDF is the central point of writing a PDF file.

func NewPDFWriter

func NewPDFWriter(file io.Writer) *PDF

NewPDFWriter initializes and returns a PDF writer targeting file. It sets PDF version 1.7, prepares internal maps, a reusable zlib writer, and starts object numbering at 1 (object 0 is the free head entry).

func (*PDF) AddPage

func (pw *PDF) AddPage(content *Object, page Objectnumber) *Page

AddPage adds a page to the PDF file. The content stream must a stream object (i.e. an object with data). Pass 0 for the page object number if you don't pre-allocate an object number for the page.

func (*PDF) Finish

func (pw *PDF) Finish() error

Finish writes the trailer and xref section but does not close the file.

func (*PDF) FinishAndClose added in v1.0.8

func (pw *PDF) FinishAndClose() error

FinishAndClose writes the trailer and xref section and closes the file if it implements io.Closer.

func (*PDF) GetCatalogNameTreeDict added in v1.0.6

func (pw *PDF) GetCatalogNameTreeDict(dict Name) Dict

GetCatalogNameTreeDict returns the Dict for the specified name. If it does not exist, it is created.

func (*PDF) LoadFace

func (pw *PDF) LoadFace(filename string, idx int) (*Face, error)

LoadFace loads a font from the disc. The index specifies the sub font to be loaded.

func (*PDF) LoadImageFile

func (pw *PDF) LoadImageFile(filename string) (*Imagefile, error)

LoadImageFile loads an image from the disc. For PDF files it defaults to page 1 and the /MediaBox.

func (*PDF) LoadImageFileWithBox

func (pw *PDF) LoadImageFileWithBox(filename string, box string, pagenumber int) (*Imagefile, error)

LoadImageFileWithBox loads an image from the disc with the given box and page number. If box is empty, it defaults to /MediaBox.

func (*PDF) LoadImageFromReader added in v1.1.8

func (pw *PDF) LoadImageFromReader(r io.ReadSeeker, box string, pagenumber int) (*Imagefile, error)

LoadImageFromReader loads an image from the given reader with the given box and page number. If box is empty, it defaults to /MediaBox. The caller is responsible for closing the reader if needed.

func (*PDF) NewFaceFromData

func (pw *PDF) NewFaceFromData(data []byte, idx int) (*Face, error)

NewFaceFromData returns a Face object which is a representation of a font file.

func (*PDF) NewObject

func (pw *PDF) NewObject() *Object

NewObject create a new PDF object and reserves an object number for it. The object is not written to the PDF until Save() is called.

func (*PDF) NewObjectWithNumber

func (pw *PDF) NewObjectWithNumber(objnum Objectnumber) *Object

NewObjectWithNumber create a new PDF object and reserves an object number for it. The object is not written to the PDF until Save() is called.

func (*PDF) NextObject

func (pw *PDF) NextObject() Objectnumber

NextObject returns the next free object number

func (*PDF) Print

func (pw *PDF) Print(s string) error

Print writes the string to the PDF file

func (*PDF) Printf

func (pw *PDF) Printf(format string, a ...any) error

Printf writes the formatted string to the PDF file.

func (*PDF) Println

func (pw *PDF) Println(s string) error

Println writes the string to the PDF file and adds a newline.

func (*PDF) Size

func (pw *PDF) Size() int64

Size returns the current size of the PDF file (number of bytes).

type Page

type Page struct {
	Dict Dict // Additional dictionary entries such as "/Trimbox"

	Annotations []Annotation
	Faces       []*Face
	Images      []*Imagefile
	Objnum      Objectnumber // The "/Page" object
	Width       float64
	Height      float64
	OffsetX     float64
	OffsetY     float64
	// contains filtered or unexported fields
}

Page contains information about a single page.

type Pages

type Pages struct {
	Pages []*Page
	// contains filtered or unexported fields
}

Pages is the parent page structure

type Separation

type Separation struct {
	ID         string
	Name       string
	Obj        Objectnumber
	ICCProfile Objectnumber
	C          float64
	M          float64
	Y          float64
	K          float64
}

Separation represents a spot color

type String

type String string

String is a string that gets automatically converted to (...) or hexadecimal form when placed in the PDF.

Jump to

Keyboard shortcuts

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