pdfcpu

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2024 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Overview

Package pdfcpu is a PDF processing library written in Go supporting encryption. It provides an API and a command line interface. Supported are all versions up to PDF 1.7 (ISO-32000).

The commands are:

annotations   list, remove page annotations
attachments   list, add, remove, extract embedded file attachments
booklet       arrange pages onto larger sheets of paper to make a booklet or zine
boxes         list, add, remove page boundaries for selected pages
changeopw     change owner password
changeupw     change user password
collect       create custom sequence of selected pages
config        print configuration
create        create PDF content via JSON
crop          set cropbox for selected pages
decrypt       remove password protection
encrypt       set password protection
extract       extract images, fonts, content, pages or metadata
fonts         install, list supported fonts, create cheat sheets
grid          rearrange pages or images for enhanced browsing experience
images        list images for selected pages
import        import/convert images to PDF
info          print file info
keywords      list, add, remove keywords
merge         concatenate PDFs
nup           rearrange pages or images for reduced number of pages
optimize      optimize PDF by getting rid of redundant page resources
pages         insert, remove selected pages
paper         print list of supported paper sizes
permissions   list, set user access permissions
portfolio     list, add, remove, extract portfolio entries with optional description
properties	   list, add, remove document properties
rotate        rotate pages
selectedpages print definition of the -pages flag
split         split up a PDF by span or bookmark
stamp         add, remove, update Unicode text, image or PDF stamps for selected pages
trim          create trimmed version of selected pages
validate      validate PDF against PDF 32000-1:2008 (PDF 1.7)
version       print version
watermark     add, remove, update Unicode text, image or PDF watermarks for selected pages

Index

Constants

View Source
const (
	DeviceGrayCS = "DeviceGray"
	DeviceRGBCS  = "DeviceRGB"
	DeviceCMYKCS = "DeviceCMYK"
	CalGrayCS    = "CalGray"
	CalRGBCS     = "CalRGB"
	LabCS        = "Lab"
	ICCBasedCS   = "ICCBased"
	IndexedCS    = "Indexed"
	PatternCS    = "Pattern"
	SeparationCS = "Separation"
	DeviceNCS    = "DeviceN"
)

PDF defines the following Color Spaces:

View Source
const (
	// ValidationStrict ensures 100% compliance with the spec (PDF 32000-1:2008).
	ValidationStrict int = iota

	// ValidationRelaxed ensures PDF compliance based on frequently encountered validation errors.
	ValidationRelaxed

	// ValidationNone bypasses validation.
	ValidationNone
)
View Source
const (

	// StatsFileNameDefault is the standard stats filename.
	StatsFileNameDefault = "stats.csv"

	// PermissionsAll enables all user access permission bits.
	PermissionsAll int16 = -1 // 0xFFFF

	// PermissionsPrint disables all user access permissions bits except for printing.
	PermissionsPrint int16 = -1849 // 0xF8C7

	// PermissionsNone disables all user access permissions bits.
	PermissionsNone int16 = -3901 // 0xF0C3

)
View Source
const (
	RightDown orientation = iota
	DownRight
	LeftDown
	DownLeft
)

These are the defined anchors for relative positioning.

View Source
const (
	DegToRad = math.Pi / 180
	RadToDeg = 180 / math.Pi
)
View Source
const (
	WMText = iota
	WMImage
	WMPDF
)

Watermark mode

View Source
const (
	NoDiagonal = iota
	DiagonalLLToUR
	DiagonalULToLR
)

Rotation along one of 2 diagonals

View Source
const (
	RootVersion = iota
	RootExtensions
	RootPageLabels
	RootNames
	RootDests
	RootViewerPrefs
	RootPageLayout
	RootPageMode
	RootOutlines
	RootThreads
	RootOpenAction
	RootAA
	RootURI
	RootAcroForm
	RootMetadata
	RootStructTreeRoot
	RootMarkInfo
	RootLang
	RootSpiderInfo
	RootOutputIntents
	RootPieceInfo
	RootOCProperties
	RootPerms
	RootLegal
	RootRequirements
	RootCollection
	RootNeedsRendering
)

The PDF root object fields.

View Source
const (
	PageLastModified = iota
	PageResources
	PageMediaBox
	PageCropBox
	PageBleedBox
	PageTrimBox
	PageArtBox
	PageBoxColorInfo
	PageContents
	PageRotate
	PageGroup
	PageThumb
	PageB
	PageDur
	PageTrans
	PageAnnots
	PageAA
	PageMetadata
	PagePieceInfo
	PageStructParents
	PageID
	PagePZ
	PageSeparationInfo
	PageTabs
	PageTemplateInstantiated
	PagePresSteps
	PageUserUnit
	PageVP
)

The PDF page object fields.

View Source
const (
	EolLF   = "\x0A"
	EolCR   = "\x0D"
	EolCRLF = "\x0D\x0A"
)

Supported line delimiters

View Source
const FreeHeadGeneration = 65535

FreeHeadGeneration is the predefined generation number for the head of the free list.

View Source
const (

	// ObjectStreamMaxObjects limits the number of objects within an object stream written.
	ObjectStreamMaxObjects = 100
)

Variables

View Source
var (
	Black     = SimpleColor{}
	White     = SimpleColor{R: 1, G: 1, B: 1}
	LightGray = SimpleColor{.9, .9, .9}
	Gray      = SimpleColor{.5, .5, .5}
	DarkGray  = SimpleColor{.3, .3, .3}
	Red       = SimpleColor{1, 0, 0}
	Green     = SimpleColor{0, 1, 0}
	Blue      = SimpleColor{0, 0, 1}
)

Some popular colors.

View Source
var AnnotTypeStrings = map[AnnotationType]string{
	AnnText:           "Text",
	AnnLink:           "Link",
	AnnFreeText:       "FreeText",
	AnnLine:           "Line",
	AnnSquare:         "Square",
	AnnCircle:         "Circle",
	AnnPolygon:        "Polygon",
	AnnPolyLine:       "PolyLine",
	AnnHighLight:      "HighLight",
	AnnUnderline:      "Underline",
	AnnSquiggly:       "Squiggly",
	AnnStrikeOut:      "StrikeOut",
	AnnStamp:          "Stamp",
	AnnCaret:          "Caret",
	AnnInk:            "Ink",
	AnnPopup:          "Popup",
	AnnFileAttachment: "FileAttachment",
	AnnSound:          "Sound",
	AnnMovie:          "Movie",
	AnnWidget:         "Widget",
	AnnScreen:         "Screen",
	AnnPrinterMark:    "PrinterMark",
	AnnTrapNet:        "TrapNet",
	AnnWatermark:      "Watermark",
	Ann3D:             "3D",
	AnnRedact:         "Redact",
}

AnnotTypeStrings manages string representations for annotation types.

View Source
var ConfigPath string = "default"

ConfigPath defines the location of pdfcpu's configuration directory. If set to a file path, pdfcpu will ensure the config dir at this location. Other possible values:

default:	Ensure config dir at default location
disable:	Disable config dir usage
View Source
var (
	ErrInvalidColor = errors.New("pdfcpu: invalid color constant")
)
View Source
var ErrInvalidUTF16BE = errors.New("pdfcpu: invalid UTF-16BE detected")

ErrInvalidUTF16BE represents an error that gets raised for invalid UTF-16BE byte sequences.

View Source
var (
	ErrUnknownEncryption = errors.New("pdfcpu: PDF 2.0 encryption not supported")
)
View Source
var (
	ErrUnsupported16BPC = errors.New("unsupported 16 bits per component")
)

Errors to be identified.

View Source
var (
	ErrWrongPassword = errors.New("pdfcpu: please provide the correct password")
)
View Source
var PaperSize = map[string]*Dim{}/* 150 elements not displayed */

PaperSize is a map of known paper sizes in user units (=72 dpi pixels).

View Source
var VersionStr = "v0.3.13 dev"

VersionStr is the current pdfcpu version.

Functions

func AddPages

func AddPages(ctx, ctxDest *Context, pages []int, usePgCache bool) error

AddPages adds pages and corresponding resources from otherXRefTable to xRefTable.

func AnchorPosition

func AnchorPosition(a Anchor, r *Rectangle, w, h float64) (x float64, y float64)

func AppendPageTree

func AppendPageTree(d1 *IndirectRef, countd1 int, d2 Dict) error

AppendPageTree appends a pagetree d1 to page tree d2.

func AppendStatsFile

func AppendStatsFile(ctx *Context) error

AppendStatsFile appends a stats line for this xRefTable to the configured csv file name.

func BestFitRectIntoRect

func BestFitRectIntoRect(rSrc, rDest *Rectangle, enforceOrient bool) (w, h, dx, dy, rot float64)

func BookletFromImages

func BookletFromImages(ctx *Context, fileNames []string, nup *NUp, pagesDict Dict, pagesIndRef *IndirectRef) error

BookletFromImages creates a booklet version of the image sequence represented by fileNames.

func CP1252ToUTF8

func CP1252ToUTF8(s string) string

CP1252ToUTF8 converts CP1252 to UTF-8.

func CreatePage

func CreatePage(
	xRefTable *XRefTable,
	parentPageIndRef IndirectRef,
	p Page,
	fonts map[string]IndirectRef,
	fields *Array,
	formFontIDs map[string]string) (*IndirectRef, Dict, error)

func CreateTestPageContent

func CreateTestPageContent(p Page)

CreateTestPageContent draws a test grid.

func DateString

func DateString(t time.Time) string

DateString returns a string representation of t.

func DateTime

func DateTime(s string, relaxed bool) (time.Time, bool)

DateTime decodes s into a time.Time.

func DecodeUTF16String

func DecodeUTF16String(s string) (string, error)

DecodeUTF16String decodes a UTF16BE string from a hex string.

func DecodeUTF8ToByte

func DecodeUTF8ToByte(s string) string

func DrawGrid

func DrawGrid(w io.Writer, x, y int, r *Rectangle, strokeCol SimpleColor, fillCol *SimpleColor)

DrawGrid draws an x * y grid on r using strokeCol and fillCol.

func DrawHairCross

func DrawHairCross(w io.Writer, x, y float64, r *Rectangle)

DrawHairCross draw a haircross with origin x/y.

func DrawLine

func DrawLine(w io.Writer, xp, yp, xq, yq float64, lineWidth float64, strokeColor *SimpleColor, style *LineJoinStyle)

DrawLine draws the path from P to Q using lineWidth, strokeColor and style.

func DrawLineSimple

func DrawLineSimple(w io.Writer, xp, yp, xq, yq float64)

DrawLineSimple draws the path from P to Q.

func DrawRect

func DrawRect(w io.Writer, r *Rectangle, lineWidth float64, strokeColor *SimpleColor, style *LineJoinStyle)

DrawRect strokes a rectangular path for r using lineWidth, strokeColor and style.

func DrawRectSimple

func DrawRectSimple(w io.Writer, r *Rectangle)

DrawRectSimple strokes a rectangular path for r.

func EncodeUTF16String

func EncodeUTF16String(s string) string

func EnsureDefaultConfigAt

func EnsureDefaultConfigAt(path string) error

EnsureDefaultConfigAt tries to load the default configuration from path. If path/pdfcpu/config.yaml is not found, it will be created.

func EqualObjects

func EqualObjects(o1, o2 Object, xRefTable *XRefTable) (ok bool, err error)

func Escape

func Escape(s string) (*string, error)

Escape applies all defined escape sequences to s.

func FillRect

func FillRect(w io.Writer, r *Rectangle, lineWidth float64, strokeCol *SimpleColor, fillCol SimpleColor, style *LineJoinStyle)

FillRect fills a rectangular path for r using lineWidth, strokeCol, fillCol and style.

func FillRectNoBorder

func FillRectNoBorder(w io.Writer, r *Rectangle, fillCol SimpleColor)

FillRectNoBorder fills a rectangular path for r using fillCol.

func HexLiteralToString

func HexLiteralToString(hl HexLiteral) (string, error)

HexLiteralToString returns a possibly UTF16 encoded string for a hex string.

func ImageFileName

func ImageFileName(fileName string) bool

ImageFileName returns true for supported image file types.

func ImageFileNames

func ImageFileNames(dir string) ([]string, error)

ImageFileNames returns a slice of image file names contained in dir.

func IndRefsForUserfontUpdate

func IndRefsForUserfontUpdate(xRefTable *XRefTable, d Dict, font *FontResource) error

func IntMemberOf

func IntMemberOf(i int, list []int) bool

IntMemberOf returns true if list contains i.

func IsStringUTF16BE

func IsStringUTF16BE(s string) bool

IsStringUTF16BE checks a string for Big Endian byte order BOM.

func IsUTF16BE

func IsUTF16BE(b []byte) bool

IsUTF16BE checks for Big Endian byte order mark and valid length.

func KeywordsAdd

func KeywordsAdd(xRefTable *XRefTable, keywords []string) error

KeywordsAdd adds keywords to the document info dict. Returns true if at least one keyword was added.

func KeywordsList

func KeywordsList(xRefTable *XRefTable) ([]string, error)

KeywordsList returns a list of keywords as recorded in the document info dict.

func KeywordsRemove

func KeywordsRemove(xRefTable *XRefTable, keywords []string) (bool, error)

KeywordsRemove deletes keywords from the document info dict. Returns true if at least one keyword was removed.

func MemberOf

func MemberOf(s string, list []string) bool

MemberOf returns true if list contains s.

func MergeXRefTables

func MergeXRefTables(ctxSource, ctxDest *Context) (err error)

MergeXRefTables merges Context ctxSource into ctxDest by appending its page tree.

func ModifyPageContent

func ModifyPageContent(
	xRefTable *XRefTable,
	dIndRef IndirectRef,
	d, res Dict,
	p Page,
	fonts map[string]IndirectRef,
	fields *Array,
	formFontIDs map[string]string) error

func NUpFromMultipleImages

func NUpFromMultipleImages(ctx *Context, fileNames []string, nup *NUp, pagesDict Dict, pagesIndRef *IndirectRef) error

NUpFromMultipleImages creates pages in NUp-style rendering each image once.

func NUpFromOneImage

func NUpFromOneImage(ctx *Context, fileName string, nup *NUp, pagesDict Dict, pagesIndRef *IndirectRef) error

NUpFromOneImage creates one page with instances of one image.

func NormalizeCoord

func NormalizeCoord(x, y float64, r *Rectangle, origin Corner, absolute bool) (float64, float64)

NormalizeCoord transfers P(x,y) from pdfcpu user space into PDF user space, which uses a coordinate system with origin in the lower left corner of r.

pdfcpu user space coordinate systems have the origin in one of four corners of r:

LowerLeft corner (default = PDF user space)

x extends to the right,
y extends upward

LowerRight corner:

x extends to the left,
y extends upward

UpperLeft corner:

x extends to the right,
y extends downward

UpperRight corner:

x extends to the left,
y extends downward

func NormalizeOffset

func NormalizeOffset(x, y float64, origin Corner) (float64, float64)

Normalize offset transfers x and y into offsets in the PDF user space.

func OptimizeXRefTable

func OptimizeXRefTable(ctx *Context) error

OptimizeXRefTable optimizes an xRefTable by locating and getting rid of redundant embedded fonts and images.

func ParseNUpDetails

func ParseNUpDetails(s string, nup *NUp) error

ParseNUpDetails parses a NUp command string into an internal structure.

func ParseNUpGridDefinition

func ParseNUpGridDefinition(rows, cols int, nUp *NUp) error

ParseNUpGridDefinition parses NUp grid dimensions into an internal structure.

func ParseNUpValue

func ParseNUpValue(n int, nUp *NUp) error

ParseNUpValue parses the NUp value into an internal structure.

func Permissions

func Permissions(ctx *Context) (list []string)

Permissions returns a list of set permissions.

func PrepBytes

func PrepBytes(s, fontName string, rtl bool) string

func RenderImage

func RenderImage(xRefTable *XRefTable, sd *StreamDict, thumb bool, resourceName string, objNr int) (io.Reader, string, error)

RenderImage returns a reader for a decoded image stream.

func ResolveWMTextString

func ResolveWMTextString(text, timeStampFormat string, pageNr, pageCount int) (string, bool)

func RotatePages

func RotatePages(ctx *Context, selectedPages IntSet, rotation int) error

RotatePages rotates all selected pages by a multiple of 90 degrees.

func SetFillColor

func SetFillColor(w io.Writer, c SimpleColor)

SetFillColor sets the fill color.

func SetLineJoinStyle

func SetLineJoinStyle(w io.Writer, s LineJoinStyle)

SetLineJoinStyle sets the line join style for stroking operations.

func SetLineWidth

func SetLineWidth(w io.Writer, width float64)

SetLineWidth sets line width for stroking operations.

func SetStrokeColor

func SetStrokeColor(w io.Writer, c SimpleColor)

SetStrokeColor sets the stroke color.

func SplitMultilineStr

func SplitMultilineStr(s string) []string

func StringLiteralToString

func StringLiteralToString(sl StringLiteral) (string, error)

StringLiteralToString returns the best possible string rep for a string literal.

func Text

func Text(o Object) (string, error)

Text returns a string based representation for String and Hexliterals.

func TimingStats

func TimingStats(op string, durRead, durVal, durOpt, durWrite, durTotal float64)

TimingStats prints processing time stats for an operation.

func UTF8ToCP1252

func UTF8ToCP1252(s string) string

UTF8ToCP1252 converts UTF-8 to CP1252.

func Unescape

func Unescape(s string, enc bool) ([]byte, error)

Unescape resolves all escape sequences of s.

func ValidationTimingStats

func ValidationTimingStats(dur1, dur2, dur float64)

ValidationTimingStats prints processing time stats for validation.

func Write

func Write(ctx *Context) (err error)

Write generates a PDF file for the cross reference table contained in Context.

func WriteImage

func WriteImage(xRefTable *XRefTable, fileName string, sd *StreamDict, thumb bool, objNr int) (string, error)

WriteImage writes a PDF image object to disk.

func WriteImageToDisk

func WriteImageToDisk(outDir, fileName string) func(Image, bool, int) error

WriteImageToDisk returns a closure for writing img to disk.

func WriteIncrement

func WriteIncrement(ctx *Context) error

WriteIncrement writes a PDF increment..

func WriteReader

func WriteReader(path string, r io.Reader) error

WriteReader consumes r's content by writing it to a file at path.

Types

type Anchor

type Anchor int
const (
	TopLeft Anchor = iota
	TopCenter
	TopRight
	Left
	Center // default
	Right
	BottomLeft
	BottomCenter
	BottomRight
	Full // special case, no anchor needed, imageSize = pageSize
)

These are the defined anchors for relative positioning.

func ParseAnchor

func ParseAnchor(s string) (Anchor, error)

func (Anchor) String

func (a Anchor) String() string

type AnnotMap

type AnnotMap map[string]AnnotationRenderer

AnnotMap represents annotations by object number of the corresponding annotation dict.

type Annotation

type Annotation struct {
	SubType  AnnotationType  // The type of annotation that this dictionary describes.
	Rect     Rectangle       // The annotation rectangle, defining the location of the annotation on the page in default user space units.
	Contents string          // Text that shall be displayed for the annotation.
	P        *IndirectRef    // An indirect reference to the page object with which this annotation is associated.
	NM       string          // (Since V1.4) The annotation name, a text string uniquely identifying it among all the annotations on its page.
	ModDate  string          // The date and time when the annotation was most recently modified.
	F        AnnotationFlags // A set of flags specifying various characteristics of the annotation.
	C        *SimpleColor    // The background color of the annotation’s icon when closed.
}

Annotation represents a PDF annnotation.

func NewAnnotation

func NewAnnotation(
	typ AnnotationType,
	rect Rectangle,
	contents string,
	pageIndRef *IndirectRef,
	nm string,
	f AnnotationFlags,
	backgrCol *SimpleColor) Annotation

NewAnnotation returns a new annotation.

func NewAnnotationForRawType

func NewAnnotationForRawType(
	typ string,
	rect Rectangle,
	contents string,
	pageIndRef *IndirectRef,
	nm string,
	f AnnotationFlags,
	backgrCol *SimpleColor) Annotation

NewAnnotationForRawType returns a new annotation of a specific type.

func (Annotation) ContentString

func (ann Annotation) ContentString() string

ContentString returns a string representation of ann's contents.

func (Annotation) ID

func (ann Annotation) ID() string

ID returns the annotation id.

func (Annotation) RectString

func (ann Annotation) RectString() string

RectString returns ann's positioning rectangle.

func (Annotation) RenderDict

func (ann Annotation) RenderDict(pageIndRef IndirectRef) Dict

RenderDict is a stub for behavior that renders ann's PDF dict.

func (Annotation) Type

func (ann Annotation) Type() AnnotationType

Type returns ann's type.

func (Annotation) TypeString

func (ann Annotation) TypeString() string

TypeString returns a string representation of ann's type.

type AnnotationFlags

type AnnotationFlags int

AnnotationFlags represents the PDF annotation flags.

const (
	AnnInvisible AnnotationFlags = 1 << iota
	AnnHidden
	AnnPrint
	AnnNoZoom
	AnnNoRotate
	AnnNoView
	AnnReadOnly
	AnnLocked
	AnnToggleNoView
	AnnLockedContents
)

type AnnotationRenderer

type AnnotationRenderer interface {
	RenderDict(pageIndRef IndirectRef) Dict
	Type() AnnotationType
	RectString() string
	ID() string
	ContentString() string
}

AnnotationRenderer is the interface for PDF annotations.

type AnnotationType

type AnnotationType int

AnnotationType represents the various PDF annotation types.

const (
	AnnText AnnotationType = iota
	AnnLink
	AnnFreeText
	AnnLine
	AnnSquare
	AnnCircle
	AnnPolygon
	AnnPolyLine
	AnnHighLight
	AnnUnderline
	AnnSquiggly
	AnnStrikeOut
	AnnStamp
	AnnCaret
	AnnInk
	AnnPopup
	AnnFileAttachment
	AnnSound
	AnnMovie
	AnnWidget
	AnnScreen
	AnnPrinterMark
	AnnTrapNet
	AnnWatermark
	Ann3D
	AnnRedact
)

type Array

type Array []Object

Array represents a PDF array object.

func NewIntegerArray

func NewIntegerArray(fVars ...int) Array

NewIntegerArray returns a PDFArray with Integer entries.

func NewNameArray

func NewNameArray(sVars ...string) Array

NewNameArray returns a PDFArray with Name entries.

func NewNumberArray

func NewNumberArray(fVars ...float64) Array

NewNumberArray returns a PDFArray with Float entries.

func NewStringArray

func NewStringArray(sVars ...string) Array

NewStringArray returns a PDFArray with StringLiteral entries.

func (Array) Clone

func (a Array) Clone() Object

Clone returns a clone of a.

func (Array) FloatNumber

func (a Array) FloatNumber(ind int) (float64, error)

FloatNumber returns the element at index ind of a numbers array and returns a float64.

func (Array) PDFString

func (a Array) PDFString() string

PDFString returns a string representation as found in and written to a PDF file.

func (Array) String

func (a Array) String() string

type Attachment

type Attachment struct {
	io.Reader            // attachment data
	ID        string     // id
	FileName  string     // filename
	Desc      string     // description
	ModTime   *time.Time // time of last modification (optional)
}

Attachment is a Reader representing a PDF attachment.

func (Attachment) String

func (a Attachment) String() string

type Bookmark

type Bookmark struct {
	Title    string
	PageFrom int
	PageThru int // for extraction only; >= pageFrom and reaches until before pageFrom of the next bookmark.
	Bold     bool
	Italic   bool
	Color    *SimpleColor
	Children []Bookmark
	Parent   *Bookmark
}

Bookmark represents an outline item tree.

func (Bookmark) Style

func (bm Bookmark) Style() int

Style returns an int corresponding to the bookmark style.

type Boolean

type Boolean bool

Boolean represents a PDF boolean object.

func (Boolean) Clone

func (boolean Boolean) Clone() Object

Clone returns a clone of boolean.

func (Boolean) PDFString

func (boolean Boolean) PDFString() string

PDFString returns a string representation as found in and written to a PDF file.

func (Boolean) String

func (boolean Boolean) String() string

func (Boolean) Value

func (boolean Boolean) Value() bool

Value returns a bool value for this PDF object.

type Box

type Box struct {
	Rect      *Rectangle // Rectangle in user space.
	Inherited bool       // Media box and Crop box may be inherited.
	RefBox    string     // Use position of another box,
	// Margins to parent box in points.
	// Relative to parent box if 0 < x < 0.5
	MLeft, MRight float64
	MTop, MBot    float64
	// Relative position within parent box
	Dim    *Dim   // dimensions
	Pos    Anchor // position anchor within parent box, one of tl,tc,tr,l,c,r,bl,bc,br.
	Dx, Dy int    // anchor offset
}

Box is a rectangular region in user space expressed either explicitly via Rect or implicitly via margins applied to the containing parent box. Media box serves as parent box for crop box. Crop box serves as parent box for trim, bleed and art box.

func ParseBox

func ParseBox(s string, u DisplayUnit) (*Box, error)

ParseBox parses a box definition.

type ByteSize

type ByteSize float64

ByteSize represents the various terms for storage space.

const (
	KB ByteSize = 1 << (10 * iota)
	MB
	GB
)

Storage space terms.

func (ByteSize) String

func (b ByteSize) String() string

type CommandMode

type CommandMode int

CommandMode specifies the operation being executed.

const (
	VALIDATE CommandMode = iota
	OPTIMIZE
	SPLIT
	MERGECREATE
	MERGEAPPEND
	EXTRACTIMAGES
	EXTRACTFONTS
	EXTRACTPAGES
	EXTRACTCONTENT
	EXTRACTMETADATA
	TRIM
	ADDATTACHMENTS
	ADDATTACHMENTSPORTFOLIO
	REMOVEATTACHMENTS
	EXTRACTATTACHMENTS
	LISTATTACHMENTS
	SETPERMISSIONS
	LISTPERMISSIONS
	ENCRYPT
	DECRYPT
	CHANGEUPW
	CHANGEOPW
	ADDWATERMARKS
	REMOVEWATERMARKS
	IMPORTIMAGES
	INSERTPAGESBEFORE
	INSERTPAGESAFTER
	REMOVEPAGES
	ROTATE
	NUP
	BOOKLET
	INFO
	CHEATSHEETSFONTS
	INSTALLFONTS
	LISTFONTS
	LISTKEYWORDS
	ADDKEYWORDS
	REMOVEKEYWORDS
	LISTPROPERTIES
	ADDPROPERTIES
	REMOVEPROPERTIES
	COLLECT
	CROP
	LISTBOXES
	ADDBOXES
	REMOVEBOXES
	LISTANNOTATIONS
	ADDANNOTATIONS
	REMOVEANNOTATIONS
	ADDBOOKMARKS
	LISTIMAGES
	CREATE
)

The available commands.

type Configuration

type Configuration struct {
	// Location of corresponding config.yml
	Path string

	// Check filename extensions.
	CheckFileNameExt bool

	// Enables PDF V1.5 compatible processing of object streams, xref streams, hybrid PDF files.
	Reader15 bool

	// Enables decoding of all streams (fontfiles, images..) for logging purposes.
	DecodeAllStreams bool

	// Validate against ISO-32000: strict or relaxed.
	ValidationMode int

	// Check for broken links in LinkedAnnotations/URIActions.
	ValidateLinks bool

	// End of line char sequence for writing.
	Eol string

	// Turns on object stream generation.
	// A signal for compressing any new non-stream-object into an object stream.
	// true enforces WriteXRefStream to true.
	// false does not prevent xRefStream generation.
	WriteObjectStream bool

	// Switches between xRefSection (<=V1.4) and objectStream/xRefStream (>=V1.5) writing.
	WriteXRefStream bool

	// Turns on stats collection.
	// TODO Decision - unused.
	CollectStats bool

	// A CSV-filename holding the statistics.
	StatsFileName string

	// Supplied user password.
	UserPW    string
	UserPWNew *string

	// Supplied owner password.
	OwnerPW    string
	OwnerPWNew *string

	// EncryptUsingAES ensures AES encryption.
	// true: AES encryption
	// false: RC4 encryption.
	EncryptUsingAES bool

	// AES:40,128,256 RC4:40,128
	EncryptKeyLength int

	// Supplied user access permissions, see Table 22.
	Permissions int16

	// Command being executed.
	Cmd CommandMode

	// Display unit in effect.
	Unit DisplayUnit

	// Timestamp format.
	TimestampFormat string

	// Buffersize for locating PDF header <= 100
	HeaderBufSize int

	// Optimize duplicate content streams across pages.
	OptimizeDuplicateContentStreams bool
}

Configuration of a Context.

func NewAESConfiguration

func NewAESConfiguration(userPW, ownerPW string, keyLength int) *Configuration

NewAESConfiguration returns a default configuration for AES encryption.

func NewDefaultConfiguration

func NewDefaultConfiguration() *Configuration

NewDefaultConfiguration returns the default pdfcpu configuration.

func NewRC4Configuration

func NewRC4Configuration(userPW, ownerPW string, keyLength int) *Configuration

NewRC4Configuration returns a default configuration for RC4 encryption.

func (*Configuration) ApplyReducedFeatureSet

func (c *Configuration) ApplyReducedFeatureSet() bool

ApplyReducedFeatureSet returns true if complex entries like annotations shall not be written.

func (*Configuration) EolString

func (c *Configuration) EolString() string

EolString returns a string rep for the eol in effect.

func (Configuration) String

func (c Configuration) String() string

func (*Configuration) UnitString

func (c *Configuration) UnitString() string

UnitString returns a string rep for the display unit in effect.

func (*Configuration) ValidationModeString

func (c *Configuration) ValidationModeString() string

ValidationModeString returns a string rep for the validation mode in effect.

type Context

type Context struct {
	*Configuration
	*XRefTable
	Read     *ReadContext
	Optimize *OptimizationContext
	Write    *WriteContext
	// contains filtered or unexported fields
}

Context represents an environment for processing PDF files.

func CollectPages

func CollectPages(ctx *Context, collectedPages []int) (*Context, error)

CollectPages creates a new PDF Context for a custom PDF page sequence of the PDF represented by ctx.

func CreateContext

func CreateContext(xRefTable *XRefTable, conf *Configuration) *Context

CreateContext creates a Context for given cross reference table and configuration.

func CreateContextWithXRefTable

func CreateContextWithXRefTable(conf *Configuration, pageDim *Dim) (*Context, error)

CreateContextWithXRefTable creates a Context with an xRefTable without pages for given configuration.

func NewContext

func NewContext(rs io.ReadSeeker, conf *Configuration) (*Context, error)

NewContext initializes a new Context.

func Read

func Read(rs io.ReadSeeker, conf *Configuration) (*Context, error)

Read takes a readSeeker and generates a Context, an in-memory representation containing a cross reference table.

func ReadFile

func ReadFile(inFile string, conf *Configuration) (*Context, error)

ReadFile reads in a PDF file and builds an internal structure holding its cross reference table aka the Context.

func (*Context) AddAnnotation

func (ctx *Context) AddAnnotation(pageDictIndRef *IndirectRef, pageDict Dict, pageNr int, ar AnnotationRenderer, incr bool) (bool, error)

AddAnnotation adds ar to pageDict.

func (*Context) AddAnnotations

func (ctx *Context) AddAnnotations(selectedPages IntSet, ar AnnotationRenderer, incr bool) (bool, error)

AddAnnotations adds ar to selected pages.

func (*Context) AddAnnotationsMap

func (ctx *Context) AddAnnotationsMap(m map[int][]AnnotationRenderer, incr bool) (bool, error)

AddAnnotationsMap adds annotations in m to corresponding pages.

func (*Context) AddAttachment

func (ctx *Context) AddAttachment(a Attachment, useCollection bool) error

AddAttachment adds a.

func (*Context) AddBookmarks

func (ctx *Context) AddBookmarks(bms []Bookmark) error

AddBookmarks adds bms to ctx.

func (*Context) AddPageBoundaries

func (ctx *Context) AddPageBoundaries(selectedPages IntSet, pb *PageBoundaries) error

AddPageBoundaries adds page boundaries specified by pb for selected pages.

func (*Context) AddWatermarks

func (ctx *Context) AddWatermarks(selectedPages IntSet, wm *Watermark) error

AddWatermarks adds watermarks to all pages selected.

func (*Context) AddWatermarksMap

func (ctx *Context) AddWatermarksMap(m map[int]*Watermark) error

AddWatermarksMap adds watermarks in m to corresponding pages.

func (*Context) AddWatermarksSliceMap

func (ctx *Context) AddWatermarksSliceMap(m map[int][]*Watermark) error

AddWatermarksSliceMap adds watermarks in m to corresponding pages.

func (*Context) AnnotationObjNrs

func (ctx *Context) AnnotationObjNrs() ([]int, error)

AnnotationObjNrs returns a list of object numbers representing known annotation dict indirect references.

func (*Context) BookletFromPDF

func (ctx *Context) BookletFromPDF(selectedPages IntSet, nup *NUp) error

BookletFromPDF creates a booklet version of the PDF represented by xRefTable.

func (*Context) BookmarksForOutline

func (ctx *Context) BookmarksForOutline() ([]Bookmark, error)

BookmarksForOutline returns all ctx bookmark information recursively.

func (*Context) BookmarksForOutlineItem

func (ctx *Context) BookmarksForOutlineItem(item *IndirectRef, parent *Bookmark) ([]Bookmark, error)

BookmarksForOutlineItem returns the bookmarks tree for an outline item.

func (*Context) ColorSpaceString

func (ctx *Context) ColorSpaceString(sd *StreamDict) (string, error)

ColorSpaceString returns a string representation for sd's colorspace.

func (*Context) Crop

func (ctx *Context) Crop(selectedPages IntSet, b *Box) error

Crop sets crop box for selected pages to b.

func (*Context) DetectPageTreeWatermarks

func (ctx *Context) DetectPageTreeWatermarks() error

DetectPageTreeWatermarks checks xRefTable's page tree for watermarks and records the result to xRefTable.Watermarked.

func (*Context) DetectWatermarks

func (ctx *Context) DetectWatermarks() error

DetectWatermarks checks ctx for watermarks and records the result to xRefTable.Watermarked.

func (*Context) ExtractAttachment

func (ctx *Context) ExtractAttachment(a Attachment) (*Attachment, error)

ExtractAttachment extracts a fully populated attachment.

func (*Context) ExtractAttachments

func (ctx *Context) ExtractAttachments(ids []string) ([]Attachment, error)

ExtractAttachments extracts attachments with id.

func (*Context) ExtractFont

func (ctx *Context) ExtractFont(objNr int) (*Font, error)

ExtractFont extracts a font from font dict by objNr.

func (*Context) ExtractImage

func (ctx *Context) ExtractImage(sd *StreamDict, thumb bool, resourceId string, objNr int, stub bool) (*Image, error)

ExtractImage extracts an image from sd.

func (*Context) ExtractMetadata

func (ctx *Context) ExtractMetadata() ([]Metadata, error)

ExtractMetadata returns all metadata of ctx.

func (*Context) ExtractPage

func (ctx *Context) ExtractPage(pageNr int) (*Context, error)

ExtractPage extracts pageNr into a new single page context.

func (*Context) ExtractPageContent

func (ctx *Context) ExtractPageContent(pageNr int) (io.Reader, error)

ExtractPageContent extracts the consolidated page content stream for pageNr.

func (*Context) ExtractPageFonts

func (ctx *Context) ExtractPageFonts(pageNr int) ([]Font, error)

ExtractPageFonts extracts all fonts used by pageNr.

func (*Context) ExtractPageImages

func (ctx *Context) ExtractPageImages(pageNr int, stub bool) ([]Image, error)

ExtractPageImages extracts all images used by pageNr. Optionally return stubs only.

func (*Context) ExtractPages

func (ctx *Context) ExtractPages(pageNrs []int, usePgCache bool) (*Context, error)

ExtractPages extracts pageNrs into a new single page context.

func (*Context) FontObjNrs

func (ctx *Context) FontObjNrs(pageNr int) []int

FontObjNrs returns all font dict objNrs for pageNr. Requires an optimized context.

func (*Context) ImageObjNrs

func (ctx *Context) ImageObjNrs(pageNr int) []int

ImageObjNrs returns all image dict objNrs for pageNr. Requires an optimized context.

func (*Context) InfoDigest

func (ctx *Context) InfoDigest(selectedPages IntSet) ([]string, error)

InfoDigest returns info about ctx.

func (*Context) ListAttachments

func (ctx *Context) ListAttachments() ([]Attachment, error)

ListAttachments returns a slice of attachment stubs (attachment w/o data).

func (*Context) ListImages

func (ctx *Context) ListImages(selectedPages IntSet) ([]string, error)

ListImages returns a list of embedded images.

func (*Context) ListPageBoundaries

func (ctx *Context) ListPageBoundaries(selectedPages IntSet, wantPB *PageBoundaries) ([]string, error)

ListPageBoundaries lists page boundaries specified in wantPB for selected pages.

func (*Context) NUpFromPDF

func (ctx *Context) NUpFromPDF(selectedPages IntSet, nup *NUp) error

NUpFromPDF creates an n-up version of the PDF represented by xRefTable.

func (*Context) PageObjFromDestinationArray

func (ctx *Context) PageObjFromDestinationArray(dest Object) (*IndirectRef, error)

PageObjFromDestinationArray return an IndirectRef for this destinations page object.

func (*Context) PropertiesAdd

func (ctx *Context) PropertiesAdd(properties map[string]string) error

PropertiesAdd adds properties into the document info dict. Returns true if at least one property was added.

func (*Context) PropertiesList

func (ctx *Context) PropertiesList() ([]string, error)

PropertiesList returns a list of document properties as recorded in the document info dict.

func (*Context) PropertiesRemove

func (ctx *Context) PropertiesRemove(properties []string) (bool, error)

PropertiesRemove deletes specified properties. Returns true if at least one property was removed.

func (*Context) RemoveAnnotations

func (ctx *Context) RemoveAnnotations(selectedPages IntSet, ids []string, objNrs []int, incr bool) (bool, error)

RemoveAnnotations removes annotations for selected pages by id and object number. All annotations for selected pages are removed if neither ids nor objNrs are provided.

func (*Context) RemoveAnnotationsFromPageDict

func (ctx *Context) RemoveAnnotationsFromPageDict(ids []string, objNrSet IntSet, pageDict Dict, pageDictObjNr, pageNr int, incr bool) (bool, error)

RemoveAnnotationsFromPageDict removes an annotation by its object number annObjNr from pageDict.

func (*Context) RemoveAttachment

func (ctx *Context) RemoveAttachment(a Attachment) (bool, error)

RemoveAttachment removes a and returns true on success.

func (*Context) RemoveAttachments

func (ctx *Context) RemoveAttachments(ids []string) (bool, error)

RemoveAttachments removes attachments with given id and returns true if anything removed.

func (*Context) RemovePageBoundaries

func (ctx *Context) RemovePageBoundaries(selectedPages IntSet, pb *PageBoundaries) error

RemovePageBoundaries removes page boundaries specified by pb for selected pages. The media box is mandatory (inherited or not) and can't be removed. A removed crop box defaults to the media box. Removed trim/bleed/art boxes default to the crop box.

func (*Context) RemoveWatermarks

func (ctx *Context) RemoveWatermarks(selectedPages IntSet) error

RemoveWatermarks removes watermarks for all pages selected.

func (*Context) ResetWriteContext

func (ctx *Context) ResetWriteContext()

ResetWriteContext prepares an existing WriteContext for a new file to be written.

func (*Context) SearchEmbeddedFilesNameTreeNodeByContent

func (ctx *Context) SearchEmbeddedFilesNameTreeNodeByContent(s string) (*string, Object, error)

SearchEmbeddedFilesNameTreeNodeByContent tries to identify a name tree by content.

func (*Context) StreamLength

func (ctx *Context) StreamLength(sd *StreamDict) (int64, error)

StreamLength returns sd's stream length.

func (*Context) String

func (ctx *Context) String() string

type Corner

type Corner int

Corner represents one of four rectangle corners.

const (
	LowerLeft Corner = iota
	LowerRight
	UpperLeft
	UpperRight
)

The four corners of a rectangle.

func ParseOrigin

func ParseOrigin(s string) (Corner, error)

type Dict

type Dict map[string]Object

Dict represents a PDF dict object.

func NewDict

func NewDict() Dict

NewDict returns a new PDFDict object.

func (Dict) ArrayEntry

func (d Dict) ArrayEntry(key string) Array

ArrayEntry expects and returns a Array entry for given key.

func (Dict) BooleanEntry

func (d Dict) BooleanEntry(key string) *bool

BooleanEntry expects and returns a BooleanEntry for given key.

func (Dict) Clone

func (d Dict) Clone() Object

Clone returns a clone of d.

func (Dict) Delete

func (d Dict) Delete(key string) (value Object)

Delete deletes the Object for given key.

func (Dict) DictEntry

func (d Dict) DictEntry(key string) Dict

DictEntry expects and returns a PDFDict entry for given key.

func (Dict) Entry

func (d Dict) Entry(dictName, key string, required bool) (Object, error)

Entry returns the value for given key.

func (Dict) Find

func (d Dict) Find(key string) (value Object, found bool)

Find returns the Object for given key and PDFDict.

func (Dict) First

func (d Dict) First() *int

First returns a *int for key "First".

func (Dict) HexLiteralEntry

func (d Dict) HexLiteralEntry(key string) *HexLiteral

HexLiteralEntry returns a HexLiteral object for given key.

func (*Dict) Increment

func (d *Dict) Increment(key string) error

Increment increments the integer value for given key.

func (*Dict) IncrementBy

func (d *Dict) IncrementBy(key string, i int) error

IncrementBy increments the integer value for given key by i.

func (Dict) Index

func (d Dict) Index() Array

Index returns a *Array for key "Index".

func (Dict) IndirectRefEntry

func (d Dict) IndirectRefEntry(key string) *IndirectRef

IndirectRefEntry returns an indirectRefEntry for given key for this dictionary.

func (Dict) Insert

func (d Dict) Insert(key string, value Object) (ok bool)

Insert adds a new entry to this PDFDict.

func (Dict) InsertFloat

func (d Dict) InsertFloat(key string, value float32)

InsertFloat adds a new float entry to this PDFDict.

func (Dict) InsertInt

func (d Dict) InsertInt(key string, value int)

InsertInt adds a new int entry to this PDFDict.

func (Dict) InsertName

func (d Dict) InsertName(key, value string)

InsertName adds a new name entry to this PDFDict.

func (Dict) InsertString

func (d Dict) InsertString(key, value string)

InsertString adds a new string entry to this PDFDict.

func (Dict) Int64Entry

func (d Dict) Int64Entry(key string) *int64

Int64Entry expects and returns a Integer entry representing an int64 value for given key.

func (Dict) IntEntry

func (d Dict) IntEntry(key string) *int

IntEntry expects and returns a Integer entry for given key.

func (Dict) IsLinearizationParmDict

func (d Dict) IsLinearizationParmDict() bool

IsLinearizationParmDict returns true if this dict has an int entry for key "Linearized".

func (Dict) IsObjStm

func (d Dict) IsObjStm() bool

IsObjStm returns true if given PDFDict is an object stream.

func (Dict) Len

func (d Dict) Len() int

Len returns the length of this PDFDict.

func (Dict) Length

func (d Dict) Length() (*int64, *int)

Length returns a *int64 for entry with key "Length". Stream length may be referring to an indirect object.

func (Dict) N

func (d Dict) N() *int

N returns a *int for key "N".

func (Dict) NameEntry

func (d Dict) NameEntry(key string) *string

NameEntry expects and returns a Name entry for given key.

func (Dict) NewIDForPrefix

func (d Dict) NewIDForPrefix(prefix string, i int) string

func (Dict) PDFString

func (d Dict) PDFString() string

PDFString returns a string representation as found in and written to a PDF file.

func (Dict) Prev

func (d Dict) Prev() *int64

Prev returns the previous offset.

func (Dict) Size

func (d Dict) Size() *int

Size returns the value of the int entry for key "Size"

func (Dict) StreamDictEntry

func (d Dict) StreamDictEntry(key string) *StreamDict

StreamDictEntry expects and returns a StreamDict entry for given key. unused.

func (Dict) String

func (d Dict) String() string

func (Dict) StringEntry

func (d Dict) StringEntry(key string) *string

StringEntry expects and returns a StringLiteral entry for given key.

func (Dict) StringEntryBytes

func (d Dict) StringEntryBytes(key string) ([]byte, error)

StringEntryBytes returns the byte slice representing the string value for key.

func (Dict) StringLiteralEntry

func (d Dict) StringLiteralEntry(key string) *StringLiteral

StringLiteralEntry returns a StringLiteral object for given key.

func (Dict) Subtype

func (d Dict) Subtype() *string

Subtype returns the value of the name entry for key "Subtype".

func (Dict) Type

func (d Dict) Type() *string

Type returns the value of the name entry for key "Type".

func (Dict) Update

func (d Dict) Update(key string, value Object)

Update modifies an existing entry of this PDFDict.

func (Dict) W

func (d Dict) W() Array

W returns a *Array for key "W".

type Dim

type Dim struct {
	Width, Height float64
}

Dim represents the dimensions of a rectangular view medium like a PDF page, a sheet of paper or an image grid in user space, inches, centimetres or millimetres.

func ParsePageFormat

func ParsePageFormat(v string) (*Dim, string, error)

func (Dim) AspectRatio

func (d Dim) AspectRatio() float64

AspectRatio returns the relation between width and height.

func (Dim) Landscape

func (d Dim) Landscape() bool

Landscape returns true if d is in landscape mode.

func (Dim) Portrait

func (d Dim) Portrait() bool

Portrait returns true if d is in portrait mode.

func (Dim) String

func (d Dim) String() string

func (Dim) ToCentimetres

func (d Dim) ToCentimetres() Dim

ToCentimetres converts d to centimetres.

func (Dim) ToInches

func (d Dim) ToInches() Dim

ToInches converts d to inches.

func (Dim) ToMillimetres

func (d Dim) ToMillimetres() Dim

ToMillimetres converts d to centimetres.

type DisplayUnit

type DisplayUnit int

DisplayUnit is the metric unit used to output paper sizes.

const (
	POINTS DisplayUnit = iota
	INCHES
	CENTIMETRES
	MILLIMETRES
)

Options for display unit in effect.

type Enc

type Enc struct {
	O, U       []byte
	OE, UE     []byte
	Perms      []byte
	L, P, R, V int
	Emd        bool // encrypt meta data
	ID         []byte
}

Enc wraps around all defined encryption attributes.

type Float

type Float float64

Float represents a PDF float object.

func (Float) Clone

func (f Float) Clone() Object

Clone returns a clone of f.

func (Float) PDFString

func (f Float) PDFString() string

PDFString returns a string representation as found in and written to a PDF file.

func (Float) String

func (f Float) String() string

func (Float) Value

func (f Float) Value() float64

Value returns a float64 value for this PDF object.

type Font

type Font struct {
	io.Reader
	Name string
	Type string
}

Font is a Reader representing an embedded font.

type FontMap

type FontMap map[string]FontResource

FontMap maps font names to font resources.

func (FontMap) EnsureKey

func (fm FontMap) EnsureKey(fontName string) string

EnsureKey registers fontName with corresponding font resource id.

type FontObject

type FontObject struct {
	ResourceNames []string
	Prefix        string
	FontName      string
	FontDict      Dict
	Data          []byte
	Extension     string
}

FontObject represents a font used in a PDF file.

func (*FontObject) AddResourceName

func (fo *FontObject) AddResourceName(resourceName string)

AddResourceName adds a resourceName referring to this font.

func (FontObject) Embedded

func (fo FontObject) Embedded() (embedded bool)

Embedded returns true if the font is embedded into this PDF file.

func (FontObject) Encoding

func (fo FontObject) Encoding() string

Encoding returns the Encoding of this font.

func (FontObject) ResourceNamesString

func (fo FontObject) ResourceNamesString() string

ResourceNamesString returns a string representation of all the resource names of this font.

func (FontObject) String

func (fo FontObject) String() string

func (FontObject) SubType

func (fo FontObject) SubType() string

SubType returns the SubType of this font.

type FontResource

type FontResource struct {
	Res       Resource
	CIDSet    *IndirectRef
	FontFile  *IndirectRef
	ToUnicode *IndirectRef
	W         *IndirectRef
}

FontResource represents an existing PDF font resource.

type HAlignment

type HAlignment int

HAlignment represents the horizontal alignment of text.

const (
	AlignLeft HAlignment = iota
	AlignCenter
	AlignRight
	AlignJustify
)

These are the options for horizontal aligned text.

func ParseHorAlignment

func ParseHorAlignment(s string) (HAlignment, error)

type HexLiteral

type HexLiteral string

HexLiteral represents a PDF hex literal object.

func NewHexLiteral

func NewHexLiteral(b []byte) HexLiteral

NewHexLiteral creates a new HexLiteral for b..

func (HexLiteral) Bytes

func (hexliteral HexLiteral) Bytes() ([]byte, error)

Bytes returns the byte representation.

func (HexLiteral) Clone

func (hexliteral HexLiteral) Clone() Object

Clone returns a clone of hexliteral.

func (HexLiteral) PDFString

func (hexliteral HexLiteral) PDFString() string

PDFString returns the string representation as found in and written to a PDF file.

func (HexLiteral) String

func (hexliteral HexLiteral) String() string

func (HexLiteral) Value

func (hexliteral HexLiteral) Value() string

Value returns a string value for this PDF object.

type Image

type Image struct {
	io.Reader
	Name     string // Resource name
	FileType string

	Width  int // "Width"
	Height int // "Height"

	Size int64 // "Length"
	// contains filtered or unexported fields
}

Image is a Reader representing an image resource.

type ImageMap

type ImageMap map[string]ImageResource

ImageMap maps image filenames to image resources.

type ImageObject

type ImageObject struct {
	ResourceNames []string
	ImageDict     *StreamDict
}

ImageObject represents an image used in a PDF file.

func (*ImageObject) AddResourceName

func (io *ImageObject) AddResourceName(resourceName string)

AddResourceName adds a resourceName to this imageObject's ResourceNames dict.

func (ImageObject) ResourceNamesString

func (io ImageObject) ResourceNamesString() string

ResourceNamesString returns a string representation of the ResourceNames for this image.

type ImageResource

type ImageResource struct {
	Res    Resource
	Width  int
	Height int
}

ImageResource represents an existing PDF image resource.

type Import

type Import struct {
	PageDim  *Dim        // page dimensions in display unit.
	PageSize string      // one of A0,A1,A2,A3,A4(=default),A5,A6,A7,A8,Letter,Legal,Ledger,Tabloid,Executive,ANSIC,ANSID,ANSIE.
	UserDim  bool        // true if one of dimensions or paperSize provided overriding the default.
	DPI      int         // destination resolution to apply in dots per inch.
	Pos      Anchor      // position anchor, one of tl,tc,tr,l,c,r,bl,bc,br,full.
	Dx, Dy   int         // anchor offset.
	Scale    float64     // relative scale factor. 0 <= x <= 1
	ScaleAbs bool        // true for absolute scaling.
	InpUnit  DisplayUnit // input display unit.
	Gray     bool        // true for rendering in Gray.
	Sepia    bool
	BgColor  *SimpleColor // background color
}

Import represents the command details for the command "ImportImage".

func DefaultImportConfig

func DefaultImportConfig() *Import

DefaultImportConfig returns the default configuration.

func ParseImportDetails

func ParseImportDetails(s string, u DisplayUnit) (*Import, error)

ParseImportDetails parses an Import command string into an internal structure.

func (Import) String

func (imp Import) String() string

type IndirectRef

type IndirectRef struct {
	ObjectNumber     Integer
	GenerationNumber Integer
}

IndirectRef represents a PDF indirect object.

func CIDFontDescriptor

func CIDFontDescriptor(xRefTable *XRefTable, ttf font.TTFLight, fontName, baseFontName string, subFont bool) (*IndirectRef, error)

CIDFontDescriptor returns a font descriptor describing the CIDFont’s default metrics other than its glyph widths.

func CIDFontDict

func CIDFontDict(xRefTable *XRefTable, ttf font.TTFLight, fontName, baseFontName string, subFont bool) (*IndirectRef, error)

CIDFontDict returns the descendant font dict for Type0 fonts.

func CIDSet

func CIDSet(xRefTable *XRefTable, ttf font.TTFLight, indRef *IndirectRef) (*IndirectRef, error)

func CIDWidths

func CIDWidths(xRefTable *XRefTable, ttf font.TTFLight, subFont bool, indRef *IndirectRef) (*IndirectRef, error)

CIDWidths returns the value for W in a CIDFontDict.

func CreateImageResource

func CreateImageResource(xRefTable *XRefTable, r io.Reader, gray, sepia bool) (*IndirectRef, int, int, error)

func EnsureFontDict

func EnsureFontDict(xRefTable *XRefTable, fontName string, subDict bool, indRef *IndirectRef) (*IndirectRef, error)

func NewIndirectRef

func NewIndirectRef(objectNumber, generationNumber int) *IndirectRef

NewIndirectRef returns a new PDFIndirectRef object.

func NewNUpPageForImage

func NewNUpPageForImage(xRefTable *XRefTable, fileName string, parentIndRef *IndirectRef, nup *NUp) (*IndirectRef, error)

NewNUpPageForImage creates a new page dict in xRefTable for given image filename and n-up conf.

func NewPageForImage

func NewPageForImage(xRefTable *XRefTable, r io.Reader, parentIndRef *IndirectRef, imp *Import) (*IndirectRef, error)

NewPageForImage creates a new page dict in xRefTable for given image reader r.

func (IndirectRef) Clone

func (ir IndirectRef) Clone() Object

Clone returns a clone of ir.

func (IndirectRef) Equals

func (ir IndirectRef) Equals(indRef IndirectRef) bool

Equals returns true if two indirect References refer to the same object.

func (IndirectRef) PDFString

func (ir IndirectRef) PDFString() string

PDFString returns a string representation as found in and written to a PDF file.

func (IndirectRef) String

func (ir IndirectRef) String() string

type InheritedPageAttrs

type InheritedPageAttrs struct {
	Resources Dict
	MediaBox  *Rectangle
	CropBox   *Rectangle
	Rotate    int
}

InheritedPageAttrs represents all inherited page attributes.

type IntSet

type IntSet map[int]bool

IntSet is a set of integers.

type Integer

type Integer int

Integer represents a PDF integer object.

func (Integer) Clone

func (i Integer) Clone() Object

Clone returns a clone of i.

func (Integer) PDFString

func (i Integer) PDFString() string

PDFString returns a string representation as found in and written to a PDF file.

func (Integer) String

func (i Integer) String() string

func (Integer) Value

func (i Integer) Value() int

Value returns an int value for this PDF object.

type LineJoinStyle

type LineJoinStyle int

LineJoinStyle represents the shape to be used at the corners of paths that are stroked (see 8.4.3.4)

const (
	LJMiter LineJoinStyle = iota
	LJRound
	LJBevel
)

Render mode

type LinkAnnotation

type LinkAnnotation struct {
	Annotation
	URI  string
	Quad QuadPoints // Shall be ignored if any coordinate lies outside the region specified by Rect.
}

LinkAnnotation represents a PDF link annotation.

func NewLinkAnnotation

func NewLinkAnnotation(
	rect Rectangle,
	quad QuadPoints,
	uri, id string,
	f AnnotationFlags,
	backgrCol *SimpleColor) LinkAnnotation

NewLinkAnnotation returns a new link annotation.

func (LinkAnnotation) ContentString

func (ann LinkAnnotation) ContentString() string

ContentString returns a string representation of ann's content.

func (LinkAnnotation) RenderDict

func (ann LinkAnnotation) RenderDict(pageIndRef IndirectRef) Dict

RenderDict renders ann into a PDF annotation dict.

type MarkupAnnotation

type MarkupAnnotation struct {
	Annotation
	T            string       // The text label that shall be displayed in the title bar of the annotation’s pop-up window when open and active. This entry shall identify the user who added the annotation.
	PopupIndRef  *IndirectRef // An indirect reference to a pop-up annotation for entering or editing the text associated with this annotation.
	CA           *float64     // (Default: 1.0) The constant opacity value that shall be used in painting the annotation.
	RC           string       // A rich text string that shall be displayed in the pop-up window when the annotation is opened.
	CreationDate string       // The date and time when the annotation was created.
	Subj         string       // Text representing a short description of the subject being addressed by the annotation.
}

MarkupAnnotation represents a PDF markup annotation.

func NewMarkupAnnotation

func NewMarkupAnnotation(
	subType AnnotationType,
	rect Rectangle,
	pageIndRef *IndirectRef,
	contents, id, title string,
	f AnnotationFlags,
	backgrCol *SimpleColor,
	popupIndRef *IndirectRef,
	ca *float64,
	rc, subject string) MarkupAnnotation

NewMarkupAnnotation returns a new markup annotation.

type Matrix

type Matrix [3][3]float64

func CalcTransformMatrix

func CalcTransformMatrix(sx, sy, sin, cos, dx, dy float64) Matrix

func (Matrix) String

func (m Matrix) String() string

func (Matrix) Transform

func (m Matrix) Transform(p Point) Point

type Metadata

type Metadata struct {
	io.Reader          // metadata
	ObjNr       int    // metadata dict objNr
	ParentObjNr int    // container object number
	ParentType  string // container dict type
}

Metadata is a Reader representing a metadata dict.

type NUp

type NUp struct {
	PageDim       *Dim         // Page dimensions in display unit.
	PageSize      string       // Paper size eg. A4L, A4P, A4(=default=A4P), see paperSize.go
	UserDim       bool         // true if one of dimensions or paperSize provided overriding the default.
	Orient        orientation  // One of rd(=default),dr,ld,dl
	Grid          *Dim         // Intra page grid dimensions eg (2,2)
	PageGrid      bool         // Create a m x n grid of pages for PDF inputfiles only (think "extra page n-Up").
	ImgInputFile  bool         // Process image or PDF input files.
	Margin        int          // Cropbox for n-Up content.
	Border        bool         // Draw bounding box.
	BookletGuides bool         // Draw folding and cutting lines.
	MultiFolio    bool         // Render booklet as sequence of folios.
	FolioSize     int          // Booklet multifolio folio size: default: 8
	InpUnit       DisplayUnit  // input display unit.
	BgColor       *SimpleColor // background color
}

NUp represents the command details for the command "NUp".

func DefaultBookletConfig

func DefaultBookletConfig() *NUp

DefaultBookletConfig returns the default configuration for a booklet

func DefaultNUpConfig

func DefaultNUpConfig() *NUp

DefaultNUpConfig returns the default NUp configuration.

func ImageBookletConfig

func ImageBookletConfig(val int, desc string) (*NUp, error)

ImageBookletConfig returns an NUp configuration for booklet-ing image files.

func ImageGridConfig

func ImageGridConfig(rows, cols int, desc string) (*NUp, error)

ImageGridConfig returns a grid configuration for Nup-ing image files.

func ImageNUpConfig

func ImageNUpConfig(val int, desc string) (*NUp, error)

ImageNUpConfig returns an NUp configuration for Nup-ing image files.

func PDFBookletConfig

func PDFBookletConfig(val int, desc string) (*NUp, error)

PDFBookletConfig returns an NUp configuration for booklet-ing PDF files.

func PDFGridConfig

func PDFGridConfig(rows, cols int, desc string) (*NUp, error)

PDFGridConfig returns a grid configuration for Nup-ing PDF files.

func PDFNUpConfig

func PDFNUpConfig(val int, desc string) (*NUp, error)

PDFNUpConfig returns an NUp configuration for Nup-ing PDF files.

func (NUp) N

func (nup NUp) N() int

N returns the nUp value.

func (NUp) String

func (nup NUp) String() string

type Name

type Name string

Name represents a PDF name object.

func (Name) Clone

func (nameObject Name) Clone() Object

Clone returns a clone of nameObject.

func (Name) PDFString

func (nameObject Name) PDFString() string

PDFString returns a string representation as found in and written to a PDF file.

func (Name) String

func (nameObject Name) String() string

func (Name) Value

func (nameObject Name) Value() string

Value returns a string value for this PDF object.

type Node

type Node struct {
	Kids       []*Node // Mirror of the name tree's Kids array, an array of indirect references.
	Names      []entry // Mirror of the name tree's Names array.
	Kmin, Kmax string  // Mirror of the name tree's Limit array[Kmin,Kmax].
	D          Dict    // The PDF dict representing this name tree node.
}

Node is an opinionated implementation of the PDF name tree. pdfcpu caches all name trees found in the PDF catalog with this data structure. The PDF spec does not impose any rules regarding a strategy for the creation of nodes. A binary tree was chosen where each leaf node has a limited number of entries (maxEntries). Once maxEntries has been reached a leaf node turns into an intermediary node with two kids, which are leaf nodes each of them holding half of the sorted entries of the original leaf node.

func (*Node) Add

func (n *Node) Add(xRefTable *XRefTable, k string, v Object) error

Add adds an entry to a name tree.

func (*Node) AddToLeaf

func (n *Node) AddToLeaf(k string, v Object)

AddToLeaf adds an entry to a leaf.

func (*Node) HandleLeaf

func (n *Node) HandleLeaf(xRefTable *XRefTable, k string, v Object) error

HandleLeaf processes a leaf node.

func (Node) KeyList

func (n Node) KeyList() ([]string, error)

KeyList returns a sorted list of all keys.

func (Node) Process

func (n Node) Process(xRefTable *XRefTable, handler func(*XRefTable, string, Object) error) error

Process traverses the nametree applying a handler to each entry (key-value pair).

func (*Node) Remove

func (n *Node) Remove(xRefTable *XRefTable, k string) (empty, ok bool, err error)

Remove removes an entry from a name tree. empty returns true if this node is an empty leaf node after removal. ok returns true if removal was successful.

func (Node) String

func (n Node) String() string

func (Node) Value

func (n Node) Value(k string) (Object, bool)

Value returns the value for given key

type Object

type Object interface {
	fmt.Stringer
	Clone() Object
	PDFString() string
}

Object defines an interface for all Objects.

func ParseObject

func ParseObject(ctx *Context, offset int64, objNr, genNr int) (Object, error)

ParseObject parses an object from file at given offset.

type ObjectStreamDict

type ObjectStreamDict struct {
	StreamDict
	Prolog         []byte
	ObjCount       int
	FirstObjOffset int
	ObjArray       Array
}

ObjectStreamDict represents a object stream dictionary.

func NewObjectStreamDict

func NewObjectStreamDict() *ObjectStreamDict

NewObjectStreamDict creates a new ObjectStreamDict object.

func (*ObjectStreamDict) AddObject

func (osd *ObjectStreamDict) AddObject(objNumber int, entry *XRefTableEntry) error

AddObject adds another object to this object stream. Relies on decoded content!

func (*ObjectStreamDict) Finalize

func (osd *ObjectStreamDict) Finalize()

Finalize prepares the final content of the objectstream.

func (*ObjectStreamDict) IndexedObject

func (osd *ObjectStreamDict) IndexedObject(index int) (Object, error)

IndexedObject returns the object at given index from a ObjectStreamDict.

type OptimizationContext

type OptimizationContext struct {

	// Font section
	PageFonts         []IntSet            // For each page a registry of font object numbers.
	FontObjects       map[int]*FontObject // FontObject lookup table by font object number.
	FormFontObjects   map[int]*FontObject // FormFontObject lookup table by font object number.
	Fonts             map[string][]int    // All font object numbers registered for a font name.
	DuplicateFonts    map[int]Dict        // Registry of duplicate font dicts.
	DuplicateFontObjs IntSet              // The set of objects that represents the union of the object graphs of all duplicate font dicts.

	// Image section
	PageImages         []IntSet             // For each page a registry of image object numbers.
	ImageObjects       map[int]*ImageObject // ImageObject lookup table by image object number.
	DuplicateImages    map[int]*StreamDict  // Registry of duplicate image dicts.
	DuplicateImageObjs IntSet               // The set of objects that represents the union of the object graphs of all duplicate image dicts.

	ContentStreamCache map[int]*StreamDict
	FormStreamCache    map[int]*StreamDict

	DuplicateInfoObjects IntSet // Possible result of manual info dict modification.
	NonReferencedObjs    []int  // Objects that are not referenced.

	Cache     map[int]bool // For visited objects during optimization.
	NullObjNr *int         // objNr of a regular null object, to be used for fixing references to free objects.
}

OptimizationContext represents the context for the optimiziation of a PDF file.

func (*OptimizationContext) DuplicateFontObjectsString

func (oc *OptimizationContext) DuplicateFontObjectsString() (int, string)

DuplicateFontObjectsString returns a formatted string and the number of objs.

func (*OptimizationContext) DuplicateImageObjectsString

func (oc *OptimizationContext) DuplicateImageObjectsString() (int, string)

DuplicateImageObjectsString returns a formatted string and the number of objs.

func (*OptimizationContext) DuplicateInfoObjectsString

func (oc *OptimizationContext) DuplicateInfoObjectsString() (int, string)

DuplicateInfoObjectsString returns a formatted string and the number of objs.

func (*OptimizationContext) IsDuplicateFontObject

func (oc *OptimizationContext) IsDuplicateFontObject(i int) bool

IsDuplicateFontObject returns true if object #i is a duplicate font object.

func (*OptimizationContext) IsDuplicateImageObject

func (oc *OptimizationContext) IsDuplicateImageObject(i int) bool

IsDuplicateImageObject returns true if object #i is a duplicate image object.

func (*OptimizationContext) IsDuplicateInfoObject

func (oc *OptimizationContext) IsDuplicateInfoObject(i int) bool

IsDuplicateInfoObject returns true if object #i is a duplicate info object.

func (*OptimizationContext) NonReferencedObjsString

func (oc *OptimizationContext) NonReferencedObjsString() (int, string)

NonReferencedObjsString returns a formatted string and the number of objs.

type Orientation

type Orientation int

Refactor because of orientation in nup.go

const (
	Horizontal Orientation = iota
	Vertical
)

func ParseRadioButtonOrientation

func ParseRadioButtonOrientation(s string) (Orientation, error)

func ParseRegionOrientation

func ParseRegionOrientation(s string) (Orientation, error)

type PDFFilter

type PDFFilter struct {
	Name        string
	DecodeParms Dict
}

PDFFilter represents a PDF stream filter object.

type PDFImage

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

PDFImage represents a XObject of subtype image.

type PDFStats

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

PDFStats is a container for stats.

func NewPDFStats

func NewPDFStats() PDFStats

NewPDFStats returns a new PDFStats object.

func (PDFStats) AddPageAttr

func (stats PDFStats) AddPageAttr(name int)

AddPageAttr adds the occurrence of a field with given name to the pageAttrs set.

func (PDFStats) AddRootAttr

func (stats PDFStats) AddRootAttr(name int)

AddRootAttr adds the occurrence of a field with given name to the rootAttrs set.

func (PDFStats) UsesPageAttr

func (stats PDFStats) UsesPageAttr(name int) bool

UsesPageAttr returns true if a field with given name is contained in the pageAttrs set.

func (PDFStats) UsesRootAttr

func (stats PDFStats) UsesRootAttr(name int) bool

UsesRootAttr returns true if a field with given name is contained in the rootAttrs set.

type Page

type Page struct {
	MediaBox     *Rectangle
	CropBox      *Rectangle
	Fm           FontMap
	Im           ImageMap
	AnnotIndRefs Array
	Annots       []Dict
	LinkAnnots   []LinkAnnotation
	Buf          *bytes.Buffer
}

Page represents rendered page content.

func NewPage

func NewPage(mediaBox *Rectangle) Page

NewPage creates a page for a mediaBox.

func NewPageWithBg

func NewPageWithBg(mediaBox *Rectangle, c SimpleColor) Page

NewPageWithBg creates a page for a mediaBox.

type PageBoundaries

type PageBoundaries struct {
	Media *Box
	Crop  *Box
	Trim  *Box
	Bleed *Box
	Art   *Box
	Rot   int // The effective page rotation.
}

PageBoundaries represent the defined PDF page boundaries.

func ParseBoxList

func ParseBoxList(s string) (*PageBoundaries, error)

ParseBoxList parses a list of box types.

func ParsePageBoundaries

func ParsePageBoundaries(s string, unit DisplayUnit) (*PageBoundaries, error)

ParsePageBoundaries parses a list of box definitions and assignments.

func (PageBoundaries) ArtBox

func (pb PageBoundaries) ArtBox() *Rectangle

ArtBox returns the effective artbox for pb.

func (PageBoundaries) BleedBox

func (pb PageBoundaries) BleedBox() *Rectangle

BleedBox returns the effective bleedbox for pb.

func (PageBoundaries) CropBox

func (pb PageBoundaries) CropBox() *Rectangle

CropBox returns the effective cropbox for pb.

func (PageBoundaries) MediaBox

func (pb PageBoundaries) MediaBox() *Rectangle

MediaBox returns the effective mediabox for pb.

func (*PageBoundaries) ResolveBox

func (pb *PageBoundaries) ResolveBox(s string) error

ResolveBox resolves s and tries to assign an empty page boundary.

func (*PageBoundaries) SelectAll

func (pb *PageBoundaries) SelectAll()

SelectAll selects all page boundaries.

func (PageBoundaries) String

func (pb PageBoundaries) String() string

func (PageBoundaries) TrimBox

func (pb PageBoundaries) TrimBox() *Rectangle

TrimBox returns the effective trimbox for pb.

type PageResourceNames

type PageResourceNames map[string]StringSet

PageResourceNames represents the required resource names for a specific page as extracted from its content streams.

func NewPageResourceNames

func NewPageResourceNames() PageResourceNames

NewPageResourceNames returns initialized pageResourceNames.

func (PageResourceNames) HasContent

func (prn PageResourceNames) HasContent() bool

HasContent returns true in any resource names present.

func (PageResourceNames) HasResources

func (prn PageResourceNames) HasResources(s string) bool

HasResources returns true for any resource names present in resource subDict s.

func (PageResourceNames) Resources

func (prn PageResourceNames) Resources(s string) StringSet

Resources returns a set of all required resource names for subdict s.

func (PageResourceNames) String

func (prn PageResourceNames) String() string

type PgAnnots

type PgAnnots map[AnnotationType]AnnotMap

PgAnnots represents a map of page annotations by type.

type Point

type Point struct {
	X, Y float64
}

Point represents a user space location.

type PopupAnnotation

type PopupAnnotation struct {
	Annotation
	ParentIndRef *IndirectRef // The parent annotation with which this pop-up annotation shall be associated.
	Open         bool         // A flag specifying whether the annotation shall initially be displayed open.
}

PopupAnnotation represents PDF Popup annotations.

func NewPopupAnnotation

func NewPopupAnnotation(
	rect Rectangle,
	pageIndRef *IndirectRef,
	contents, id string,
	f AnnotationFlags,
	backgrCol *SimpleColor,
	parentIndRef *IndirectRef) PopupAnnotation

NewPopupAnnotation returns a new popup annotation.

func (PopupAnnotation) ContentString

func (ann PopupAnnotation) ContentString() string

ContentString returns a string representation of ann's content.

type QuadLiteral

type QuadLiteral struct {
	P1, P2, P3, P4 Point
}

QuadLiteral is a polygon with four edges and four vertices. The four vertices are assumed to be specified in counter clockwise order.

func (QuadLiteral) Array

func (ql QuadLiteral) Array() Array

Array returns the PDF representation of ql.

func (QuadLiteral) EnclosingRectangle

func (ql QuadLiteral) EnclosingRectangle(f float64) *Rectangle

EnclosingRectangle calculates the rectangle enclosing ql's vertices at a distance f.

type QuadPoints

type QuadPoints []QuadLiteral

QuadPoints is an array of 8 × n numbers specifying the coordinates of n quadrilaterals in default user space.

func (*QuadPoints) AddQuadLiteral

func (qp *QuadPoints) AddQuadLiteral(ql QuadLiteral)

AddQuadLiteral adds a quadliteral to qp.

func (*QuadPoints) Array

func (qp *QuadPoints) Array() Array

Array returns the PDF representation of qp.

type ReadContext

type ReadContext struct {
	FileName string // Input PDF-File.
	FileSize int64  // Input file size.

	EolCount            int    // 1 or 2 characters used for eol.
	BinaryTotalSize     int64  // total stream data
	BinaryImageSize     int64  // total image stream data
	BinaryFontSize      int64  // total font stream data (fontfiles)
	BinaryImageDuplSize int64  // total obsolet image stream data after optimization
	BinaryFontDuplSize  int64  // total obsolet font stream data after optimization
	Linearized          bool   // File is linearized.
	Hybrid              bool   // File is a hybrid PDF file.
	UsingObjectStreams  bool   // File is using object streams.
	ObjectStreams       IntSet // All object numbers of any object streams found which need to be decoded.
	UsingXRefStreams    bool   // File is using xref streams.
	XRefStreams         IntSet // All object numbers of any xref streams found.
	// contains filtered or unexported fields
}

ReadContext represents the context for reading a PDF file.

func (*ReadContext) IsObjectStreamObject

func (rc *ReadContext) IsObjectStreamObject(i int) bool

IsObjectStreamObject returns true if object i is a an object stream. All compressed objects are object streams.

func (*ReadContext) IsXRefStreamObject

func (rc *ReadContext) IsXRefStreamObject(i int) bool

IsXRefStreamObject returns true if object #i is a an xref stream.

func (*ReadContext) LogStats

func (rc *ReadContext) LogStats(optimized bool)

LogStats logs stats for read file.

func (*ReadContext) ObjectStreamsString

func (rc *ReadContext) ObjectStreamsString() (int, string)

ObjectStreamsString returns a formatted string and the number of object stream objects.

func (*ReadContext) ReadFileSize

func (rc *ReadContext) ReadFileSize() int

ReadFileSize returns the size of the input file, if there is one.

func (*ReadContext) XRefStreamsString

func (rc *ReadContext) XRefStreamsString() (int, string)

XRefStreamsString returns a formatted string and the number of xref stream objects.

type Rectangle

type Rectangle struct {
	*types.Rectangle
}

Rectangle represents a rectangular region in userspace.

func ApplyBox

func ApplyBox(boxName string, b *Box, d Dict, parent *Rectangle) *Rectangle

func CalcBoundingBox

func CalcBoundingBox(s string, x, y float64, fontName string, fontSize int) *Rectangle

func Rect

func Rect(llx, lly, urx, ury float64) *Rectangle

Rect returns a new rectangle for given lower left and upper right corners.

func RectForArray

func RectForArray(a Array) (*Rectangle, error)

RectForArray returns a new rectangle for given Array.

func RectForDim

func RectForDim(width, height float64) *Rectangle

RectForDim returns a new rectangle for given dimensions.

func RectForFormat

func RectForFormat(f string) *Rectangle

RectForFormat returns a new rectangle for given format.

func RectForWidthAndHeight

func RectForWidthAndHeight(llx, lly, width, height float64) *Rectangle

RectForWidthAndHeight returns a new rectangle for given dimensions.

func WriteColumn

func WriteColumn(w io.Writer, mediaBox, region *Rectangle, td TextDescriptor, width float64) *Rectangle

WriteColumn writes a text column using s at position x/y using a certain font, fontsize and a desired horizontal and vertical alignment. Enforce a desired column width by supplying a width > 0 (especially useful for justified text). It returns the bounding box of this column.

func WriteColumnAnchored

func WriteColumnAnchored(w io.Writer, mediaBox, region *Rectangle, td TextDescriptor, a Anchor, width float64) *Rectangle

WriteColumnAnchored writes a justified text column with anchored position and returns its bounding box.

func WriteMultiLine

func WriteMultiLine(w io.Writer, mediaBox, region *Rectangle, td TextDescriptor) *Rectangle

WriteMultiLine writes s at position x/y using a certain font, fontsize and a desired horizontal and vertical alignment. It returns the bounding box of this text column.

func WriteMultiLineAnchored

func WriteMultiLineAnchored(w io.Writer, mediaBox, region *Rectangle, td TextDescriptor, a Anchor) *Rectangle

WriteMultiLineAnchored writes multiple lines with anchored position and returns its bounding box.

func (Rectangle) Array

func (r Rectangle) Array() Array

Array returns the PDF representation of a rectangle.

func (*Rectangle) Center

func (r *Rectangle) Center() Point

func (Rectangle) CroppedCopy

func (r Rectangle) CroppedCopy(margin float64) *Rectangle

CroppedCopy returns a copy of r with applied margin..

func (Rectangle) Dimensions

func (r Rectangle) Dimensions() Dim

Dimensions returns r's dimensions.

func (Rectangle) Equals

func (r Rectangle) Equals(r2 Rectangle) bool

func (Rectangle) FitsWithin

func (r Rectangle) FitsWithin(r2 *Rectangle) bool

FitsWithin returns true if rectangle r fits within rectangle r2.

func (Rectangle) Format

func (r Rectangle) Format(unit DisplayUnit) string

Format returns r's details converted into unit.

func (Rectangle) ScaledHeight

func (r Rectangle) ScaledHeight(w float64) float64

ScaledHeight returns the height for given width according to r's aspect ratio.

func (Rectangle) ScaledWidth

func (r Rectangle) ScaledWidth(h float64) float64

ScaledWidth returns the width for given height according to r's aspect ratio.

func (*Rectangle) Translate

func (r *Rectangle) Translate(dx, dy float64)

Translate moves r by dx and dy.

type RelPosition

type RelPosition int

RelPosition represents the relative position of a text field's label.

const (
	RelPosLeft RelPosition = iota
	RelPosRight
	RelPosTop
	RelPosBottom
)

These are the options for relative label positions.

func ParseRelPosition

func ParseRelPosition(s string) (RelPosition, error)

type RenderMode

type RenderMode int

RenderMode represents the text rendering mode (see 9.3.6)

const (
	RMFill RenderMode = iota
	RMStroke
	RMFillAndStroke
)

Render mode

type Resource

type Resource struct {
	ID     string
	IndRef *IndirectRef
}

type SimpleColor

type SimpleColor struct {
	R, G, B float32 // intensities between 0 and 1.
}

SimpleColor is a simple rgb wrapper.

func NewSimpleColor

func NewSimpleColor(rgb uint32) SimpleColor

NewSimpleColor returns a SimpleColor for rgb in the form 0x00RRGGBB

func ParseColor

func ParseColor(s string) (SimpleColor, error)

func ParseHexColor

func ParseHexColor(hexCol string) (SimpleColor, error)

func (SimpleColor) Array

func (sc SimpleColor) Array() Array

func (SimpleColor) String

func (sc SimpleColor) String() string

type StreamDict

type StreamDict struct {
	Dict
	StreamOffset      int64
	StreamLength      *int64
	StreamLengthObjNr *int
	FilterPipeline    []PDFFilter
	Raw               []byte // Encoded
	Content           []byte // Decoded
	//DCTImage          image.Image
	IsPageContent bool
	CSComponents  int
}

StreamDict represents a PDF stream dict object.

func CreateImageStreamDict

func CreateImageStreamDict(xRefTable *XRefTable, r io.Reader, gray, sepia bool) (*StreamDict, int, int, error)

func NewStreamDict

func NewStreamDict(d Dict, streamOffset int64, streamLength *int64, streamLengthObjNr *int, filterPipeline []PDFFilter) StreamDict

NewStreamDict creates a new PDFStreamDict for given PDFDict, stream offset and length.

func (StreamDict) Clone

func (sd StreamDict) Clone() Object

Clone returns a clone of sd.

func (*StreamDict) Decode

func (sd *StreamDict) Decode() error

Decode applies sd's filter pipeline to sd.Raw in order to produce sd.Content.

func (*StreamDict) Encode

func (sd *StreamDict) Encode() error

Encode applies sd's filter pipeline to sd.Content in order to produce sd.Raw.

func (StreamDict) HasSoleFilterNamed

func (sd StreamDict) HasSoleFilterNamed(filterName string) bool

HasSoleFilterNamed returns true if sd has a filterPipeline with 1 filter named filterName.

func (StreamDict) Image

func (sd StreamDict) Image() bool

type StringLiteral

type StringLiteral string

StringLiteral represents a PDF string literal object.

func (StringLiteral) Clone

func (stringliteral StringLiteral) Clone() Object

Clone returns a clone of stringLiteral.

func (StringLiteral) PDFString

func (stringliteral StringLiteral) PDFString() string

PDFString returns a string representation as found in and written to a PDF file.

func (StringLiteral) String

func (stringliteral StringLiteral) String() string

func (StringLiteral) Value

func (stringliteral StringLiteral) Value() string

Value returns a string value for this PDF object.

type StringSet

type StringSet map[string]bool

StringSet is a set of strings.

func NewStringSet

func NewStringSet(slice []string) StringSet

NewStringSet returns a new StringSet for slice.

type TextAnnotation

type TextAnnotation struct {
	MarkupAnnotation
	Open bool   // A flag specifying whether the annotation shall initially be displayed open.
	Name string // The name of an icon that shall be used in displaying the annotation. Comment, Key, (Note), Help, NewParagraph, Paragraph, Insert
}

TextAnnotation represents a PDF text annotation aka "Sticky Note".

func NewTextAnnotation

func NewTextAnnotation(
	rect Rectangle,
	contents, id, title string,
	f AnnotationFlags,
	backgrCol *SimpleColor,
	ca *float64,
	rc, subj string,
	open bool,
	name string) TextAnnotation

NewTextAnnotation returns a new text annotation.

func (TextAnnotation) RenderDict

func (ann TextAnnotation) RenderDict(pageIndRef IndirectRef) Dict

RenderDict renders ann into a PDF annotation dict.

type TextDescriptor

type TextDescriptor struct {
	Text           string        // A multi line string using \n for line breaks.
	FontName       string        // Name of the core or user font to be used.
	RTL            bool          // Right to left user font.
	FontKey        string        // Resource id registered for FontName.
	FontSize       int           // Fontsize in points.
	X, Y           float64       // Position of first char's baseline.
	Dx, Dy         float64       // Horizontal and vertical offsets for X,Y.
	MTop, MBot     float64       // Top and bottom margins applied to text bounding box.
	MLeft, MRight  float64       // Left and right margins applied to text bounding box.
	MinHeight      float64       // The minimum height of this text's bounding box.
	Rotation       float64       // 0..360 degree rotation angle.
	ScaleAbs       bool          // Scaling type, true=absolute, false=relative to container dimensions.
	Scale          float64       // font scaling factor > 0 (and <= 1 for relative scaling).
	HAlign         HAlignment    // Horizontal text alignment.
	VAlign         VAlignment    // Vertical text alignment.
	RMode          RenderMode    // Text render mode
	StrokeCol      SimpleColor   // Stroke color to be used for rendering text corresponding to RMode.
	FillCol        SimpleColor   // Fill color to be used for rendering text corresponding to RMode.
	ShowTextBB     bool          // Render bounding box including BackgroundCol, border and margins.
	ShowBackground bool          // Render background of bounding box using BackgroundCol.
	BackgroundCol  SimpleColor   // Bounding box fill color.
	ShowBorder     bool          // Render border using BorderCol, BorderWidth and BorderStyle.
	BorderWidth    float64       // Border width, visibility depends on ShowBorder.
	BorderStyle    LineJoinStyle // Border style, also visible if ShowBorder is false as long as ShowBackground is true.
	BorderCol      SimpleColor   // Border color.
	ParIndent      bool          // Indent first line of paragraphs or space between paragraphs.
	ShowLineBB     bool          // Render line bounding boxes in black (for HAlign != AlignJustify only)
	ShowMargins    bool          // Render margins in light gray.
	HairCross      bool          // Draw haircross at X,Y.
}

TextDescriptor contains all attributes needed for rendering a text column in PDF user space.

type VAlignment

type VAlignment int

VAlignment represents the vertical alignment of text.

const (
	AlignBaseline VAlignment = iota
	AlignTop
	AlignMiddle
	AlignBottom
)

These are the options for vertical aligned text.

type Version

type Version int

Version is a type for the internal representation of PDF versions.

const (
	V10 Version = iota
	V11
	V12
	V13
	V14
	V15
	V16
	V17
)

Constants for all PDF versions up to v1.7

func PDFVersion

func PDFVersion(versionStr string) (Version, error)

PDFVersion returns the PDFVersion for a version string.

func (Version) String

func (v Version) String() string

String returns a string representation for a given PDFVersion.

type Watermark

type Watermark struct {
	// configuration
	Mode              int           // WMText, WMImage or WMPDF
	TextString        string        // raw display text.
	TextLines         []string      // display multiple lines of text.
	URL               string        // overlay link annotation for stamps.
	FileName          string        // display pdf page or png image.
	Image             io.Reader     // reader for image watermark.
	Page              int           // the page number of a PDF file. 0 means multistamp/multiwatermark.
	OnTop             bool          // if true this is a STAMP else this is a WATERMARK.
	InpUnit           DisplayUnit   // input display unit.
	Pos               Anchor        // position anchor, one of tl,tc,tr,l,c,r,bl,bc,br.
	Dx, Dy            int           // anchor offset.
	HAlign            *HAlignment   // horizonal alignment for text watermarks.
	FontName          string        // supported are Adobe base fonts only. (as of now: Helvetica, Times-Roman, Courier)
	FontSize          int           // font scaling factor.
	ScaledFontSize    int           // font scaling factor for a specific page
	RTL               bool          // if true, render text from right to left
	Color             SimpleColor   // text fill color(=non stroking color) for backwards compatibility.
	FillColor         SimpleColor   // text fill color(=non stroking color).
	StrokeColor       SimpleColor   // text stroking color
	BgColor           *SimpleColor  // text bounding box background color
	MLeft, MRight     int           // left and right bounding box margin
	MTop, MBot        int           // top and bottom bounding box margin
	BorderWidth       int           // Border width, visible if BgColor is set.
	BorderStyle       LineJoinStyle // Border style (bounding box corner style), visible if BgColor is set.
	BorderColor       *SimpleColor  // border color
	Rotation          float64       // rotation to apply in degrees. -180 <= x <= 180
	Diagonal          int           // paint along the diagonal.
	UserRotOrDiagonal bool          // true if one of rotation or diagonal provided overriding the default.
	Opacity           float64       // opacity of the watermark. 0 <= x <= 1
	RenderMode        RenderMode    // fill=0, stroke=1 fill&stroke=2
	Scale             float64       // relative scale factor: 0 <= x <= 1, absolute scale factor: 0 <= x
	ScaleEff          float64       // effective scale factor
	ScaleAbs          bool          // true for absolute scaling.
	Update            bool          // true for updating instead of adding a page watermark.
	// contains filtered or unexported fields
}

Watermark represents the basic structure and command details for the commands "Stamp" and "Watermark".

func DefaultWatermarkConfig

func DefaultWatermarkConfig() *Watermark

DefaultWatermarkConfig returns the default configuration.

func ParseImageWatermarkDetails

func ParseImageWatermarkDetails(fileName, desc string, onTop bool, u DisplayUnit) (*Watermark, error)

ParseImageWatermarkDetails parses an image Watermark/Stamp command string into an internal structure.

func ParsePDFWatermarkDetails

func ParsePDFWatermarkDetails(fileName, desc string, onTop bool, u DisplayUnit) (*Watermark, error)

ParsePDFWatermarkDetails parses a PDF Watermark/Stamp command string into an internal structure.

func ParseTextWatermarkDetails

func ParseTextWatermarkDetails(text, desc string, onTop bool, u DisplayUnit) (*Watermark, error)

ParseTextWatermarkDetails parses a text Watermark/Stamp command string into an internal structure.

func (Watermark) OnTopString

func (wm Watermark) OnTopString() string

OnTopString returns "watermark" or "stamp" whichever applies.

func (*Watermark) Recycle

func (wm *Watermark) Recycle()

func (Watermark) String

func (wm Watermark) String() string

type WriteContext

type WriteContext struct {

	// The PDF-File which gets generated.
	*bufio.Writer                     // A writer associated with Fp.
	Fp                  *os.File      // A file pointer needed for detecting FileSize.
	FileSize            int64         // The size of the written file.
	DirName             string        // The output directory.
	FileName            string        // The output file name.
	SelectedPages       IntSet        // For split, trim and extract.
	BinaryTotalSize     int64         // total stream data, counts 100% all stream data written.
	BinaryImageSize     int64         // total image stream data written = Read.BinaryImageSize.
	BinaryFontSize      int64         // total font stream data (fontfiles) = copy of Read.BinaryFontSize.
	Table               map[int]int64 // object write offsets
	Offset              int64         // current write offset
	WriteToObjectStream bool          // if true start to embed objects into object streams and obey ObjectStreamMaxObjects.
	CurrentObjStream    *int          // if not nil, any new non-stream-object gets added to the object stream with this object number.
	Eol                 string        // end of line char sequence
	Increment           bool          // Write context as PDF increment.
	ObjNrs              []int         // Increment candidate object numbers.
	OffsetPrevXRef      *int64        // Increment trailer entry "Prev".
}

WriteContext represents the context for writing a PDF file.

func NewWriteContext

func NewWriteContext(eol string) *WriteContext

NewWriteContext returns a new WriteContext.

func (*WriteContext) HasWriteOffset

func (wc *WriteContext) HasWriteOffset(objNumber int) bool

HasWriteOffset returns true if an object has already been written to PDFDestination.

func (*WriteContext) IncrementWithObjNr

func (wc *WriteContext) IncrementWithObjNr(i int)

IncrementWithObjNr adds obj# i to wc for writing.

func (*WriteContext) LogStats

func (wc *WriteContext) LogStats()

LogStats logs stats for written file.

func (*WriteContext) SetWriteOffset

func (wc *WriteContext) SetWriteOffset(objNumber int)

SetWriteOffset saves the current write offset to the PDFDestination.

func (*WriteContext) WriteEol

func (wc *WriteContext) WriteEol() error

WriteEol writes an end of line sequence.

type XRefStreamDict

type XRefStreamDict struct {
	StreamDict
	Size           int
	Objects        []int
	W              [3]int
	PreviousOffset *int64
}

XRefStreamDict represents a cross reference stream dictionary.

func NewXRefStreamDict

func NewXRefStreamDict(ctx *Context) *XRefStreamDict

NewXRefStreamDict creates a new PDFXRefStreamDict object.

type XRefTable

type XRefTable struct {
	Table               map[int]*XRefTableEntry
	Size                *int             // Object count from PDF trailer dict.
	PageCount           int              // Number of pages.
	Root                *IndirectRef     // Pointer to catalog (reference to root object).
	RootDict            Dict             // Catalog
	Names               map[string]*Node // Cache for name trees as found in catalog.
	Encrypt             *IndirectRef     // Encrypt dict.
	E                   *Enc
	EncKey              []byte // Encrypt key.
	AES4Strings         bool
	AES4Streams         bool
	AES4EmbeddedStreams bool

	// PDF Version
	HeaderVersion *Version // The PDF version the source is claiming to us as per its header.
	RootVersion   *Version // Optional PDF version taking precedence over the header version.

	// Document information section
	ID           Array        // from trailer
	Info         *IndirectRef // Infodict (reference to info dict object)
	Title        string
	Subject      string
	Keywords     string
	Author       string
	Creator      string
	Producer     string
	CreationDate string
	ModDate      string
	Properties   map[string]string

	// Linearization section (not yet supported)
	OffsetPrimaryHintTable  *int64
	OffsetOverflowHintTable *int64
	LinearizationObjs       IntSet

	// Page annotation cache
	PageAnnots map[int]PgAnnots

	// Thumbnail images
	PageThumbs map[int]IndirectRef

	// Offspec section
	AdditionalStreams *Array // array of IndirectRef - trailer :e.g., Oasis "Open Doc"

	// Statistics
	Stats PDFStats

	Tagged bool // File is using tags. This is important for ???

	// Validation
	CurPage        int                       // current page during validation
	CurObj         int                       // current object during validation, the last dereferenced object
	ValidationMode int                       // see Configuration
	ValidateLinks  bool                      // check for broken links in LinkAnnotations/URIDicts.
	Valid          bool                      // true means successful validated against ISO 32000.
	URIs           map[int]map[string]string // URIs for link checking

	Optimized      bool
	Watermarked    bool
	AcroForm       Dict
	SignatureExist bool
	AppendOnly     bool
}

XRefTable represents a PDF cross reference table plus stats for a PDF file.

func CreateAcroFormDemoXRef

func CreateAcroFormDemoXRef() (*XRefTable, error)

CreateAcroFormDemoXRef creates an xRefTable with an AcroForm example.

func CreateAnnotationDemoXRef

func CreateAnnotationDemoXRef() (*XRefTable, error)

CreateAnnotationDemoXRef creates a PDF file with examples of annotations and actions.

func CreateDemoXRef

func CreateDemoXRef(p Page) (*XRefTable, error)

CreateDemoXRef creates a minimal single page PDF file for demo purposes.

func CreateResourceDictInheritanceDemoXRef

func CreateResourceDictInheritanceDemoXRef() (*XRefTable, error)

CreateResourceDictInheritanceDemoXRef creates a page tree for testing resource dict inheritance.

func CreateXRefTableWithRootDict

func CreateXRefTableWithRootDict() (*XRefTable, error)

func (*XRefTable) Annotation

func (xRefTable *XRefTable) Annotation(d Dict) (AnnotationRenderer, error)

Annotation returns an annotation renderer. Validation sets up a cache of annotation renderers.

func (*XRefTable) AppendContent

func (xRefTable *XRefTable) AppendContent(pageDict Dict, bb []byte) error

AppendContent appends bb to pageDict's content stream.

func (*XRefTable) BindNameTrees

func (xRefTable *XRefTable) BindNameTrees() error

BindNameTrees syncs up the internal name tree cache with the xreftable.

func (*XRefTable) Catalog

func (xRefTable *XRefTable) Catalog() (Dict, error)

Catalog returns a pointer to the root object / catalog.

func (*XRefTable) CatalogHasPieceInfo

func (xRefTable *XRefTable) CatalogHasPieceInfo() (bool, error)

CatalogHasPieceInfo returns true if the root has an entry for \"PieceInfo\".

func (*XRefTable) ColorSpaceComponents

func (xRefTable *XRefTable) ColorSpaceComponents(sd *StreamDict) (int, error)

ColorSpaceComponents returns the corresponding number of used color components for sd's colorspace.

func (*XRefTable) DeleteObjectGraph

func (xRefTable *XRefTable) DeleteObjectGraph(o Object) error

DeleteObjectGraph deletes all objects reachable by indRef.

func (*XRefTable) Dereference

func (xRefTable *XRefTable) Dereference(o Object) (Object, error)

Dereference resolves an indirect object and returns the resulting PDF object.

func (*XRefTable) DereferenceArray

func (xRefTable *XRefTable) DereferenceArray(o Object) (Array, error)

DereferenceArray resolves and validates an array object, which may be an indirect reference.

func (*XRefTable) DereferenceBoolean

func (xRefTable *XRefTable) DereferenceBoolean(o Object, sinceVersion Version) (*Boolean, error)

DereferenceBoolean resolves and validates a boolean object, which may be an indirect reference.

func (*XRefTable) DereferenceCSVSafeText

func (xRefTable *XRefTable) DereferenceCSVSafeText(o Object) (string, error)

DereferenceCSVSafeText resolves and validates a string or hex literal object to a string.

func (*XRefTable) DereferenceDict

func (xRefTable *XRefTable) DereferenceDict(o Object) (Dict, error)

DereferenceDict resolves and validates a dictionary object, which may be an indirect reference.

func (*XRefTable) DereferenceDictEntry

func (xRefTable *XRefTable) DereferenceDictEntry(d Dict, key string) (Object, error)

DereferenceDictEntry returns a dereferenced dict entry.

func (*XRefTable) DereferenceInteger

func (xRefTable *XRefTable) DereferenceInteger(o Object) (*Integer, error)

DereferenceInteger resolves and validates an integer object, which may be an indirect reference.

func (*XRefTable) DereferenceName

func (xRefTable *XRefTable) DereferenceName(o Object, sinceVersion Version, validate func(string) bool) (n Name, err error)

DereferenceName resolves and validates a name object, which may be an indirect reference.

func (*XRefTable) DereferenceNumber

func (xRefTable *XRefTable) DereferenceNumber(o Object) (float64, error)

DereferenceNumber resolves a number object, which may be an indirect reference and returns a float64.

func (*XRefTable) DereferenceStreamDict

func (xRefTable *XRefTable) DereferenceStreamDict(o Object) (*StreamDict, bool, error)

DereferenceStreamDict resolves stream dictionary objects.

func (*XRefTable) DereferenceStringEntryBytes

func (xRefTable *XRefTable) DereferenceStringEntryBytes(d Dict, key string) ([]byte, error)

DereferenceStringEntryBytes returns the bytes of a string entry of d.

func (*XRefTable) DereferenceStringLiteral

func (xRefTable *XRefTable) DereferenceStringLiteral(o Object, sinceVersion Version, validate func(string) bool) (s StringLiteral, err error)

DereferenceStringLiteral resolves and validates a string literal object, which may be an indirect reference.

func (*XRefTable) DereferenceStringOrHexLiteral

func (xRefTable *XRefTable) DereferenceStringOrHexLiteral(obj Object, sinceVersion Version, validate func(string) bool) (s string, err error)

DereferenceStringOrHexLiteral resolves and validates a string or hex literal object, which may be an indirect reference.

func (*XRefTable) DereferenceText

func (xRefTable *XRefTable) DereferenceText(o Object) (string, error)

DereferenceText resolves and validates a string or hex literal object to a string.

func (*XRefTable) EncryptDict

func (xRefTable *XRefTable) EncryptDict() (Dict, error)

EncryptDict returns a pointer to the root object / catalog.

func (*XRefTable) EnsureCollection

func (xRefTable *XRefTable) EnsureCollection() error

EnsureCollection makes sure there is a Collection entry in the catalog. Needed for portfolio / portable collections eg. for file attachments.

func (*XRefTable) EnsurePageCount

func (xRefTable *XRefTable) EnsurePageCount() error

EnsurePageCount evaluates the page count for xRefTable if necessary. Important when validation is turned off.

func (*XRefTable) EnsureValidFreeList

func (xRefTable *XRefTable) EnsureValidFreeList() error

EnsureValidFreeList ensures the integrity of the free list associated with the recorded free objects. See 7.5.4 Cross-Reference Table

func (*XRefTable) EnsureVersionForWriting

func (xRefTable *XRefTable) EnsureVersionForWriting()

EnsureVersionForWriting sets the version to the highest supported PDF Version 1.7. This is necessary to allow validation after adding features not supported by the original version of a document as during watermarking.

func (*XRefTable) Exists

func (xRefTable *XRefTable) Exists(objNr int) bool

Exists returns true if xRefTable contains an entry for objNumber.

func (*XRefTable) Find

func (xRefTable *XRefTable) Find(objNr int) (*XRefTableEntry, bool)

Find returns the XRefTable entry for given object number.

func (*XRefTable) FindObject

func (xRefTable *XRefTable) FindObject(objNr int) (Object, error)

FindObject returns the object of the XRefTableEntry for a specific object number.

func (*XRefTable) FindTableEntry

func (xRefTable *XRefTable) FindTableEntry(objNr int, genNr int) (*XRefTableEntry, bool)

FindTableEntry returns the XRefTable entry for given object and generation numbers.

func (*XRefTable) FindTableEntryForIndRef

func (xRefTable *XRefTable) FindTableEntryForIndRef(ir *IndirectRef) (*XRefTableEntry, bool)

FindTableEntryForIndRef returns the XRefTable entry for given indirect reference.

func (*XRefTable) FindTableEntryLight

func (xRefTable *XRefTable) FindTableEntryLight(objNr int) (*XRefTableEntry, bool)

FindTableEntryLight returns the XRefTable entry for given object number.

func (*XRefTable) Free

func (xRefTable *XRefTable) Free(objNr int) (*XRefTableEntry, error)

Free returns the cross ref table entry for given number of a free object.

func (*XRefTable) IDFirstElement

func (xRefTable *XRefTable) IDFirstElement() (id []byte, err error)

IDFirstElement returns the first element of ID.

func (*XRefTable) IndRefForNewObject

func (xRefTable *XRefTable) IndRefForNewObject(obj Object) (*IndirectRef, error)

IndRefForNewObject inserts an object into the xRefTable and returns an indirect reference to it.

func (*XRefTable) InsertAndUseRecycled

func (xRefTable *XRefTable) InsertAndUseRecycled(xRefTableEntry XRefTableEntry) (objNr int, err error)

InsertAndUseRecycled adds given xRefTableEntry into the cross reference table utilizing the freelist.

func (*XRefTable) InsertBlankPages

func (xRefTable *XRefTable) InsertBlankPages(pages IntSet, before bool) error

InsertBlankPages inserts a blank page before or after each selected page.

func (*XRefTable) InsertNew

func (xRefTable *XRefTable) InsertNew(xRefTableEntry XRefTableEntry) (objNr int)

InsertNew adds given xRefTableEntry at next new objNumber into the cross reference table. Only to be called once an xRefTable has been generated completely and all trailer dicts have been processed. xRefTable.Size is the size entry of the first trailer dict processed. Called on creation of new object streams. Called by InsertAndUseRecycled.

func (*XRefTable) InsertObject

func (xRefTable *XRefTable) InsertObject(obj Object) (objNr int, err error)

InsertObject inserts an object into the xRefTable.

func (*XRefTable) IsLinearizationObject

func (xRefTable *XRefTable) IsLinearizationObject(i int) bool

IsLinearizationObject returns true if object #i is a a linearization object.

func (*XRefTable) IsValid

func (xRefTable *XRefTable) IsValid(ir IndirectRef) (bool, error)

IsValid returns true if the object referenced by ir has already been validated.

func (*XRefTable) LinearizationObjsString

func (xRefTable *XRefTable) LinearizationObjsString() (int, string)

LinearizationObjsString returns a formatted string and the number of objs.

func (*XRefTable) ListAnnotations

func (xRefTable *XRefTable) ListAnnotations(selectedPages IntSet) (int, []string, error)

ListAnnotations returns a formatted list of annotations for selected pages.

func (*XRefTable) LocateNameTree

func (xRefTable *XRefTable) LocateNameTree(nameTreeName string, ensure bool) error

LocateNameTree locates/ensures a specific name tree.

func (*XRefTable) MissingObjects

func (xRefTable *XRefTable) MissingObjects() (int, *string)

MissingObjects returns the number of objects that were not written plus the corresponding comma separated string representation.

func (*XRefTable) NamesDict

func (xRefTable *XRefTable) NamesDict() (Dict, error)

NamesDict returns the dict that contains all name trees.

func (*XRefTable) NewEmbeddedFileStreamDict

func (xRefTable *XRefTable) NewEmbeddedFileStreamDict(filename string) (*IndirectRef, error)

NewEmbeddedFileStreamDict returns an embeddedFileStreamDict containing the file "filename".

func (*XRefTable) NewEmbeddedStreamDict

func (xRefTable *XRefTable) NewEmbeddedStreamDict(r io.Reader, modDate time.Time) (*IndirectRef, error)

NewEmbeddedStreamDict creates and returns an embeddedStreamDict containing the bytes represented by r.

func (*XRefTable) NewFileSpecDict

func (xRefTable *XRefTable) NewFileSpecDict(f, uf, desc string, indRefStreamDict IndirectRef) (Dict, error)

NewFileSpecDict creates and returns a new fileSpec dictionary.

func (*XRefTable) NewFileSpectDictForAttachment

func (xRefTable *XRefTable) NewFileSpectDictForAttachment(a Attachment) (*IndirectRef, error)

NewFileSpectDictForAttachment returns a fileSpecDict for a.

func (*XRefTable) NewSoundStreamDict

func (xRefTable *XRefTable) NewSoundStreamDict(filename string, samplingRate int, fileSpecDict Dict) (*IndirectRef, error)

NewSoundStreamDict returns a new sound stream dict.

func (*XRefTable) NewStreamDictForBuf

func (xRefTable *XRefTable) NewStreamDictForBuf(buf []byte) (*StreamDict, error)

NewStreamDictForBuf creates a streamDict for buf.

func (*XRefTable) NewStreamDictForFile

func (xRefTable *XRefTable) NewStreamDictForFile(filename string) (*StreamDict, error)

NewStreamDictForFile creates a streamDict for filename.

func (*XRefTable) NextForFree

func (xRefTable *XRefTable) NextForFree(objNr int) (int, error)

NextForFree returns the number of the object the free object with objNumber links to. This is the successor of this free object in the free list.

func (*XRefTable) Outlines

func (xRefTable *XRefTable) Outlines() (*IndirectRef, error)

Outlines returns the Outlines reference contained in the catalog.

func (*XRefTable) PageBoundaries

func (xRefTable *XRefTable) PageBoundaries() ([]PageBoundaries, error)

PageBoundaries returns a sorted slice with page boundaries for all pages sorted ascending by page number.

func (*XRefTable) PageContent

func (xRefTable *XRefTable) PageContent(d Dict) ([]byte, error)

PageContent returns the content in PDF syntax for page dict d.

func (*XRefTable) PageDict

func (xRefTable *XRefTable) PageDict(pageNr int, consolidateRes bool) (Dict, *IndirectRef, *InheritedPageAttrs, error)

PageDict returns a specific page dict along with the resources, mediaBox and CropBox in effect. consolidateRes ensures optimized resources in InheritedPageAttrs.

func (*XRefTable) PageDictIndRef

func (xRefTable *XRefTable) PageDictIndRef(page int) (*IndirectRef, error)

PageDictIndRef returns the pageDict IndRef for a logical page number.

func (*XRefTable) PageDims

func (xRefTable *XRefTable) PageDims() ([]Dim, error)

PageDims returns a sorted slice with effective media box dimensions for all pages sorted ascending by page number.

func (*XRefTable) PageNumber

func (xRefTable *XRefTable) PageNumber(pageObjNr int) (int, error)

PageNumber returns the logical page number for a page dict object number.

func (*XRefTable) Pages

func (xRefTable *XRefTable) Pages() (*IndirectRef, error)

Pages returns the Pages reference contained in the catalog.

func (*XRefTable) ParseRootVersion

func (xRefTable *XRefTable) ParseRootVersion() (v *string, err error)

ParseRootVersion returns a string representation for an optional Version entry in the root object.

func (*XRefTable) RemoveCollection

func (xRefTable *XRefTable) RemoveCollection() error

RemoveCollection removes an existing Collection entry from the catalog.

func (*XRefTable) RemoveEmbeddedFilesNameTree

func (xRefTable *XRefTable) RemoveEmbeddedFilesNameTree() error

RemoveEmbeddedFilesNameTree removes both the embedded files name tree and the Collection dict.

func (*XRefTable) RemoveNameTree

func (xRefTable *XRefTable) RemoveNameTree(nameTreeName string) error

RemoveNameTree removes a specific name tree. Also removes a resulting empty names dict.

func (*XRefTable) SetValid

func (xRefTable *XRefTable) SetValid(ir IndirectRef) error

SetValid marks the xreftable entry of the object referenced by ir as valid.

func (*XRefTable) UndeleteObject

func (xRefTable *XRefTable) UndeleteObject(objectNumber int) error

UndeleteObject ensures an object is not recorded in the free list. e.g. sometimes caused by indirect references to free objects in the original PDF file.

func (*XRefTable) ValidateVersion

func (xRefTable *XRefTable) ValidateVersion(element string, sinceVersion Version) error

ValidateVersion validates against the xRefTable's version.

func (*XRefTable) Version

func (xRefTable *XRefTable) Version() Version

Version returns the PDF version of the PDF writer that created this file. Before V1.4 this is the header version. Since V1.4 the catalog may contain a Version entry which takes precedence over the header version.

func (*XRefTable) VersionString

func (xRefTable *XRefTable) VersionString() string

VersionString return a string representation for this PDF files PDF version.

type XRefTableEntry

type XRefTableEntry struct {
	Free            bool
	Offset          *int64
	Generation      *int
	RefCount        int
	Object          Object
	Compressed      bool
	ObjectStream    *int
	ObjectStreamInd *int
	Valid           bool
}

XRefTableEntry represents an entry in the PDF cross reference table.

This may wrap a free object, a compressed object or any in use PDF object:

Dict, StreamDict, ObjectStreamDict, PDFXRefStreamDict, Array, Integer, Float, Name, StringLiteral, HexLiteral, Boolean

func NewFreeHeadXRefTableEntry

func NewFreeHeadXRefTableEntry() *XRefTableEntry

NewFreeHeadXRefTableEntry returns the xref table entry for object 0 which is per definition the head of the free list (list of free objects).

func NewXRefTableEntryGen0

func NewXRefTableEntryGen0(obj Object) *XRefTableEntry

NewXRefTableEntryGen0 returns a cross reference table entry for an object with generation 0.

Directories

Path Synopsis
Package validate implements validation against PDF 32000-1:2008.
Package validate implements validation against PDF 32000-1:2008.

Jump to

Keyboard shortcuts

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