model

package
v0.0.0-...-4e20295 Latest Latest
Warning

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

Go to latest
Published: May 22, 2024 License: MIT Imports: 35 Imported by: 0

Documentation

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
)
View Source
const (
	PermissionsNone  = PermissionFlags(0xF0C3)
	PermissionsPrint = PermissionsNone + PermissionPrintRev2 + PermissionPrintRev3
	PermissionsAll   = PermissionFlags(0xFFFF)
)
View Source
const (
	RightDown orientation = iota
	DownRight
	LeftDown
	DownLeft
)

These are the defined anchors for relative positioning.

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 (
	DegToRad = math.Pi / 180
	RadToDeg = 180 / math.Pi
)
View Source
const (
	NoDiagonal = iota
	DiagonalLLToUR
	DiagonalULToLR
)

Rotation along one of 2 diagonals

View Source
const (
	WMText = iota
	WMImage
	WMPDF
)

Watermark mode

View Source
const (

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

Variables

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

If you want to disable config dir usage in a multi threaded environment you are encouraged to use pdf.DisableConfigDir().

View Source
var CutParamMap = cutParameterMap{
	"horizontalCut": parseHorCut,
	"verticalCut":   parseVertCut,
	"dimensions":    parseDimensionsCut,
	"formsize":      parsePageFormatCut,
	"papersize":     parsePageFormatCut,
	"scalefactor":   parseScaleFactorCut,
	"border":        parseBorderCut,
	"margin":        parseMarginCut,
	"bgcolor":       parseBackgroundColorCut,
}
View Source
var DestinationTypeStrings = map[DestinationType]string{
	DestXYZ:   "XYZ",
	DestFit:   "Fit",
	DestFitH:  "FitH",
	DestFitV:  "FitV",
	DestFitR:  "FitR",
	DestFitB:  "FitB",
	DestFitBH: "FitBH",
	DestFitBV: "FitBV",
}

DestinationTypeStrings manages string representations for destination types.

View Source
var ErrNoContent = errors.New("pdfcpu: page without content")
View Source
var ResizeParamMap = resizeParameterMap{
	"dimensions":  parseDimensionsRes,
	"enforce":     parseEnforceOrientation,
	"formsize":    parsePageFormatRes,
	"papersize":   parsePageFormatRes,
	"scalefactor": parseScaleFactorRes,
	"bgcolor":     parseBackgroundColorRes,
	"border":      parseBorderRes,
}
View Source
var VersionStr = "v0.8.0 dev"

VersionStr is the current pdfcpu version.

View Source
var ZoomParamMap = zoomParameterMap{
	"factor":  parseZoomFactor,
	"hmargin": parseHMargin,
	"vmargin": parseVMargin,
	"bgcolor": parseBackgroundColorZoom,
	"border":  parseBorderZoom,
}

Functions

func AnchorPosAndAlign

func AnchorPosAndAlign(a types.Anchor, r *types.Rectangle) (x, y float64, hAlign types.HAlignment, vAlign types.VAlignment)

AnchorPosAndAlign calculates position and alignment for an anchored rectangle r.

func AppendPageTree

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

AppendPageTree appends a pagetree d1 to page tree d2.

func ApplyBox

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

func CSVSafeString

func CSVSafeString(s string) string

func CalcBoundingBox

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

func CalcBoundingBoxForRects

func CalcBoundingBoxForRects(r1, r2 *types.Rectangle) *types.Rectangle

func ContentBytesForPageRotation

func ContentBytesForPageRotation(rot int, w, h float64) []byte

ContentBytesForPageRotation returns content bytes compensating for rot.

func CreateDCTImageObject

func CreateDCTImageObject(xRefTable *XRefTable, buf []byte, w, h, bpc int, cs string) (*types.StreamDict, error)

CreateDCTImageObject returns a DCT encoded stream dict.

func CreateImageResource

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

CreateImageResource creates a new XObject for given image data represented by r and applies optional filters.

func CreateImageStreamDict

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

CreateImageStreamDict returns a stream dict for image data represented by r and applies optional filters.

func DecodeUTF8ToByte

func DecodeUTF8ToByte(s string) string

func DetectKeywords

func DetectKeywords(line string) (endInd int, streamInd int, err error)

func DrawMargins

func DrawMargins(w io.Writer, c color.SimpleColor, colBB *types.Rectangle, borderWidth, mLeft, mRight, mTop, mBot float64)

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 EqualFontDicts

func EqualFontDicts(fd1, fd2 types.Dict, xRefTable *XRefTable) (bool, error)

EqualFontDicts returns true, if two font dicts are equal.

func EqualObjects

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

EqualObjects returns true if two objects are equal in the context of given xrefTable. Some object and an indirect reference to it are treated as equal. Objects may in fact be object trees.

func EqualStreamDicts

func EqualStreamDicts(sd1, sd2 *types.StreamDict, xRefTable *XRefTable) (bool, error)

EqualStreamDicts returns true if two stream dicts are equal and contain the same bytes.

func ImageFileName

func ImageFileName(fileName string) bool

ImageFileName returns true for supported image file types.

func ImageFileNames

func ImageFileNames(dir string, maxFileSize types.ByteSize) ([]string, error)

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

func LowerLeftCorner

func LowerLeftCorner(vp *types.Rectangle, bbw, bbh float64, a types.Anchor) types.Point

LowerLeftCorner returns the lower left corner for a bounding box anchored onto vp.

func NUpTilePDFBytes

func NUpTilePDFBytes(wr io.Writer, rSrc, rDest *types.Rectangle, formResID string, nup *NUp, rotate, enforceOrient bool)

NUpTilePDFBytesForPDF applies nup tiles to content bytes.

func ObjectStreamDict

func ObjectStreamDict(sd *types.StreamDict) (*types.ObjectStreamDict, error)

ObjectStreamDict creates a ObjectStreamDict out of a StreamDict.

func ParseObject

func ParseObject(line *string) (types.Object, error)

ParseObject parses next Object from string buffer and returns the updated (left clipped) buffer.

func ParseObjectAttributes

func ParseObjectAttributes(line *string) (objectNumber *int, generationNumber *int, err error)

ParseObjectAttributes parses object number and generation of the next object for given string buffer.

func ParseObjectContext

func ParseObjectContext(c context.Context, line *string) (types.Object, error)

ParseObjectContext parses next Object from string buffer and returns the updated (left clipped) buffer. If the passed context is cancelled, parsing will be interrupted.

func ParseXRefStreamDict

func ParseXRefStreamDict(sd *types.StreamDict) (*types.XRefStreamDict, error)

ParseXRefStreamDict creates a XRefStreamDict out of a StreamDict.

func PrepBytes

func PrepBytes(xRefTable *XRefTable, s, fontName string, embed, rtl bool) string

func ProcessRefCounts

func ProcessRefCounts(xRefTable *XRefTable, o types.Object)

func SplitMultilineStr

func SplitMultilineStr(s string) []string

func Text

func Text(o types.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 ValidationTimingStats

func ValidationTimingStats(dur1, dur2, dur float64)

ValidationTimingStats prints processing time stats for validation.

func WriteColumn

func WriteColumn(xRefTable *XRefTable, w io.Writer, mediaBox, region *types.Rectangle, td TextDescriptor, width float64) *types.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(xRefTable *XRefTable, w io.Writer, mediaBox, region *types.Rectangle, td TextDescriptor, a types.Anchor, width float64) *types.Rectangle

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

func WriteMultiLine

func WriteMultiLine(xRefTable *XRefTable, w io.Writer, mediaBox, region *types.Rectangle, td TextDescriptor) *types.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(xRefTable *XRefTable, w io.Writer, mediaBox, region *types.Rectangle, td TextDescriptor, a types.Anchor) *types.Rectangle

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

Types

type Annot

type Annot struct {
	IndRefs *[]types.IndirectRef
	Map     AnnotMap
}

type AnnotMap

type AnnotMap map[int]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     types.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        *types.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        *color.SimpleColor // The background color of the annotation’s icon when closed.
}

Annotation represents a PDF annnotation.

func NewAnnotation

func NewAnnotation(
	typ AnnotationType,
	rect types.Rectangle,
	contents string,
	pageIndRef *types.IndirectRef,
	nm string,
	f AnnotationFlags,
	col *color.SimpleColor) Annotation

NewAnnotation returns a new annotation.

func NewAnnotationForRawType

func NewAnnotationForRawType(
	typ string,
	rect types.Rectangle,
	contents string,
	pageIndRef *types.IndirectRef,
	nm string,
	f AnnotationFlags,
	col *color.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(xRefTable *XRefTable, pageIndRef types.IndirectRef) (types.Dict, error)

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(xRefTable *XRefTable, pageIndRef types.IndirectRef) (types.Dict, error)
	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 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 BookletBinding

type BookletBinding int
const (
	LongEdge BookletBinding = iota
	ShortEdge
)

func (BookletBinding) String

func (b BookletBinding) String() string

type BookletPage

type BookletPage struct {
	Number int
	Rotate bool
}

type BookletType

type BookletType int
const (
	Booklet BookletType = iota
	BookletAdvanced
	BookletPerfectBound
)

These are the types of booklet layouts.

func (BookletType) String

func (b BookletType) String() string

type BorderStyle

type BorderStyle int

BorderStyle (see table 168)

const (
	BSSolid BorderStyle = iota
	BSDashed
	BSBeveled
	BSInset
	BSUnderline
)

type BorderStyling

type BorderStyling struct {
	Color     *color.SimpleColor
	LineStyle *types.LineJoinStyle
	Width     float64
}

type Box

type Box struct {
	Rect      *types.Rectangle `json:"rect"` // Rectangle in user space.
	Inherited bool             `json:"-"`    // Media box and Crop box may be inherited.
	RefBox    string           `json:"-"`    // Use position of another box,
	// Margins to parent box in points.
	// Relative to parent box if 0 < x < 0.5
	MLeft, MRight float64 `json:"-"`
	MTop, MBot    float64 `json:"-"`
	// Relative position within parent box
	Dim    *types.Dim   `json:"-"` // dimensions
	Pos    types.Anchor `json:"-"` // position anchor within parent box, one of tl,tc,tr,l,c,r,bl,bc,br.
	Dx, Dy int          `json:"-"` // 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 types.DisplayUnit) (*Box, error)

ParseBox parses a box definition.

type CircleAnnotation

type CircleAnnotation struct {
	Annotation
	FillCol               *color.SimpleColor
	Margins               types.Array
	BorderWidth           float64
	BorderStyle           BorderStyle
	CloudyBorder          bool
	CloudyBorderIntensity int // 0,1,2
}

CircleAnnotation represents a square annotation.

func NewCircleAnnotation

func NewCircleAnnotation(
	rect types.Rectangle,
	contents string,
	id string,
	f AnnotationFlags,
	borderWidth float64,
	borderStyle BorderStyle,
	borderCol *color.SimpleColor,
	cloudyBorder bool,
	cloudyBorderIntensity int,
	fillCol *color.SimpleColor,
	MLeft, MTop, MRight, MBot float64) CircleAnnotation

NewCircleAnnotation returns a new circle annotation.

func (CircleAnnotation) RenderDict

func (ann CircleAnnotation) RenderDict(xRefTable *XRefTable, pageIndRef types.IndirectRef) (types.Dict, error)

RenderDict renders ann into a page annotation dict.

type CommandMode

type CommandMode int

CommandMode specifies the operation being executed.

const (
	VALIDATE CommandMode = iota
	LISTINFO
	OPTIMIZE
	SPLIT
	SPLITBYPAGENR
	MERGECREATE
	MERGECREATEZIP
	MERGEAPPEND
	EXTRACTIMAGES
	EXTRACTFONTS
	EXTRACTPAGES
	EXTRACTCONTENT
	EXTRACTMETADATA
	TRIM
	LISTATTACHMENTS
	EXTRACTATTACHMENTS
	ADDATTACHMENTS
	ADDATTACHMENTSPORTFOLIO
	REMOVEATTACHMENTS
	LISTPERMISSIONS
	SETPERMISSIONS
	ADDWATERMARKS
	REMOVEWATERMARKS
	IMPORTIMAGES
	INSERTPAGESBEFORE
	INSERTPAGESAFTER
	REMOVEPAGES
	LISTKEYWORDS
	ADDKEYWORDS
	REMOVEKEYWORDS
	LISTPROPERTIES
	ADDPROPERTIES
	REMOVEPROPERTIES
	COLLECT
	CROP
	LISTBOXES
	ADDBOXES
	REMOVEBOXES
	LISTANNOTATIONS
	ADDANNOTATIONS
	REMOVEANNOTATIONS
	ROTATE
	NUP
	BOOKLET
	LISTBOOKMARKS
	ADDBOOKMARKS
	REMOVEBOOKMARKS
	IMPORTBOOKMARKS
	EXPORTBOOKMARKS
	LISTIMAGES
	CREATE
	DUMP
	LISTFORMFIELDS
	REMOVEFORMFIELDS
	LOCKFORMFIELDS
	UNLOCKFORMFIELDS
	RESETFORMFIELDS
	EXPORTFORMFIELDS
	FILLFORMFIELDS
	MULTIFILLFORMFIELDS
	ENCRYPT
	DECRYPT
	CHANGEUPW
	CHANGEOPW
	CHEATSHEETSFONTS
	INSTALLFONTS
	LISTFONTS
	RESIZE
	POSTER
	NDOWN
	CUT
	LISTPAGELAYOUT
	SETPAGELAYOUT
	RESETPAGELAYOUT
	LISTPAGEMODE
	SETPAGEMODE
	RESETPAGEMODE
	LISTVIEWERPREFERENCES
	SETVIEWERPREFERENCES
	RESETVIEWERPREFERENCES
	ZOOM
)

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

	// Enable validation right before writing.
	PostProcessValidate bool

	// 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 PermissionFlags // int16

	// Command being executed.
	Cmd CommandMode

	// Display unit in effect.
	Unit types.DisplayUnit

	// Timestamp format.
	TimestampFormat string

	// Date format.
	DateFormat string

	// Optimize.
	Optimize bool

	// Optimize page resources via content stream analysis.
	OptimizeResourceDicts bool

	// Optimize duplicate content streams across pages.
	OptimizeDuplicateContentStreams bool

	// Merge creates bookmarks
	CreateBookmarks bool

	// PDF Viewer is expected to supply appearance streams for form fields.
	NeedAppearances 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) SetUnit

func (c *Configuration) SetUnit(s string)

SetUnit configures the display unit.

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
	WritingPages bool // true, when writing page dicts.
	Dest         bool // true when writing a destination within a page.
}

Context represents an environment for processing PDF files.

func NewContext

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

NewContext initializes a new Context.

func (*Context) AddAttachment

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

AddAttachment adds a.

func (*Context) AddAttachmentsToInfoDigest

func (ctx *Context) AddAttachmentsToInfoDigest(ss *[]string) error

func (*Context) AddPageBoundaries

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

AddPageBoundaries adds page boundaries specified by pb for selected pages.

func (*Context) ConvertToUnit

func (ctx *Context) ConvertToUnit(d types.Dim) types.Dim

ConvertToUnit converts dimensions in point to inches,cm,mm

func (*Context) Crop

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

Crop sets crop box for selected pages to b.

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) ListAttachments

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

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

func (*Context) ListPageBoundaries

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

ListPageBoundaries lists page boundaries specified in wantPB for selected pages.

func (*Context) NUpTilePDFBytesForPDF

func (ctx *Context) NUpTilePDFBytesForPDF(
	pageNr int,
	formsResDict types.Dict,
	buf *bytes.Buffer,
	rDest *types.Rectangle,
	nup *NUp,
	rotate bool) error

NUpTilePDFBytesForPDF applies nup tiles from PDF.

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 types.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) 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, types.Object, error)

SearchEmbeddedFilesNameTreeNodeByContent tries to identify a name tree by content.

func (*Context) String

func (ctx *Context) String() string

func (*Context) UnitString

func (ctx *Context) UnitString() string

type Cut

type Cut struct {
	Hor      []float64          // Horizontal cut points
	Vert     []float64          // Vertical cut points
	Scale    float64            // scale factor x > 1 (poster)
	PageSize string             // paper/form size eg. A2,A3,A4,Legal,Ledger,...
	PageDim  *types.Dim         // page dimensions in display unit
	Unit     types.DisplayUnit  // display unit
	UserDim  bool               // true if dimensions set by dim rather than formsize
	Border   bool               // true to render crop box
	Margin   float64            // glue area in display unit
	BgColor  *color.SimpleColor // background color
	Origin   types.Corner       // one of 4 page corners, default = UpperLeft
}

type Destination

type Destination struct {
	Typ                      DestinationType
	PageNr                   int
	Left, Bottom, Right, Top int
	Zoom                     float32
}

Destination represents a PDF destination.

func (Destination) Array

func (dest Destination) Array(indRef types.IndirectRef) types.Array

func (Destination) Name

func (dest Destination) Name() types.Name

func (Destination) String

func (dest Destination) String() string

type DestinationType

type DestinationType int

DestinationType represents the various PDF destination types.

const (
	DestXYZ   DestinationType = iota // [page /XYZ left top zoom]
	DestFit                          // [page /Fit]
	DestFitH                         // [page /FitH top]
	DestFitV                         // [page /FitV left]
	DestFitR                         // [page /FitR left bottom right top]
	DestFitB                         // [page /FitB]
	DestFitBH                        // [page /FitBH top]
	DestFitBV                        // [page /FitBV left]
)

See table 151

type Direction

type Direction int
const (
	L2R Direction = iota
	R2L
)

func DirectionFor

func DirectionFor(s string) *Direction

func (*Direction) String

func (d *Direction) String() string

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 FieldAnnotation

type FieldAnnotation struct {
	Dict   types.Dict
	IndRef *types.IndirectRef
	Ind    int
	Field  bool
	Kids   types.Array
}

type FontMap

type FontMap map[string]FontResource

FontMap maps font names to font resources.

func DrawBookletGuides

func DrawBookletGuides(nup *NUp, w io.Writer) FontMap

DrawBookletGuides draws guides according to corresponding nup value.

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      types.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
	Lang      string
	CIDSet    *types.IndirectRef
	FontFile  *types.IndirectRef
	ToUnicode *types.IndirectRef
	W         *types.IndirectRef
}

FontResource represents an existing PDF font resource.

type Image

type Image struct {
	io.Reader
	Name        string // Resource name
	FileType    string
	PageNr      int
	ObjNr       int
	Width       int    // "Width"
	Height      int    // "Height"
	Bpc         int    // "BitsPerComponent"
	Cs          string // "ColorSpace"
	Comp        int    // color component count
	IsImgMask   bool   // "ImageMask"
	HasImgMask  bool   // "Mask"
	HasSMask    bool   // "SMask"
	Thumb       bool   // "Thumbnail"
	Interpol    bool   // "Interpolate"
	Size        int64  // "Length"
	Filter      string // filter pipeline
	DecodeParms string
}

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     *types.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 InheritedPageAttrs

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

InheritedPageAttrs represents all inherited page attributes.

type InkAnnotation

type InkAnnotation struct {
	MarkupAnnotation
	InkList []InkPath
	BS      types.Dict
	AP      types.Dict
}

func NewInkAnnotation

func NewInkAnnotation(
	rect types.Rectangle,
	contents, id, title string,
	ink []InkPath,
	bs types.Dict,
	f AnnotationFlags,
	bgCol *color.SimpleColor,
	ca *float64,
	rc, subj string,
	ap types.Dict,
) InkAnnotation

NewInkAnnotation returns a new ink annotation.

func (InkAnnotation) RenderDict

func (ann InkAnnotation) RenderDict(pageIndRef types.IndirectRef) types.Dict

type InkPath

type InkPath []float64

A series of alternating x and y coordinates in PDF user space, specifying points along the path.

type LinkAnnotation

type LinkAnnotation struct {
	Annotation
	Dest        *Destination     // internal link
	URI         string           // external link
	Quad        types.QuadPoints // shall be ignored if any coordinate lies outside the region specified by Rect.
	Border      bool             // render border using borderColor.
	BorderWidth float64
	BorderStyle BorderStyle
}

LinkAnnotation represents a PDF link annotation.

func NewLinkAnnotation

func NewLinkAnnotation(
	rect types.Rectangle,
	quad types.QuadPoints,
	dest *Destination,
	uri string,
	id string,
	f AnnotationFlags,
	borderWidth float64,
	borderStyle BorderStyle,
	borderCol *color.SimpleColor,
	border bool) 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(xRefTable *XRefTable, pageIndRef types.IndirectRef) (types.Dict, error)

RenderDict renders ann into a page 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  *types.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 types.Rectangle,
	pageIndRef *types.IndirectRef,
	contents, id, title string,
	f AnnotationFlags,
	bgCol *color.SimpleColor,
	popupIndRef *types.IndirectRef,
	ca *float64,
	rc, subject string) MarkupAnnotation

NewMarkupAnnotation returns a new markup annotation.

type NUp

type NUp struct {
	PageDim         *types.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            *types.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          float64            // Cropbox for n-Up content.
	Border          bool               // Draw bounding box.
	BorderOnCropbox *BorderStyling     // Draw bounding box around crop box.
	BookletGuides   bool               // Draw folding and cutting lines.
	MultiFolio      bool               // Render booklet as sequence of folios.
	FolioSize       int                // Booklet multifolio folio size: default: 8
	BookletType     BookletType        // Is this a booklet or booklet cover layout
	BookletBinding  BookletBinding     // Does the booklet have short or long-edge binding
	InpUnit         types.DisplayUnit  // input display unit.
	BgColor         *color.SimpleColor // background color
}

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

func DefaultNUpConfig

func DefaultNUpConfig() *NUp

DefaultNUpConfig returns the default NUp configuration.

func (NUp) IsBooklet

func (nup NUp) IsBooklet() bool

func (NUp) IsTopFoldBinding

func (nup NUp) IsTopFoldBinding() bool

func (NUp) N

func (nup NUp) N() int

N returns the nUp value.

func (NUp) RectsForGrid

func (nup NUp) RectsForGrid() []*types.Rectangle

RectsForGrid calculates dest rectangles for given grid.

func (NUp) String

func (nup NUp) String() string

type NameMap

type NameMap map[string][]types.Dict

func (NameMap) Add

func (m NameMap) Add(k string, d types.Dict)

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          types.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 types.Object, m NameMap, nameRefDictKeys []string) error

Add adds an entry to a name tree.

func (*Node) AddTree

func (n *Node) AddTree(xRefTable *XRefTable, tree *Node, m NameMap, nameRefDictKeys []string) error

AddTree adds a name tree to a name tree.

func (*Node) AppendToNames

func (n *Node) AppendToNames(k string, v types.Object)

AppendToNames adds an entry to a leaf node (for internalizing name trees).

func (*Node) HandleLeaf

func (n *Node) HandleLeaf(xRefTable *XRefTable, k string, v types.Object, m NameMap, nameRefDictKeys []string) 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, *types.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) (types.Object, bool)

Value returns the value for given key

type NonFullScreenPageMode

type NonFullScreenPageMode PageMode
const (
	NFSPageModeUseNone NonFullScreenPageMode = iota
	NFSPageModeUseOutlines
	NFSPageModeUseThumb
	NFSPageModeUseOC
)

type OptimizationContext

type OptimizationContext struct {

	// Font section
	PageFonts         []types.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]types.Dict  // Registry of duplicate font dicts.
	DuplicateFontObjs types.IntSet        // The set of objects that represents the union of the object graphs of all duplicate font dicts.

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

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

	DuplicateInfoObjects types.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 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   *types.Rectangle
	CropBox    *types.Rectangle
	Fm         FontMap
	Im         ImageMap
	Annots     []FieldAnnotation
	AnnotTabs  map[int]FieldAnnotation
	LinkAnnots []LinkAnnotation
	Buf        *bytes.Buffer
	Fields     types.Array
}

Page represents rendered page content.

func NewPage

func NewPage(mediaBox, cropBox *types.Rectangle) Page

NewPage creates a page for given mediaBox and cropBox.

func NewPageWithBg

func NewPageWithBg(mediaBox *types.Rectangle, c color.SimpleColor) Page

NewPageWithBg creates a page for a mediaBox.

type PageBoundaries

type PageBoundaries struct {
	Media       *Box   `json:"mediaBox,omitempty"`
	Crop        *Box   `json:"cropBox,omitempty"`
	Trim        *Box   `json:"trimBox,omitempty"`
	Bleed       *Box   `json:"bleedBox,omitempty"`
	Art         *Box   `json:"artBox,omitempty"`
	Rot         int    `json:"rot"` // The effective page rotation.
	Orientation string `json:"orient"`
}

PageBoundaries represent the defined PDF page boundaries.

func ParseBoxList

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

ParseBoxList parses a list of box

func ParsePageBoundaries

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

ParsePageBoundaries parses a list of box definitions and assignments.

func (PageBoundaries) ArtBox

func (pb PageBoundaries) ArtBox() *types.Rectangle

ArtBox returns the effective artbox for pb.

func (PageBoundaries) BleedBox

func (pb PageBoundaries) BleedBox() *types.Rectangle

BleedBox returns the effective bleedbox for pb.

func (PageBoundaries) CropBox

func (pb PageBoundaries) CropBox() *types.Rectangle

CropBox returns the effective cropbox for pb.

func (PageBoundaries) MediaBox

func (pb PageBoundaries) MediaBox() *types.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() *types.Rectangle

TrimBox returns the effective trimbox for pb.

type PageBoundary

type PageBoundary int
const (
	MediaBox PageBoundary = iota
	CropBox
	TrimBox
	BleedBox
	ArtBox
)

func PageBoundaryFor

func PageBoundaryFor(s string) *PageBoundary

func (*PageBoundary) String

func (pb *PageBoundary) String() string

type PageLayout

type PageLayout int
const (
	PageLayoutSinglePage PageLayout = iota
	PageLayoutTwoColumnLeft
	PageLayoutTwoColumnRight
	PageLayoutTwoPageLeft
	PageLayoutTwoPageRight
)

func PageLayoutFor

func PageLayoutFor(s string) *PageLayout

func (*PageLayout) String

func (pl *PageLayout) String() string

type PageMode

type PageMode int
const (
	PageModeUseNone PageMode = iota
	PageModeUseOutlines
	PageModeUseThumbs
	PageModeFullScreen
	PageModeUseOC
	PageModeUseAttachments
)

func PageModeFor

func PageModeFor(s string) *PageMode

func (*PageMode) String

func (pm *PageMode) String() string

type PageResourceNames

type PageResourceNames map[string]types.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) types.StringSet

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

func (PageResourceNames) String

func (prn PageResourceNames) String() string

type PaperHandling

type PaperHandling int
const (
	Simplex PaperHandling = iota
	DuplexFlipShortEdge
	DuplexFlipLongEdge
)

func PaperHandlingFor

func PaperHandlingFor(s string) *PaperHandling

func (*PaperHandling) String

func (ph *PaperHandling) String() string

type PdfResources

type PdfResources struct {
	Content []byte
	ResDict *types.IndirectRef
	Bb      *types.Rectangle // visible region in user space
}

type PermissionFlags

type PermissionFlags int

See table 22 - User access permissions

const (
	UnusedFlag1              PermissionFlags = 1 << iota // Bit 1:  unused
	UnusedFlag2                                          // Bit 2:  unused
	PermissionPrintRev2                                  // Bit 3:  Print (security handlers rev.2), draft print (security handlers >= rev.3)
	PermissionModify                                     // Bit 4:  Modify contents by operations other than controlled by bits 6, 9, 11.
	PermissionExtract                                    // Bit 5:  Copy, extract text & graphics
	PermissionModAnnFillForm                             // Bit 6:  Add or modify annotations, fill form fields, in conjunction with bit 4 create/mod form fields.
	UnusedFlag7                                          // Bit 7:  unused
	UnusedFlag8                                          // Bit 8:  unused
	PermissionFillRev3                                   // Bit 9:  Fill form fields (security handlers >= rev.3)
	PermissionExtractRev3                                // Bit 10: Copy, extract text & graphics (security handlers >= rev.3) (unused since PDF 2.0)
	PermissionAssembleRev3                               // Bit 11: Assemble document (security handlers >= rev.3)
	PermissionPrintRev3                                  // Bit 12: Print (security handlers >= rev.3)
)

type PgAnnots

type PgAnnots map[AnnotationType]Annot

PgAnnots represents a map of page annotations by type.

type PopupAnnotation

type PopupAnnotation struct {
	Annotation
	ParentIndRef *types.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 types.Rectangle,
	pageIndRef *types.IndirectRef,
	contents, id string,
	f AnnotationFlags,
	bgCol *color.SimpleColor,
	parentIndRef *types.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 PrintScaling

type PrintScaling int
const (
	PrintScalingNone PrintScaling = iota
	PrintScalingAppDefault
)

func PrintScalingFor

func PrintScalingFor(s string) *PrintScaling

func (*PrintScaling) String

func (ps *PrintScaling) String() string

type ReadContext

type ReadContext struct {
	FileName            string        // Input PDF-File.
	FileSize            int64         // Input file size.
	RS                  io.ReadSeeker // Input read seeker.
	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       types.IntSet  // All object numbers of any object streams found which need to be decoded.
	UsingXRefStreams    bool          // File is using xref streams.
	XRefStreams         types.IntSet  // All object numbers of any xref streams found.
}

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 Resize

type Resize struct {
	Scale         float64            // scale factor x > 0, x > 1 enlarges, x < 1 shrinks down
	Unit          types.DisplayUnit  // display unit
	PageDim       *types.Dim         // page dimensions in display unit
	PageSize      string             // paper size eg. A2,A3,A4,Legal,Ledger,...
	EnforceOrient bool               // enforce orientation of PageDim
	UserDim       bool               // true if dimensions set by dim rather than formsize
	Border        bool               // true to render original crop box
	BgColor       *color.SimpleColor // background color
}

func (Resize) EnforceOrientation

func (r Resize) EnforceOrientation() bool

type Resource

type Resource struct {
	ID     string
	IndRef *types.IndirectRef
}

type SquareAnnotation

type SquareAnnotation struct {
	Annotation
	FillCol               *color.SimpleColor
	Margins               types.Array
	BorderWidth           float64
	BorderStyle           BorderStyle
	CloudyBorder          bool
	CloudyBorderIntensity int // 0,1,2
}

SquareAnnotation represents a square annotation.

func NewSquareAnnotation

func NewSquareAnnotation(
	rect types.Rectangle,
	contents string,
	id string,
	f AnnotationFlags,
	borderWidth float64,
	borderStyle BorderStyle,
	borderCol *color.SimpleColor,
	cloudyBorder bool,
	cloudyBorderIntensity int,
	fillCol *color.SimpleColor,
	MLeft, MTop, MRight, MBot float64) SquareAnnotation

NewSquareAnnotation returns a new square annotation.

func (SquareAnnotation) RenderDict

func (ann SquareAnnotation) RenderDict(xRefTable *XRefTable, pageIndRef types.IndirectRef) (types.Dict, error)

RenderDict renders ann into a page annotation dict.

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 types.Rectangle,
	contents, id, title string,
	f AnnotationFlags,
	bgCol *color.SimpleColor,
	ca *float64,
	rc, subj string,
	open bool,
	name string) TextAnnotation

NewTextAnnotation returns a new text annotation.

func (TextAnnotation) RenderDict

func (ann TextAnnotation) RenderDict(xRefTable *XRefTable, pageIndRef types.IndirectRef) (types.Dict, error)

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.
	Embed          bool                // Embed 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         types.HAlignment    // Horizontal text alignment.
	VAlign         types.VAlignment    // Vertical text alignment.
	RMode          draw.RenderMode     // Text render mode
	StrokeCol      color.SimpleColor   // Stroke color to be used for rendering text corresponding to RMode.
	FillCol        color.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  color.SimpleColor   // Bounding box fill color.
	ShowBorder     bool                // Render border using BorderCol, BorderWidth and BorderStyle.
	BorderWidth    float64             // Border width, visibility depends on ShowBorder.
	BorderStyle    types.LineJoinStyle // Border style, also visible if ShowBorder is false as long as ShowBackground is true.
	BorderCol      color.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.
	ShowPosition   bool                // Highlight position.
	HairCross      bool                // Draw haircross at X,Y
}

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

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
	V20
)

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 ViewerPrefJSON

type ViewerPrefJSON struct {
	HideToolbar           *bool    `json:"hideToolbar,omitempty"`
	HideMenubar           *bool    `json:"hideMenubar,omitempty"`
	HideWindowUI          *bool    `json:"hideWindowUI,omitempty"`
	FitWindow             *bool    `json:"fitWindow,omitempty"`
	CenterWindow          *bool    `json:"centerWindow,omitempty"`
	DisplayDocTitle       *bool    `json:"displayDocTitle,omitempty"`
	NonFullScreenPageMode string   `json:"nonFullScreenPageMode,omitempty"`
	Direction             string   `json:"direction,omitempty"`
	ViewArea              string   `json:"viewArea,omitempty"`
	ViewClip              string   `json:"viewClip,omitempty"`
	PrintArea             string   `json:"printArea,omitempty"`
	PrintClip             string   `json:"printClip,omitempty"`
	PrintScaling          string   `json:"printScaling,omitempty"`
	Duplex                string   `json:"duplex,omitempty"`
	PickTrayByPDFSize     *bool    `json:"pickTrayByPDFSize,omitempty"`
	PrintPageRange        []int    `json:"printPageRange,omitempty"`
	NumCopies             *int     `json:"numCopies,omitempty"`
	Enforce               []string `json:"enforce,omitempty"`
}

type ViewerPreferences

type ViewerPreferences struct {
	HideToolbar           *bool
	HideMenubar           *bool
	HideWindowUI          *bool
	FitWindow             *bool
	CenterWindow          *bool
	DisplayDocTitle       *bool // since 1.4
	NonFullScreenPageMode *NonFullScreenPageMode
	Direction             *Direction     // since 1.3
	ViewArea              *PageBoundary  // since 1.4 to 1.7
	ViewClip              *PageBoundary  // since 1.4 to 1.7
	PrintArea             *PageBoundary  // since 1.4 to 1.7
	PrintClip             *PageBoundary  // since 1.4 to 1.7
	PrintScaling          *PrintScaling  // since 1.6
	Duplex                *PaperHandling // since 1.7
	PickTrayByPDFSize     *bool          // since 1.7
	PrintPageRange        types.Array    // since 1.7
	NumCopies             *types.Integer // since 1.7
	Enforce               types.Array    // since 2.0
}

ViewerPreferences see 12.2 Table 147

func DefaultViewerPreferences

func DefaultViewerPreferences(version Version) *ViewerPreferences

func ViewerPreferencesWithDefaults

func ViewerPreferencesWithDefaults(vp *ViewerPreferences, version Version) (*ViewerPreferences, error)

func (ViewerPreferences) List

func (vp ViewerPreferences) List() []string

List generates output for the viewer pref command.

func (*ViewerPreferences) MarshalJSON

func (vp *ViewerPreferences) MarshalJSON() ([]byte, error)

func (*ViewerPreferences) Populate

func (vp *ViewerPreferences) Populate(vp1 *ViewerPreferences)

func (*ViewerPreferences) SetCenterWindow

func (vp *ViewerPreferences) SetCenterWindow(val bool)

func (*ViewerPreferences) SetDisplayDocTitle

func (vp *ViewerPreferences) SetDisplayDocTitle(val bool)

func (*ViewerPreferences) SetFitWindow

func (vp *ViewerPreferences) SetFitWindow(val bool)

func (*ViewerPreferences) SetHideMenuBar

func (vp *ViewerPreferences) SetHideMenuBar(val bool)

func (*ViewerPreferences) SetHideToolBar

func (vp *ViewerPreferences) SetHideToolBar(val bool)

func (*ViewerPreferences) SetHideWindowUI

func (vp *ViewerPreferences) SetHideWindowUI(val bool)

func (*ViewerPreferences) SetNumCopies

func (vp *ViewerPreferences) SetNumCopies(i int)

func (*ViewerPreferences) SetPickTrayByPDFSize

func (vp *ViewerPreferences) SetPickTrayByPDFSize(val bool)

func (ViewerPreferences) String

func (vp ViewerPreferences) String() string

String generates output for the info command.

func (*ViewerPreferences) UnmarshalJSON

func (vp *ViewerPreferences) UnmarshalJSON(data []byte) error

func (*ViewerPreferences) Validate

func (vp *ViewerPreferences) Validate(version Version) error

type Watermark

type Watermark struct {
	OnTop                     bool                // if true STAMP else WATERMARK.
	Mode                      int                 // WMText, WMImage or WMPDF
	FileName                  string              // image or PDF file name
	Image                     io.Reader           // image reader
	PDF                       io.ReadSeeker       // PDF read seeker
	TextString                string              // raw display text.
	TextLines                 []string            // display multiple lines of text.
	URL                       string              // overlay link annotation for stamps.
	InpUnit                   types.DisplayUnit   // input display unit.
	Pos                       types.Anchor        // position anchor, one of tl,tc,tr,l,c,r,bl,bc,br.
	Dx, Dy                    float64             // anchor offset.
	HAlign                    *types.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
	ScriptName                string              // ISO 15924: Hans, Hant, Hira, Kana, Jpan, Hang, Kore: if set, font will not be embedded.
	RTL                       bool                // if true, render text from right to left
	Color                     color.SimpleColor   // text fill color(=non stroking color) for backwards compatibility.
	FillColor                 color.SimpleColor   // text fill color(=non stroking color).
	StrokeColor               color.SimpleColor   // text stroking color
	BgColor                   *color.SimpleColor  // text bounding box background color
	MLeft, MRight             float64             // left and right bounding box margin
	MTop, MBot                float64             // top and bottom bounding box margin
	BorderWidth               float64             // Border width, visible if BgColor is set.
	BorderStyle               types.LineJoinStyle // Border style (bounding box corner style), visible if BgColor is set.
	BorderColor               *color.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                draw.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.
	Ocg, ExtGState, Font, Img *types.IndirectRef  // resources
	Width, Height             int                 // image or page dimensions

	PdfRes                  map[int]PdfResources // content & corresponding resources
	PdfPageNrSrc            int                  // page number of the source PDF file serving as stamp provider, 0 for multi stamping
	PdfMultiStartPageNrSrc  int                  // start page number of the source PDF file serving as stamp provider.
	PdfMultiStartPageNrDest int                  // start page number of the destination PDF file.

	// page specific
	Bb      *types.Rectangle   // bounding box of the form representing this watermark.
	BbTrans types.QuadLiteral  // Transformed bounding box.
	Vp      *types.Rectangle   // view port, page dimensions.
	PageRot int                // page rotation in effect.
	Form    *types.IndirectRef // form dependent on given page dimensions.

	// house keeping
	Objs   types.IntSet // objects for which wm has been applied already.
	FCache formCache    // form cache.
	// 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 (*Watermark) CalcBoundingBox

func (wm *Watermark) CalcBoundingBox(pageNr int)

CalcBoundingBox returns the bounding box for wm and pageNr.

func (*Watermark) CalcTransformMatrix

func (wm *Watermark) CalcTransformMatrix() matrix.Matrix

CalcTransformMatrix return the transform matrix for a watermark.

func (Watermark) IsImage

func (wm Watermark) IsImage() bool

IsImage returns true if the watermark content is an image.

func (Watermark) IsPDF

func (wm Watermark) IsPDF() bool

IsPDF returns true if the watermark content is PDF.

func (Watermark) IsText

func (wm Watermark) IsText() bool

IsText returns true if the watermark content is text.

func (Watermark) MultiStamp

func (wm Watermark) MultiStamp() bool

MultiStamp returns true if wm is a multi stamp.

func (Watermark) OnTopString

func (wm Watermark) OnTopString() string

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

func (*Watermark) PdfResIndex

func (wm *Watermark) PdfResIndex(pageNr int) int

func (*Watermark) Recycle

func (wm *Watermark) Recycle()

Recycle resets all caches.

func (Watermark) String

func (wm Watermark) String() string

func (Watermark) Typ

func (wm Watermark) Typ() string

Typ returns the nature of wm.

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       types.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 XRefTable

type XRefTable struct {
	Table               map[int]*XRefTableEntry
	Size                *int               // Object count from PDF trailer dict.
	PageCount           int                // Number of pages.
	Root                *types.IndirectRef // Pointer to catalog (reference to root object).
	RootDict            types.Dict         // Catalog
	Names               map[string]*Node   // Cache for name trees as found in catalog.
	NameRefs            map[string]NameMap // Name refs for merging only
	Encrypt             *types.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           types.Array        // from trailer
	Info         *types.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

	PageLayout *PageLayout
	PageMode   *PageMode
	ViewerPref *ViewerPreferences

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

	// Page annotation cache
	PageAnnots map[int]PgAnnots

	// Thumbnail images
	PageThumbs map[int]types.IndirectRef

	// Offspec section
	AdditionalStreams *types.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
	Conf           *Configuration            // current command being executed
	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
	Form           types.Dict
	Outlines       types.Dict
	SignatureExist bool
	AppendOnly     bool

	// Fonts
	UsedGIDs  map[string]map[uint16]bool
	FillFonts map[string]types.IndirectRef
}

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

func (*XRefTable) AppendContent

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

AppendContent appends bb to pageDict's content stream.

func (*XRefTable) AppendPages

func (xRefTable *XRefTable) AppendPages(rootPageIndRef *types.IndirectRef, fromPageNr int, ctx *Context) (int, error)

func (*XRefTable) BindNameTrees

func (xRefTable *XRefTable) BindNameTrees() error

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

func (*XRefTable) BindPrinterPreferences

func (xRefTable *XRefTable) BindPrinterPreferences(vp *ViewerPreferences, d types.Dict)

func (*XRefTable) BindViewerPreferences

func (xRefTable *XRefTable) BindViewerPreferences()

func (*XRefTable) Catalog

func (xRefTable *XRefTable) Catalog() (types.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) DeleteDictEntry

func (xRefTable *XRefTable) DeleteDictEntry(d types.Dict, key string) error

func (*XRefTable) DeleteObject

func (xRefTable *XRefTable) DeleteObject(o types.Object) error

DeleteObject makes a deep remove of o.

func (*XRefTable) DeleteObjectGraph

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

DeleteObjectGraph deletes all objects reachable by indRef.

func (*XRefTable) Dereference

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

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

func (*XRefTable) DereferenceArray

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

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

func (*XRefTable) DereferenceBoolean

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

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

func (*XRefTable) DereferenceCSVSafeText

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

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

func (*XRefTable) DereferenceDestArray

func (xRefTable *XRefTable) DereferenceDestArray(key string) (types.Array, error)

DereferenceDestArray resolves the destination for key.

func (*XRefTable) DereferenceDict

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

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

func (*XRefTable) DereferenceDictEntry

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

DereferenceDictEntry returns a dereferenced dict entry.

func (*XRefTable) DereferenceFontDict

func (xRefTable *XRefTable) DereferenceFontDict(indRef types.IndirectRef) (types.Dict, error)

DereferenceFontDict returns the font dict referenced by indRef.

func (*XRefTable) DereferenceForWrite

func (xRefTable *XRefTable) DereferenceForWrite(o types.Object) (types.Object, error)

func (*XRefTable) DereferenceInteger

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

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

func (*XRefTable) DereferenceName

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

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

func (*XRefTable) DereferenceNumber

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

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

func (*XRefTable) DereferencePageNodeDict

func (xRefTable *XRefTable) DereferencePageNodeDict(indRef types.IndirectRef) (types.Dict, error)

DereferencePageNodeDict returns the page node dict referenced by indRef.

func (*XRefTable) DereferenceStreamDict

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

DereferenceStreamDict resolves a stream dictionary object.

func (*XRefTable) DereferenceStringEntryBytes

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

DereferenceStringEntryBytes returns the bytes of a string entry of d.

func (*XRefTable) DereferenceStringLiteral

func (xRefTable *XRefTable) DereferenceStringLiteral(o types.Object, sinceVersion Version, validate func(string) bool) (s types.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 types.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 types.Object) (string, error)

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

func (*XRefTable) DereferenceXObjectDict

func (xRefTable *XRefTable) DereferenceXObjectDict(indRef types.IndirectRef) (*types.StreamDict, error)

DereferenceXObjectDict resolves an XObject.

func (*XRefTable) DestName

func (xRefTable *XRefTable) DestName(obj types.Object) (string, error)

func (*XRefTable) DumpObject

func (xRefTable *XRefTable) DumpObject(objNr, mode int)

func (*XRefTable) EmptyPage

func (xRefTable *XRefTable) EmptyPage(parentIndRef *types.IndirectRef, mediaBox *types.Rectangle) (*types.IndirectRef, error)

func (*XRefTable) EncryptDict

func (xRefTable *XRefTable) EncryptDict() (types.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.

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) (types.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(indRef *types.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) FreeObject

func (xRefTable *XRefTable) FreeObject(objNr int) error

FreeObject marks an objects xref table entry as free and inserts it into the free list right after the head.

func (*XRefTable) HasUsedGIDs

func (xRefTable *XRefTable) HasUsedGIDs(fontName string) bool

func (*XRefTable) IDFirstElement

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

IDFirstElement returns the first element of ID.

func (*XRefTable) IncrementRefCount

func (xRefTable *XRefTable) IncrementRefCount(indRef *types.IndirectRef)

IncrementRefCount increments the number of references for the object pointed to by indRef.

func (*XRefTable) IndRefForNewObject

func (xRefTable *XRefTable) IndRefForNewObject(obj types.Object) (*types.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 types.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 types.Object) (objNr int, err error)

InsertObject inserts an object into the xRefTable.

func (*XRefTable) InsertPages

func (xRefTable *XRefTable) InsertPages(parent *types.IndirectRef, p *int, ctx *Context) (int, error)

Zip in ctx's pages: for each page weave in the corresponding ctx page as long as there is one.

func (*XRefTable) IsLinearizationObject

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

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

func (*XRefTable) IsMerging

func (xRefTable *XRefTable) IsMerging() bool

func (*XRefTable) IsValid

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

IsValid returns true if the object referenced by ir is valid.

func (*XRefTable) IsValidObj

func (xRefTable *XRefTable) IsValidObj(objNr, genNr int) (bool, error)

IsValidObj returns true if the object with objNr and genNr is valid.

func (*XRefTable) LinearizationObjsString

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

LinearizationObjsString returns a formatted string and the number of objs.

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) NameRef

func (xRefTable *XRefTable) NameRef(nameType string) NameMap

func (*XRefTable) NamesDict

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

NamesDict returns the dict that contains all name trees.

func (*XRefTable) NewEmbeddedFileStreamDict

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

NewEmbeddedFileStreamDict returns an embeddedFileStreamDict containing the file "filename".

func (*XRefTable) NewEmbeddedStreamDict

func (xRefTable *XRefTable) NewEmbeddedStreamDict(r io.Reader, modDate time.Time) (*types.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 types.IndirectRef) (types.Dict, error)

NewFileSpecDict creates and returns a new fileSpec dictionary.

func (*XRefTable) NewFileSpecDictForAttachment

func (xRefTable *XRefTable) NewFileSpecDictForAttachment(a Attachment) (types.Dict, error)

NewFileSpectDictForAttachment returns a fileSpecDict for a.

func (*XRefTable) NewSoundStreamDict

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

NewSoundStreamDict returns a new sound stream dict.

func (*XRefTable) NewStreamDictForBuf

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

NewStreamDictForBuf creates a streamDict for buf.

func (*XRefTable) NewStreamDictForFile

func (xRefTable *XRefTable) NewStreamDictForFile(filename string) (*types.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) PageBoundaries

func (xRefTable *XRefTable) PageBoundaries(selectedPages types.IntSet) ([]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 types.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) (types.Dict, *types.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) (*types.IndirectRef, error)

PageDictIndRef returns the pageDict IndRef for a logical page number.

func (*XRefTable) PageDims

func (xRefTable *XRefTable) PageDims() ([]types.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() (*types.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) RectForArray

func (xRefTable *XRefTable) RectForArray(a types.Array) (*types.Rectangle, error)

RectForArray returns a new rectangle for given Array.

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) RemoveSignature

func (xRefTable *XRefTable) RemoveSignature()

func (*XRefTable) SetValid

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

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

func (*XRefTable) StreamDictIndRef

func (xRefTable *XRefTable) StreamDictIndRef(bb []byte) (*types.IndirectRef, error)

StreamDictIndRef creates a new stream dict for bb.

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          types.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 types.Object) *XRefTableEntry

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

type Zoom

type Zoom struct {
	Factor  float64            // zoom factor x > 0, x > 1 zooms in, x < 1 zooms out
	HMargin float64            // horizontal margin implying some (usually negative) scale factor
	VMargin float64            // vertical margin implying some (usually negative) scale factor
	Unit    types.DisplayUnit  // display unit
	Border  bool               // border around page content when zooming out
	BgColor *color.SimpleColor // background color when zooming out
}

func (*Zoom) EnsureFactorAndMargins

func (z *Zoom) EnsureFactorAndMargins(w, h float64) error

Jump to

Keyboard shortcuts

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