pdfcpu: github.com/pdfcpu/pdfcpu/pkg/pdfcpu Index | Files | Directories

package pdfcpu

import "github.com/pdfcpu/pdfcpu/pkg/pdfcpu"

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

The commands are:

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

Index

Package Files

array.go attach.go collect.go colorSpace.go configuration.go context.go create.go createAnnotations.go createRenditions.go createTestPDF.go crypto.go dict.go doc.go equal.go extract.go filter.go iccProfile.go imageRead.go imageWrite.go importImage.go info.go merge.go nameTree.go nup.go optimize.go pages.go paperSize.go parse.go read.go resources.go rotate.go slice.go stamp.go stats.go streamdict.go string.go types.go utf16.go version.go write.go writeObjects.go writePages.go writeStats.go xreftable.go

Constants

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:

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

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

    // ValidationNone bypasses validation.
    ValidationNone
)
const (

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

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

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

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

These are the defined anchors for relative positioning.

const (
    RightDown orientation = iota
    DownRight
    LeftDown
    DownLeft
)

These are the defined anchors for relative positioning.

const (
    WMText = iota
    WMImage
    WMPDF
)

Watermark mode

const (
    NoDiagonal = iota
    DiagonalLLToUR
    DiagonalULToLR
)

Rotation along one of 2 diagonals

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.

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.

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

Supported line delimiters

const FreeHeadGeneration = 65535

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

const (

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

Variables

var (
    ErrUnsupportedColorSpace   = errors.New("unsupported color space")
    ErrUnsupported16BPC        = errors.New("unsupported 16 bits per component")
    ErrUnsupportedTIFFCreation = errors.New("unsupported tiff file creation")
)

Errors to be identified.

var (
    Black     = SimpleColor{}
    White     = SimpleColor{R: 1, G: 1, B: 1}
    Gray      = SimpleColor{.5, .5, .5}
    LightGray = SimpleColor{.9, .9, .9}
)

Some popular colors.

var PaperSize = map[string]*Dim{ /* 150 elements not displayed */

}

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

var VersionStr = "v0.3.4 dev"

VersionStr is the current pdfcpu version.

func AddPages Uses

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

AddPages adds pages and corresponding resources from otherXRefTable to xRefTable.

func AddWatermarks Uses

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

AddWatermarks adds watermarks to all pages selected.

func AppendPageTree Uses

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

AppendPageTree appends a pagetree d1 to page tree d2.

func AppendStatsFile Uses

func AppendStatsFile(ctx *Context) error

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

func AttachAdd Uses

func AttachAdd(xRefTable *XRefTable, files StringSet, coll bool) (bool, error)

AttachAdd embeds specified files. Existing attachments are replaced. Ensures collection for portfolios. Returns true if at least one attachment was added.

func AttachExtract Uses

func AttachExtract(ctx *Context, files StringSet) error

AttachExtract exports specified embedded files. If no files specified extract all embedded files.

func AttachList Uses

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

AttachList returns a list of embedded files.

func AttachRemove Uses

func AttachRemove(xRefTable *XRefTable, files StringSet) (bool, error)

AttachRemove deletes specified embedded files. Returns true if at least one attachment could be removed.

func CreateTestPageContent Uses

func CreateTestPageContent(p Page)

CreateTestPageContent draws a test grid.

func DateString Uses

func DateString(t time.Time) string

DateString returns a string representation of t.

func DecodeUTF16String Uses

func DecodeUTF16String(s string) (string, error)

DecodeUTF16String decodes a UTF16BE string from a hex string.

func DetectWatermarks Uses

func DetectWatermarks(ctx *Context) error

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

func DrawAndFillRect Uses

func DrawAndFillRect(b *bytes.Buffer, r *Rectangle)

DrawAndFillRect strokes and fills a rectangular path for r.

func DrawGrid Uses

func DrawGrid(bb *bytes.Buffer, x, y int, r *Rectangle, strokeCol SimpleColor, fillCol *SimpleColor)

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

func DrawHairCross Uses

func DrawHairCross(buf *bytes.Buffer, x, y float64, r *Rectangle)

DrawHairCross draw a haircross with origin x/y.

func DrawLine Uses

func DrawLine(b *bytes.Buffer, xp, yp, xq, yq float64)

DrawLine draws the path from P to Q.

func DrawRect Uses

func DrawRect(b *bytes.Buffer, r *Rectangle)

DrawRect strokes a rectangular path for r.

func Escape Uses

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

Escape applies all defined escape sequences to s.

func ExtractStreamData Uses

func ExtractStreamData(ctx *Context, objNr int) (data []byte, err error)

ExtractStreamData extracts the content of a stream dict for a specific objNr.

func FillRect Uses

func FillRect(bb *bytes.Buffer, rect *Rectangle, c SimpleColor)

FillRect draws and fills a rectangle using r, g, b.

func HexLiteralToString Uses

func HexLiteralToString(hexString string) (string, error)

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

func IntMemberOf Uses

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

IntMemberOf returns true if list contains i.

func IsStringUTF16BE Uses

func IsStringUTF16BE(s string) bool

IsStringUTF16BE checks a string for Big Endian byte order BOM.

func IsUTF16BE Uses

func IsUTF16BE(b []byte) bool

IsUTF16BE checks for Big Endian byte order mark.

func KeywordsAdd Uses

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

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

func KeywordsList Uses

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

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

func KeywordsRemove Uses

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

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

func MemberOf Uses

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

MemberOf returns true if list contains s.

func MergeXRefTables Uses

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

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

func NUpFromPDF Uses

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

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

func OptimizeXRefTable Uses

func OptimizeXRefTable(ctx *Context) error

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

func ParseNUpDetails Uses

func ParseNUpDetails(s string, nup *NUp) error

ParseNUpDetails parses a NUp command string into an internal structure.

func ParseNUpGridDefinition Uses

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

ParseNUpGridDefinition parses NUp grid dimensions into an internal structure.

func ParseNUpValue Uses

func ParseNUpValue(n int, nUp *NUp) error

ParseNUpValue parses the NUp value into an internal structure.

func Permissions Uses

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

Permissions returns a list of set permissions.

func PropertiesAdd Uses

func PropertiesAdd(xRefTable *XRefTable, properties map[string]string) error

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

func PropertiesList Uses

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

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

func PropertiesRemove Uses

func PropertiesRemove(xRefTable *XRefTable, properties []string) (bool, error)

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

func RemoveWatermarks Uses

func RemoveWatermarks(ctx *Context, selectedPages IntSet) error

RemoveWatermarks removes watermarks for all pages selected.

func RotatePages Uses

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

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

func SetFillColor Uses

func SetFillColor(bb *bytes.Buffer, c SimpleColor)

SetFillColor sets the fill color.

func SetLineJoinStyle Uses

func SetLineJoinStyle(b *bytes.Buffer, s LineJoinStyle)

SetLineJoinStyle sets the line join style for stroking operations.

func SetLineWidth Uses

func SetLineWidth(b *bytes.Buffer, w float64)

SetLineWidth sets line width for stroking operations.

func SetStrokeColor Uses

func SetStrokeColor(bb *bytes.Buffer, c SimpleColor)

SetStrokeColor sets the stroke color.

func StringLiteralToString Uses

func StringLiteralToString(s string) (string, error)

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

func Text Uses

func Text(o Object) (string, error)

Text returns a string based representation for String and Hexliterals.

func TimingStats Uses

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

TimingStats prints processing time stats for an operation.

func Unescape Uses

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

Unescape resolves all escape sequences of s.

func ValidationTimingStats Uses

func ValidationTimingStats(dur1, dur2, dur float64)

ValidationTimingStats prints processing time stats for validation.

func Write Uses

func Write(ctx *Context) error

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

func WriteImage Uses

func WriteImage(xRefTable *XRefTable, filename string, sd *StreamDict, objNr int) (fileName string, err error)

WriteImage writes a PDF image object to disk.

type Array Uses

type Array []Object

Array represents a PDF array object.

func NewIntegerArray Uses

func NewIntegerArray(fVars ...int) Array

NewIntegerArray returns a PDFArray with Integer entries.

func NewNameArray Uses

func NewNameArray(sVars ...string) Array

NewNameArray returns a PDFArray with Name entries.

func NewNumberArray Uses

func NewNumberArray(fVars ...float64) Array

NewNumberArray returns a PDFArray with Float entries.

func NewStringArray Uses

func NewStringArray(sVars ...string) Array

NewStringArray returns a PDFArray with StringLiteral entries.

func (Array) Clone Uses

func (a Array) Clone() Object

Clone returns a clone of a.

func (Array) PDFString Uses

func (a Array) PDFString() string

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

func (Array) String Uses

func (a Array) String() string

type Boolean Uses

type Boolean bool

Boolean represents a PDF boolean object.

func (Boolean) Clone Uses

func (boolean Boolean) Clone() Object

Clone returns a clone of boolean.

func (Boolean) PDFString Uses

func (boolean Boolean) PDFString() string

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

func (Boolean) String Uses

func (boolean Boolean) String() string

func (Boolean) Value Uses

func (boolean Boolean) Value() bool

Value returns a bool value for this PDF object.

type ByteSize Uses

type ByteSize float64

ByteSize represents the various terms for storage space.

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

Storage space terms.

func (ByteSize) String Uses

func (b ByteSize) String() string

type CommandMode Uses

type CommandMode int

CommandMode specifies the operation being executed.

const (
    VALIDATE CommandMode = iota
    OPTIMIZE
    SPLIT
    MERGECREATE
    MERGEAPPEND
    EXTRACTIMAGES
    EXTRACTFONTS
    EXTRACTPAGES
    EXTRACTCONTENT
    EXTRACTMETADATA
    TRIM
    ADDATTACHMENTS
    ADDATTACHMENTSPORTFOLIO
    REMOVEATTACHMENTS
    EXTRACTATTACHMENTS
    LISTATTACHMENTS
    SETPERMISSIONS
    LISTPERMISSIONS
    ENCRYPT
    DECRYPT
    CHANGEUPW
    CHANGEOPW
    ADDWATERMARKS
    REMOVEWATERMARKS
    IMPORTIMAGES
    INSERTPAGESBEFORE
    INSERTPAGESAFTER
    REMOVEPAGES
    ROTATE
    NUP
    INFO
    INSTALLFONTS
    LISTFONTS
    LISTKEYWORDS
    ADDKEYWORDS
    REMOVEKEYWORDS
    LISTPROPERTIES
    ADDPROPERTIES
    REMOVEPROPERTIES
    COLLECT
)

The available commands.

type Configuration Uses

type Configuration struct {

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

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

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

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

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

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

    // Supplied user password
    UserPW    string
    UserPWNew *string

    // Supplied owner password
    OwnerPW    string
    OwnerPWNew *string

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

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

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

    // Command being executed.
    Cmd CommandMode

    // Chosen units for outputting paper sizes.
    Units DisplayUnit
}

Configuration of a Context.

func NewAESConfiguration Uses

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

NewAESConfiguration returns a default configuration for AES encryption.

func NewDefaultConfiguration Uses

func NewDefaultConfiguration() *Configuration

NewDefaultConfiguration returns the default pdfcpu configuration.

func NewRC4Configuration Uses

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

NewRC4Configuration returns a default configuration for RC4 encryption.

func (*Configuration) ApplyReducedFeatureSet Uses

func (c *Configuration) ApplyReducedFeatureSet() bool

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

func (*Configuration) ValidationModeString Uses

func (c *Configuration) ValidationModeString() string

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

type Context Uses

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

Context represents an environment for processing PDF files.

func CollectPages Uses

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

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

func CreateContext Uses

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

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

func CreateContextWithXRefTable Uses

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

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

func NUpFromImage Uses

func NUpFromImage(conf *Configuration, imageFileNames []string, nup *NUp) (*Context, error)

NUpFromImage creates a single page n-up PDF for one image or a sequence of n-up pages for more than one image.

func NewContext Uses

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

NewContext initializes a new Context.

func Read Uses

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

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

func ReadFile Uses

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

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

func (*Context) InfoDigest Uses

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

InfoDigest returns info about ctx.

func (*Context) ResetWriteContext Uses

func (ctx *Context) ResetWriteContext()

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

func (*Context) String Uses

func (ctx *Context) String() string

type Dict Uses

type Dict map[string]Object

Dict represents a PDF dict object.

func NewDict Uses

func NewDict() Dict

NewDict returns a new PDFDict object.

func (Dict) ArrayEntry Uses

func (d Dict) ArrayEntry(key string) Array

ArrayEntry expects and returns a Array entry for given key.

func (Dict) BooleanEntry Uses

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

BooleanEntry expects and returns a BooleanEntry for given key.

func (Dict) Clone Uses

func (d Dict) Clone() Object

Clone returns a clone of d.

func (Dict) Delete Uses

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

Delete deletes the Object for given key.

func (Dict) DictEntry Uses

func (d Dict) DictEntry(key string) Dict

DictEntry expects and returns a PDFDict entry for given key.

func (Dict) Entry Uses

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

Entry returns the value for given key.

func (Dict) Find Uses

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

Find returns the Object for given key and PDFDict.

func (Dict) First Uses

func (d Dict) First() *int

First returns a *int for key "First".

func (Dict) HexLiteralEntry Uses

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

HexLiteralEntry returns a HexLiteral object for given key.

func (*Dict) Increment Uses

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

Increment increments the integer value for given key.

func (*Dict) IncrementBy Uses

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

IncrementBy increments the integer value for given key by i.

func (Dict) Index Uses

func (d Dict) Index() Array

Index returns a *Array for key "Index".

func (Dict) IndirectRefEntry Uses

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

IndirectRefEntry returns an indirectRefEntry for given key for this dictionary.

func (Dict) Insert Uses

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

Insert adds a new entry to this PDFDict.

func (Dict) InsertFloat Uses

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

InsertFloat adds a new float entry to this PDFDict.

func (Dict) InsertInt Uses

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

InsertInt adds a new int entry to this PDFDict.

func (Dict) InsertName Uses

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

InsertName adds a new name entry to this PDFDict.

func (Dict) InsertString Uses

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

InsertString adds a new string entry to this PDFDict.

func (Dict) Int64Entry Uses

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

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

func (Dict) IntEntry Uses

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

IntEntry expects and returns a Integer entry for given key.

func (Dict) IsLinearizationParmDict Uses

func (d Dict) IsLinearizationParmDict() bool

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

func (Dict) IsObjStm Uses

func (d Dict) IsObjStm() bool

IsObjStm returns true if given PDFDict is an object stream.

func (Dict) Len Uses

func (d Dict) Len() int

Len returns the length of this PDFDict.

func (Dict) Length Uses

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

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

func (Dict) N Uses

func (d Dict) N() *int

N returns a *int for key "N".

func (Dict) NameEntry Uses

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

NameEntry expects and returns a Name entry for given key.

func (Dict) PDFString Uses

func (d Dict) PDFString() string

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

func (Dict) Prev Uses

func (d Dict) Prev() *int64

Prev returns the previous offset.

func (Dict) Size Uses

func (d Dict) Size() *int

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

func (Dict) StreamDictEntry Uses

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

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

func (Dict) String Uses

func (d Dict) String() string

func (Dict) StringEntry Uses

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

StringEntry expects and returns a StringLiteral entry for given key. Unused.

func (Dict) StringEntryBytes Uses

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

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

func (Dict) StringLiteralEntry Uses

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

StringLiteralEntry returns a StringLiteral object for given key.

func (Dict) Subtype Uses

func (d Dict) Subtype() *string

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

func (Dict) Type Uses

func (d Dict) Type() *string

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

func (Dict) Update Uses

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

Update modifies an existing entry of this PDFDict.

func (Dict) W Uses

func (d Dict) W() Array

W returns a *Array for key "W".

type Dim Uses

type Dim struct {
    Width, Height float64
}

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

func (Dim) AspectRatio Uses

func (d Dim) AspectRatio() float64

AspectRatio returns the relation between width and height.

func (Dim) Landscape Uses

func (d Dim) Landscape() bool

Landscape returns true if d is in landscape mode.

func (Dim) Portrait Uses

func (d Dim) Portrait() bool

Portrait returns true if d is in portrait mode.

func (Dim) String Uses

func (d Dim) String() string

func (Dim) ToCentimetres Uses

func (d Dim) ToCentimetres() Dim

ToCentimetres converts d to centimetres.

func (Dim) ToInches Uses

func (d Dim) ToInches() Dim

ToInches converts d to inches.

func (Dim) ToMillimetres Uses

func (d Dim) ToMillimetres() Dim

ToMillimetres converts d to centimetres.

type DisplayUnit Uses

type DisplayUnit int

DisplayUnit is the metric unit used to output paper sizes.

const (
    POINTS DisplayUnit = iota
    INCHES
    CENTIMETRES
    MILLIMETRES
)

The available display units.

type Enc Uses

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

Enc wraps around all defined encryption attributes.

type Float Uses

type Float float64

Float represents a PDF float object.

func (Float) Clone Uses

func (f Float) Clone() Object

Clone returns a clone of f.

func (Float) PDFString Uses

func (f Float) PDFString() string

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

func (Float) String Uses

func (f Float) String() string

func (Float) Value Uses

func (f Float) Value() float64

Value returns a float64 value for this PDF object.

type FontMap Uses

type FontMap map[string]string

FontMap maps font resource ids to font names.

func (FontMap) EnsureKey Uses

func (fm FontMap) EnsureKey(fontName string) string

EnsureKey registers fontName with corresponding font resource id.

type FontObject Uses

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

FontObject represents a font used in a PDF file.

func ExtractFontData Uses

func ExtractFontData(ctx *Context, objNr int) (*FontObject, error)

ExtractFontData extracts font data (the "fontfile") for objNr. Supported fontTypes: TrueType

func (*FontObject) AddResourceName Uses

func (fo *FontObject) AddResourceName(resourceName string)

AddResourceName adds a resourceName referring to this font.

func (FontObject) Embedded Uses

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

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

func (FontObject) Encoding Uses

func (fo FontObject) Encoding() string

Encoding returns the Encoding of this font.

func (FontObject) ResourceNamesString Uses

func (fo FontObject) ResourceNamesString() string

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

func (FontObject) String Uses

func (fo FontObject) String() string

func (FontObject) SubType Uses

func (fo FontObject) SubType() string

SubType returns the SubType of this font.

type HAlignment Uses

type HAlignment int

HAlignment represents the horizontal alignment of text.

const (
    AlignLeft HAlignment = iota
    AlignCenter
    AlignRight
    AlignJustify
)

These are the options for horizontal aligned text.

type HexLiteral Uses

type HexLiteral string

HexLiteral represents a PDF hex literal object.

func NewHexLiteral Uses

func NewHexLiteral(b []byte) HexLiteral

NewHexLiteral creates a new HexLiteral for b..

func (HexLiteral) Bytes Uses

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

Bytes returns the byte representation.

func (HexLiteral) Clone Uses

func (hexliteral HexLiteral) Clone() Object

Clone returns a clone of hexliteral.

func (HexLiteral) PDFString Uses

func (hexliteral HexLiteral) PDFString() string

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

func (HexLiteral) String Uses

func (hexliteral HexLiteral) String() string

func (HexLiteral) Value Uses

func (hexliteral HexLiteral) Value() string

Value returns a string value for this PDF object.

type ImageObject Uses

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

ImageObject represents an image used in a PDF file.

func ExtractImageData Uses

func ExtractImageData(ctx *Context, objNr int) (*ImageObject, error)

ExtractImageData extracts image data for objNr. Supported imgTypes: FlateDecode, DCTDecode, JPXDecode TODO: Implementation and usage of these filters: DCTDecode and JPXDecode. TODO: Should an error be returned instead of nil, nil when filters are not supported?

func (*ImageObject) AddResourceName Uses

func (io *ImageObject) AddResourceName(resourceName string)

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

func (ImageObject) ResourceNamesString Uses

func (io ImageObject) ResourceNamesString() string

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

type Import Uses

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

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

func DefaultImportConfig Uses

func DefaultImportConfig() *Import

DefaultImportConfig returns the default configuration.

func ParseImportDetails Uses

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

ParseImportDetails parses an Import command string into an internal structure.

func (Import) String Uses

func (imp Import) String() string

type IndirectRef Uses

type IndirectRef struct {
    ObjectNumber     Integer
    GenerationNumber Integer
}

IndirectRef represents a PDF indirect object.

func CIDFontDescriptor Uses

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

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

func CIDFontDict Uses

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

CIDFontDict returns the descendent font dict for Type0 fonts.

func NewIndirectRef Uses

func NewIndirectRef(objectNumber, generationNumber int) *IndirectRef

NewIndirectRef returns a new PDFIndirectRef object.

func NewNUpPageForImage Uses

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

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

func NewPageForImage Uses

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

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

func (IndirectRef) Clone Uses

func (ir IndirectRef) Clone() Object

Clone returns a clone of ir.

func (IndirectRef) Equals Uses

func (ir IndirectRef) Equals(indRef IndirectRef) bool

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

func (IndirectRef) PDFString Uses

func (ir IndirectRef) PDFString() string

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

func (IndirectRef) String Uses

func (ir IndirectRef) String() string

type InheritedPageAttrs Uses

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

InheritedPageAttrs represents all inherited page attributes.

type IntSet Uses

type IntSet map[int]bool

IntSet is a set of integers.

type Integer Uses

type Integer int

Integer represents a PDF integer object.

func (Integer) Clone Uses

func (i Integer) Clone() Object

Clone returns a clone of i.

func (Integer) PDFString Uses

func (i Integer) PDFString() string

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

func (Integer) String Uses

func (i Integer) String() string

func (Integer) Value Uses

func (i Integer) Value() int

Value returns an int value for this PDF object.

type LineJoinStyle Uses

type LineJoinStyle int

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

const (
    LJMiter LineJoinStyle = iota
    LJRound
    LJBevel
)

Render mode

type NUp Uses

type NUp struct {
    PageDim      *Dim        // Page dimensions in user units.
    PageSize     string      // Paper size eg. A4L, A4P, A4(=default=A4P), see paperSize.go
    UserDim      bool        // true if one of dimensions or paperSize provided overriding the default.
    Orient       orientation // One of rd(=default),dr,ld,dl
    Grid         *Dim        // Intra page grid dimensions eg (2,2)
    PageGrid     bool        // Create a mxn grid of pages for PDF inputfiles only (think "extra page n-Up").
    ImgInputFile bool        // Process image or PDF input files.
    Margin       int         // Cropbox for n-Up content.
    Border       bool        // Draw bounding box.
}

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

func DefaultNUpConfig Uses

func DefaultNUpConfig() *NUp

DefaultNUpConfig returns the default NUp configuration.

func ImageGridConfig Uses

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

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

func ImageNUpConfig Uses

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

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

func PDFGridConfig Uses

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

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

func PDFNUpConfig Uses

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

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

func (NUp) String Uses

func (nup NUp) String() string

type Name Uses

type Name string

Name represents a PDF name object.

func (Name) Clone Uses

func (nameObject Name) Clone() Object

Clone returns a clone of nameObject.

func (Name) PDFString Uses

func (nameObject Name) PDFString() string

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

func (Name) String Uses

func (nameObject Name) String() string

func (Name) Value Uses

func (nameObject Name) Value() string

Value returns a string value for this PDF object.

type Node Uses

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

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

func (*Node) Add Uses

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

Add adds an entry to a name tree.

func (*Node) AddToLeaf Uses

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

AddToLeaf adds an entry to a leaf.

func (Node) KeyList Uses

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

KeyList returns a sorted list of all keys.

func (Node) Process Uses

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

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

func (*Node) Remove Uses

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 Uses

func (n Node) String() string

func (Node) Value Uses

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

Value returns the value for given key

type Object Uses

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

Object defines an interface for all Objects.

func ParseObject Uses

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

ParseObject parses an object from file at given offset.

type ObjectStreamDict Uses

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

ObjectStreamDict represents a object stream dictionary.

func NewObjectStreamDict Uses

func NewObjectStreamDict() *ObjectStreamDict

NewObjectStreamDict creates a new ObjectStreamDict object.

func (*ObjectStreamDict) AddObject Uses

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

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

func (*ObjectStreamDict) Finalize Uses

func (osd *ObjectStreamDict) Finalize()

Finalize prepares the final content of the objectstream.

func (*ObjectStreamDict) IndexedObject Uses

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

IndexedObject returns the object at given index from a ObjectStreamDict.

type OptimizationContext Uses

type OptimizationContext struct {

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

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

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

    FixTable  map[int]bool // map for visited objects during xreftable traversal for fixing references to free objects.
    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 Uses

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

DuplicateFontObjectsString returns a formatted string and the number of objs.

func (*OptimizationContext) DuplicateImageObjectsString Uses

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

DuplicateImageObjectsString returns a formatted string and the number of objs.

func (*OptimizationContext) DuplicateInfoObjectsString Uses

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

DuplicateInfoObjectsString returns a formatted string and the number of objs.

func (*OptimizationContext) IsDuplicateFontObject Uses

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

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

func (*OptimizationContext) IsDuplicateImageObject Uses

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

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

func (*OptimizationContext) IsDuplicateInfoObject Uses

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

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

func (*OptimizationContext) NonReferencedObjsString Uses

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

NonReferencedObjsString returns a formatted string and the number of objs.

type PDFFilter Uses

type PDFFilter struct {
    Name        string
    DecodeParms Dict
}

PDFFilter represents a PDF stream filter object.

type PDFImage Uses

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

PDFImage represents a XObject of subtype image.

type PDFStats Uses

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

PDFStats is a container for stats.

func NewPDFStats Uses

func NewPDFStats() PDFStats

NewPDFStats returns a new PDFStats object.

func (PDFStats) AddPageAttr Uses

func (stats PDFStats) AddPageAttr(name int)

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

func (PDFStats) AddRootAttr Uses

func (stats PDFStats) AddRootAttr(name int)

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

func (PDFStats) UsesPageAttr Uses

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 Uses

func (stats PDFStats) UsesRootAttr(name int) bool

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

type Page Uses

type Page struct {
    MediaBox *Rectangle
    Fm       FontMap
    Buf      *bytes.Buffer
}

Page represents rendered page content.

func NewPage Uses

func NewPage(mediaBox *Rectangle) Page

NewPage creates a page for a mediaBox.

func NewPageWithBg Uses

func NewPageWithBg(mediaBox *Rectangle, c SimpleColor) Page

NewPageWithBg creates a page for a mediaBox.

type PageResourceNames Uses

type PageResourceNames map[string]StringSet

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

func NewPageResourceNames Uses

func NewPageResourceNames() PageResourceNames

NewPageResourceNames returns initialized pageResourceNames.

func PageResourceNamesForContent Uses

func PageResourceNamesForContent(s string) PageResourceNames

PageResourceNamesForContent detects all resource names used by s.

func (PageResourceNames) HasContent Uses

func (prn PageResourceNames) HasContent() bool

HasContent returns true in any resource names present.

func (PageResourceNames) HasResources Uses

func (prn PageResourceNames) HasResources(s string) bool

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

func (PageResourceNames) Resources Uses

func (prn PageResourceNames) Resources(s string) StringSet

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

func (PageResourceNames) String Uses

func (prn PageResourceNames) String() string

type Point Uses

type Point struct {
    X, Y float64
}

Point represents a user space location.

type ReadContext Uses

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

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

ReadContext represents the context for reading a PDF file.

func (*ReadContext) IsObjectStreamObject Uses

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 Uses

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

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

func (*ReadContext) LogStats Uses

func (rc *ReadContext) LogStats(optimized bool)

LogStats logs stats for read file.

func (*ReadContext) ObjectStreamsString Uses

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

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

func (*ReadContext) ReadFileSize Uses

func (rc *ReadContext) ReadFileSize() int

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

func (*ReadContext) XRefStreamsString Uses

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

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

type Rectangle Uses

type Rectangle struct {
    *types.Rectangle
}

Rectangle represents a rectangular region in userspace.

func Rect Uses

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

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

func RectForArray Uses

func RectForArray(a Array) *Rectangle

RectForArray returns a new rectangle for given Array.

func RectForDim Uses

func RectForDim(width, height float64) *Rectangle

RectForDim returns a new rectangle for given dimensions.

func RectForFormat Uses

func RectForFormat(f string) *Rectangle

RectForFormat returns a new rectangle for given format.

func RectForWidthAndHeight Uses

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

RectForWidthAndHeight returns a new rectangle for given dimensions.

func WriteColumn Uses

func WriteColumn(buf *bytes.Buffer, mediaBox, region *Rectangle, td TextDescriptor, width float64) *Rectangle

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

func WriteColumnAnchored Uses

func WriteColumnAnchored(buf *bytes.Buffer, mediaBox, region *Rectangle, td TextDescriptor, a anchor, width float64) *Rectangle

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

func WriteMultiLine Uses

func WriteMultiLine(buf *bytes.Buffer, mediaBox, region *Rectangle, td TextDescriptor) *Rectangle

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

func WriteMultiLineAnchored Uses

func WriteMultiLineAnchored(buf *bytes.Buffer, mediaBox, region *Rectangle, td TextDescriptor, a anchor) *Rectangle

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

func (Rectangle) Array Uses

func (r Rectangle) Array() Array

Array returns the PDF representation of a rectangle.

func (Rectangle) CroppedCopy Uses

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

CroppedCopy returns a copy of r with applied margin..

func (Rectangle) FitsWithin Uses

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

FitsWithin returns true if rectangle r fits within rectangle r2.

func (Rectangle) ScaledHeight Uses

func (r Rectangle) ScaledHeight(w float64) float64

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

func (Rectangle) ScaledWidth Uses

func (r Rectangle) ScaledWidth(h float64) float64

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

func (*Rectangle) Translate Uses

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

Translate moves r by dx and dy.

type RenderMode Uses

type RenderMode int

RenderMode represents the text rendering mode (see 9.3.6)

const (
    RMFill RenderMode = iota
    RMStroke
    RMFillAndStroke
)

Render mode

type SimpleColor Uses

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

SimpleColor is a simple rgb wrapper.

func NewSimpleColor Uses

func NewSimpleColor(rgb uint32) SimpleColor

NewSimpleColor returns a SimpleColor for rgb in the form 0x00RRGGBB

func (SimpleColor) String Uses

func (sc SimpleColor) String() string

type StreamDict Uses

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

StreamDict represents a PDF stream dict object.

func NewStreamDict Uses

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

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

func ReadJPEG Uses

func ReadJPEG(xRefTable *XRefTable, buf []byte, c image.Config) (*StreamDict, error)

ReadJPEG generates a PDF image object for a JPEG stream and appends this object to the cross reference table.

func (StreamDict) Clone Uses

func (sd StreamDict) Clone() Object

Clone returns a clone of sd.

func (StreamDict) HasSoleFilterNamed Uses

func (sd StreamDict) HasSoleFilterNamed(filterName string) bool

HasSoleFilterNamed returns true if there is exactly one filter defined for a stream dict.

type StringLiteral Uses

type StringLiteral string

StringLiteral represents a PDF string literal object.

func (StringLiteral) Clone Uses

func (stringliteral StringLiteral) Clone() Object

Clone returns a clone of stringLiteral.

func (StringLiteral) PDFString Uses

func (stringliteral StringLiteral) PDFString() string

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

func (StringLiteral) String Uses

func (stringliteral StringLiteral) String() string

func (StringLiteral) Value Uses

func (stringliteral StringLiteral) Value() string

Value returns a string value for this PDF object.

type StringSet Uses

type StringSet map[string]bool

StringSet is a set of strings.

func NewStringSet Uses

func NewStringSet(slice []string) StringSet

NewStringSet returns a new StringSet for slice.

type TextDescriptor Uses

type TextDescriptor struct {
    Text           string        // A multi line string using \n for line breaks.
    FontName       string        // Corefont name to be used.
    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 (<= 1 for relative scaling).
    HAlign         HAlignment    // Horizontal text alignment.
    VAlign         VAlignment    // Vertical text alignment.
    RMode          RenderMode    // Text render mode
    StrokeCol      SimpleColor   // Stroke color to be used for rendering text corresponding to RMode.
    FillCol        SimpleColor   // Fill color to be used for rendering text corresponding to RMode.
    ShowTextBB     bool          // Render bounding box including BackgroundCol, border and margins.
    ShowBackground bool          // Render background of bounding box using BackgroundCol.
    BackgroundCol  SimpleColor   // Bounding box fill color.
    ShowBorder     bool          // Render border using BorderCol, BorderWidth and BorderStyle.
    BorderWidth    float64       // Border width, visibility depends on ShowBorder.
    BorderStyle    LineJoinStyle // Border style, also visible if ShowBorder is false as long as ShowBackground is true.
    BorderCol      SimpleColor   // Border color.
    ParIndent      bool          // Indent first line of paragraphs or space between paragraphs.
    // Testing
    ShowLineBB  bool // Render line bounding boxes in black.
    ShowMargins bool // Render all margins in light gray.
    HairCross   bool // Draw haircross at X,Y.
}

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

type VAlignment Uses

type VAlignment int

VAlignment represents the vertical alignment of text.

const (
    AlignBaseline VAlignment = iota
    AlignTop
    AlignMiddle
    AlignBottom
)

These are the options for vertical aligned text.

type Version Uses

type Version int

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

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

Constants for all PDF versions up to v1.7

func PDFVersion Uses

func PDFVersion(versionStr string) (Version, error)

PDFVersion returns the PDFVersion for a version string.

func (Version) String Uses

func (v Version) String() string

String returns a string representation for a given PDFVersion.

type Watermark Uses

type Watermark struct {

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

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

func DefaultWatermarkConfig Uses

func DefaultWatermarkConfig() *Watermark

DefaultWatermarkConfig returns the default configuration.

func ParseImageWatermarkDetails Uses

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

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

func ParsePDFWatermarkDetails Uses

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

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

func ParseTextWatermarkDetails Uses

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

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

func (Watermark) OnTopString Uses

func (wm Watermark) OnTopString() string

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

func (Watermark) String Uses

func (wm Watermark) String() string

type WriteContext Uses

type WriteContext struct {

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

WriteContext represents the context for writing a PDF file.

func NewWriteContext Uses

func NewWriteContext(eol string) *WriteContext

NewWriteContext returns a new WriteContext.

func (*WriteContext) HasWriteOffset Uses

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

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

func (*WriteContext) LogStats Uses

func (wc *WriteContext) LogStats()

LogStats logs stats for written file.

func (*WriteContext) SetWriteOffset Uses

func (wc *WriteContext) SetWriteOffset(objNumber int)

SetWriteOffset saves the current write offset to the PDFDestination.

func (*WriteContext) WriteEol Uses

func (wc *WriteContext) WriteEol() error

WriteEol writes an end of line sequence.

type XRefStreamDict Uses

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

XRefStreamDict represents a cross reference stream dictionary.

func NewXRefStreamDict Uses

func NewXRefStreamDict(ctx *Context) *XRefStreamDict

NewXRefStreamDict creates a new PDFXRefStreamDict object.

type XRefTable Uses

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

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

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

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

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

    // Statistics
    Stats PDFStats

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

    // Validation
    Valid          bool // true means successful validated against ISO 32000.
    ValidationMode int  // see Configuration

    Optimized   bool
    Watermarked bool
}

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

func CreateAcroFormDemoXRef Uses

func CreateAcroFormDemoXRef() (*XRefTable, error)

CreateAcroFormDemoXRef creates an xRefTable with an AcroForm example.

func CreateAnnotationDemoXRef Uses

func CreateAnnotationDemoXRef() (*XRefTable, error)

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

func CreateDemoXRef Uses

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

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

func CreateResourceDictInheritanceDemoXRef Uses

func CreateResourceDictInheritanceDemoXRef() (*XRefTable, error)

CreateResourceDictInheritanceDemoXRef creates a page tree for testing resource dict inheritance.

func (*XRefTable) BindNameTrees Uses

func (xRefTable *XRefTable) BindNameTrees() error

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

func (*XRefTable) Catalog Uses

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

Catalog returns a pointer to the root object / catalog.

func (*XRefTable) CatalogHasPieceInfo Uses

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

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

func (*XRefTable) DeleteObject Uses

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

DeleteObject marks an object as free and inserts it into the free list right after the head.

func (*XRefTable) DeleteObjectGraph Uses

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

DeleteObjectGraph deletes all objects reachable by indRef.

func (*XRefTable) Dereference Uses

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

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

func (*XRefTable) DereferenceArray Uses

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

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

func (*XRefTable) DereferenceBoolean Uses

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

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

func (*XRefTable) DereferenceCSVSafeText Uses

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

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

func (*XRefTable) DereferenceDict Uses

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

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

func (*XRefTable) DereferenceDictEntry Uses

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

DereferenceDictEntry returns a dereferenced dict entry.

func (*XRefTable) DereferenceInteger Uses

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

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

func (*XRefTable) DereferenceName Uses

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

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

func (*XRefTable) DereferenceNumber Uses

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

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

func (*XRefTable) DereferenceStreamDict Uses

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

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

func (*XRefTable) DereferenceStreamDictForValidation Uses

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

DereferenceStreamDictForValidation resolves stream dictionary objects and ensures they are visited once only during validation.

func (*XRefTable) DereferenceStringLiteral Uses

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

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

func (*XRefTable) DereferenceStringOrHexLiteral Uses

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

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

func (*XRefTable) DereferenceText Uses

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

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

func (*XRefTable) DetectPageTreeWatermarks Uses

func (xRefTable *XRefTable) DetectPageTreeWatermarks() error

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

func (*XRefTable) EncryptDict Uses

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

EncryptDict returns a pointer to the root object / catalog.

func (*XRefTable) EnsureCollection Uses

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 Uses

func (xRefTable *XRefTable) EnsurePageCount() error

EnsurePageCount evaluates the page count for xRefTable if necessary.

func (*XRefTable) EnsureValidFreeList Uses

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 Uses

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 Uses

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

Exists returns true if xRefTable contains an entry for objNumber.

func (*XRefTable) Find Uses

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

Find returns the XRefTable entry for given object number.

func (*XRefTable) FindObject Uses

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

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

func (*XRefTable) FindTableEntry Uses

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

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

func (*XRefTable) FindTableEntryForIndRef Uses

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

FindTableEntryForIndRef returns the XRefTable entry for given indirect reference.

func (*XRefTable) FindTableEntryLight Uses

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

FindTableEntryLight returns the XRefTable entry for given object number.

func (*XRefTable) Free Uses

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

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

func (*XRefTable) IDFirstElement Uses

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

IDFirstElement returns the first element of ID.

func (*XRefTable) IndRefForNewObject Uses

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

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

func (*XRefTable) InsertAndUseRecycled Uses

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 Uses

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

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

func (*XRefTable) InsertNew Uses

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 Uses

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

InsertObject inserts an object into the xRefTable.

func (*XRefTable) IsLinearizationObject Uses

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

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

func (*XRefTable) LinearizationObjsString Uses

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

LinearizationObjsString returns a formatted string and the number of objs.

func (*XRefTable) LocateNameTree Uses

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

LocateNameTree locates/ensures a specific name tree.

func (*XRefTable) MissingObjects Uses

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

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

func (*XRefTable) NamesDict Uses

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

NamesDict returns the dict that contains all name trees.

func (*XRefTable) NewEmbeddedFileStreamDict Uses

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

NewEmbeddedFileStreamDict creates and returns an embeddedFileStreamDict containing the file "filename".

func (*XRefTable) NewFileSpecDict Uses

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

NewFileSpecDict creates and returns a new fileSpec dictionary.

func (*XRefTable) NewSoundStreamDict Uses

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

NewSoundStreamDict returns a new sound stream dict.

func (*XRefTable) NewStreamDictForBuf Uses

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

NewStreamDictForBuf creates a streamDict for buf.

func (*XRefTable) NewStreamDictForFile Uses

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

NewStreamDictForFile creates a streamDict for filename.

func (*XRefTable) NextForFree Uses

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

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

func (*XRefTable) Outlines Uses

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

Outlines returns the Outlines reference contained in the catalog.

func (*XRefTable) PageContent Uses

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

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

func (*XRefTable) PageDict Uses

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

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

func (*XRefTable) PageDims Uses

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

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

func (*XRefTable) PageNumber Uses

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

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

func (*XRefTable) Pages Uses

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

Pages returns the Pages reference contained in the catalog.

func (*XRefTable) ParseRootVersion Uses

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

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

func (*XRefTable) RemoveCollection Uses

func (xRefTable *XRefTable) RemoveCollection() error

RemoveCollection removes an existing Collection entry from the catalog.

func (*XRefTable) RemoveEmbeddedFilesNameTree Uses

func (xRefTable *XRefTable) RemoveEmbeddedFilesNameTree() error

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

func (*XRefTable) RemoveNameTree Uses

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

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

func (*XRefTable) UndeleteObject Uses

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 Uses

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

ValidateVersion validates against the xRefTable's version.

func (*XRefTable) Version Uses

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 Uses

func (xRefTable *XRefTable) VersionString() string

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

type XRefTableEntry Uses

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

XRefTableEntry represents an entry in the PDF cross reference table.

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

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

func NewFreeHeadXRefTableEntry Uses

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 Uses

func NewXRefTableEntryGen0(obj Object) *XRefTableEntry

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

Directories

PathSynopsis
validatePackage validate implements validation against PDF 32000-1:2008.

Package pdfcpu imports 35 packages (graph) and is imported by 11 packages. Updated 2020-06-29. Refresh now. Tools for package owners.