pdfcpu

package
v0.16.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: Apache-2.0 Imports: 59 Imported by: 155

Documentation

Overview

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

The commands are:

annotations   List, remove page annotations
attachments   List, add, remove, extract embedded file attachments
booklet       Arrange pages onto larger sheets of paper to make a booklet or zine
bookmarks     List, import, export, remove bookmarks
boxes         List, add, remove page boundaries for selected pages
certificates  List, inspect, import, reset certificates
changeopw     Change owner password
changeupw     Change user password
collect       Create custom sequence of selected pages
completion    Generate shell completion script
config        Initialize, list, inspect, validate, reset configuration
create        Create PDF content including forms via JSON
crop          Set cropbox for selected pages
cut           Custom cut pages horizontally or vertically
decrypt       Remove password protection
encrypt       Set password protection
extract       Extract images, fonts, content, pages or metadata
fonts         Install, list supported fonts, create cheat sheets
form          List, remove fields, lock, unlock, reset, export, fill form via JSON or CSV
grid          Rearrange pages or images for enhanced browsing experience
help          Help about any command
images        List, extract, update images
import        Import/convert images to PDF
info          Print file info
keywords      List, add, remove keywords
merge         Concatenate PDFs
ndown         Cut selected page into n pages symmetrically
nup           Rearrange pages or images for reduced number of pages
optimize      Optimize PDF by getting rid of redundant page resources
pagelayout    List, set, reset page layout for opened document
pagemode      List, set, reset page mode for opened document
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
poster        Create poster using paper size
properties    List, add, remove document properties
resize        Scale selected pages
rotate        Rotate selected pages
selectedpages Print definition of the -pages flag
signatures    Remove signatures, validate integrity
split         Split up inFile 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) + basic PDF 2.0 validation
version       Print version
viewerpref    List, set, reset viewer preferences
watermark     Add, remove, update text, image or PDF watermarks for selected pages
zoom          Zoom in/out of selected pages

Index

Constants

View Source
const (

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

Variables

View Source
var (
	// ErrNoBookmarks signals that a PDF has no bookmarks to process.
	ErrNoBookmarks = errors.New("no bookmarks available")

	// ErrInvalidBookmark signals an invalid bookmark tree.
	ErrInvalidBookmark = errors.New("invalid bookmark")

	// ErrInvalidBookmarkJSON signals malformed bookmark JSON data.
	ErrInvalidBookmarkJSON = errors.New("invalid bookmark JSON")

	// ErrExistingBookmarks signals that adding bookmarks would conflict with existing bookmarks.
	ErrExistingBookmarks = errors.New("existing bookmarks")

	// ErrCircularBookmarks signals a circular outline item list.
	ErrCircularBookmarks = errors.New("circular outline item list")
)
View Source
var (

	// ErrMalformedEncryption reports a missing, malformed, or inconsistent encryption dictionary.
	ErrMalformedEncryption = errors.New("malformed encryption")

	// ErrUnsupportedEncryptionFeature reports a recognized encryption algorithm, version, or security handler that pdfcpu cannot process.
	ErrUnsupportedEncryptionFeature = errors.New("unsupported encryption feature")
)
View Source
var (
	// ErrInvalidPageNumber signals an invalid page number.
	ErrInvalidPageNumber = errors.New("invalid page number")

	// ErrMissingAnnotation signals a missing required annotation.
	ErrMissingAnnotation = errors.New("missing annotation")

	// ErrMissingContext signals a missing required Go context.
	ErrMissingContext = model.ErrMissingContext

	// ErrMissingImageReader signals a missing required image reader.
	ErrMissingImageReader = model.ErrMissingImageReader

	// ErrMissingOptimizationContext signals a missing required optimization context.
	ErrMissingOptimizationContext = errors.New("missing optimization context")

	// ErrMissingPageNumbers signals missing required page numbers.
	ErrMissingPageNumbers = errors.New("missing page numbers")

	// ErrMissingPDFContext signals a missing required PDF context.
	ErrMissingPDFContext = model.ErrMissingPDFContext

	// ErrMissingPDFInfo signals missing required PDF info.
	ErrMissingPDFInfo = errors.New("missing PDF info")

	// ErrMissingReadContext signals a missing required PDF read context.
	ErrMissingReadContext = errors.New("missing PDF read context")

	// ErrMissingReader signals a missing required reader.
	ErrMissingReader = errors.New("missing reader")

	// ErrMissingStreamDict signals a missing required PDF stream dictionary.
	ErrMissingStreamDict = errors.New("missing PDF stream dictionary")

	// ErrMissingWatermarkConfiguration signals a missing required watermark configuration.
	ErrMissingWatermarkConfiguration = errors.New("missing watermark configuration")

	// ErrMissingWatermarks signals missing required watermarks.
	ErrMissingWatermarks = errors.New("missing watermarks")

	// ErrMissingWriteContext signals a missing required PDF write context.
	ErrMissingWriteContext = errors.New("missing PDF write context")

	// ErrMissingXRefTable signals a missing required PDF cross-reference table.
	ErrMissingXRefTable = model.ErrMissingXRefTable

	// ErrNoSignatures signals that a PDF has no signatures to process.
	ErrNoSignatures = errors.New("no signatures present")

	// ErrUnsupportedResource signals that extraction skipped a resource because
	// pdfcpu does not support its type or filter. Use errors.Is to identify it.
	ErrUnsupportedResource = errors.New("unsupported resource")

	// ErrUnsupportedVersion reports an unsupported PDF version for the requested
	// operation. It is a stable sentinel intended for use with errors.Is.
	ErrUnsupportedVersion = errors.New("PDF 2.0 unsupported for this operation")

	// ErrVersionTooLow signals that an element requires a newer declared PDF version.
	ErrVersionTooLow = model.ErrVersionTooLow
)
View Source
var (
	// ErrCorruptHeader reports a missing or malformed PDF header.
	ErrCorruptHeader = errors.New("no header version available")

	// ErrEmptyInput reports an empty input stream passed to the PDF reader.
	ErrEmptyInput = errors.New("the file could not be opened because it is empty")

	// ErrEncrypted reports an operation that cannot process encrypted PDFs.
	ErrEncrypted = errors.New("this file is encrypted")

	// ErrMissingXRefSection reports a PDF without a detectable final xref section.
	ErrMissingXRefSection = errors.New("can't detect last xref section")

	// ErrNotEncrypted reports an operation requiring encryption on an unencrypted PDF.
	ErrNotEncrypted = errors.New("this file is not encrypted")

	// ErrOwnerPasswordRequired reports missing owner credentials for an encryption operation.
	ErrOwnerPasswordRequired = errors.New("please provide owner password and optional user password")

	// ErrPermissionDenied reports a PDF operation blocked by encryption permission bits.
	ErrPermissionDenied = errors.New("operation restricted via permission bits setting")

	// ErrPostScriptInput reports a PostScript input stream passed to the PDF reader.
	ErrPostScriptInput = errors.New("PostScript input is not supported; convert to PDF before processing")

	// ErrReferenceDoesNotExist reports a reference to a missing indirect object.
	ErrReferenceDoesNotExist = errors.New("referenced object does not exist")

	// ErrWrongPassword reports supplied PDF credentials that fail password authentication.
	ErrWrongPassword = errors.New("please provide the correct password")
)
View Source
var ErrMissingCertificate = errors.New("missing certificate")

ErrMissingCertificate signals a missing required certificate.

View Source
var ErrNoCertificates = errors.New("no certificates found")

ErrNoCertificates signals that a certificate file contains no usable certificates.

View Source
var ErrUnknownFileType = ErrUnsupportedCertificateFile

ErrUnknownFileType signals an unsupported certificate file type. Deprecated: Use ErrUnsupportedCertificateFile.

View Source
var (
	// ErrUnsupported16BPC reports an unsupported 16-bit image component depth.
	ErrUnsupported16BPC = errors.New("unsupported 16 bits per component")
)

Errors to be identified.

View Source
var ErrUnsupportedCertificateFile = errors.New("unsupported file type")

ErrUnsupportedCertificateFile signals an unsupported certificate file type.

View Source
var (
	// NUpValues contains the supported n-up page counts.
	NUpValues = []int{2, 3, 4, 6, 8, 9, 12, 16}
)

Functions

func AddAnnotation added in v0.4.0

func AddAnnotation(c context.Context, ctx *model.Context, pageDictIndRef *types.IndirectRef, pageDict types.Dict, pageNr int, ar model.AnnotationRenderer, incr bool) (*types.IndirectRef, types.Dict, error)

AddAnnotation adds ar to pageDict.

func AddAnnotationToPage added in v0.8.1

func AddAnnotationToPage(c context.Context, ctx *model.Context, pageNr int, ar model.AnnotationRenderer, incr bool) (*types.IndirectRef, types.Dict, error)

AddAnnotationToPage adds annotation to page.

func AddAnnotations added in v0.4.0

func AddAnnotations(c context.Context, ctx *model.Context, selectedPages types.IntSet, ar model.AnnotationRenderer, incr bool) (bool, error)

AddAnnotations adds ar to selected pages.

func AddAnnotationsMap added in v0.4.0

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

AddAnnotationsMap adds annotations in m to corresponding pages.

func AddBookmarks added in v0.4.0

func AddBookmarks(c context.Context, ctx *model.Context, bms []Bookmark, replace bool) error

AddBookmarks adds bookmarks to ctx and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func AddPages added in v0.3.4

func AddPages(c context.Context, ctxSrc, ctxDest *model.Context, pageNrs []int, usePgCache bool) error

AddPages adds pages and corresponding resources from ctxSrc to ctxDest and supports cancellation.

func AddWatermarks added in v0.1.16

func AddWatermarks(c context.Context, ctx *model.Context, selectedPages types.IntSet, wm *model.Watermark) error

AddWatermarks adds watermarks to all selected pages and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func AddWatermarksMap added in v0.4.0

func AddWatermarksMap(c context.Context, ctx *model.Context, m map[int]*model.Watermark) error

AddWatermarksMap adds watermarks in m to corresponding pages and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func AddWatermarksSliceMap added in v0.4.0

func AddWatermarksSliceMap(c context.Context, ctx *model.Context, m map[int][]*model.Watermark) error

AddWatermarksSliceMap adds watermarks in m to corresponding pages and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func Annotation added in v0.3.12

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

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

func AnnotationsForSelectedPages added in v0.5.0

func AnnotationsForSelectedPages(c context.Context, ctx *model.Context, selectedPages types.IntSet) (map[int]model.PgAnnots, error)

AnnotationsForSelectedPages returns annotations for selected pages and supports cancellation.

func AppendStatsFile

func AppendStatsFile(ctx *model.Context) error

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

func BookletFromImages added in v0.3.9

func BookletFromImages(c context.Context, ctx *model.Context, fileNames []string, nup *model.NUp, pagesDict types.Dict, pagesIndRef *types.IndirectRef) error

BookletFromImages creates a booklet version of the image sequence represented by fileNames. On failure, ctx may contain partial objects or page-tree changes and its PageCount remains unchanged.

func BookletFromPDF added in v0.4.0

func BookletFromPDF(c context.Context, ctx *model.Context, selectedPages types.IntSet, nup *model.NUp) error

BookletFromPDF creates a booklet version of the PDF represented by xRefTable. On failure, the original page tree and PageCount remain authoritative; ctx may contain orphaned partial output objects.

func BookmarkList added in v0.5.0

func BookmarkList(c context.Context, ctx *model.Context) ([]string, error)

BookmarkList returns a formatted bookmark list for ctx and supports cancellation.

func CacheFormFonts added in v0.8.0

func CacheFormFonts(ctx *model.Context) error

CacheFormFonts caches form fonts referenced by ctx.

func CachedAnnotationObjNrs added in v0.4.0

func CachedAnnotationObjNrs(ctx *model.Context) ([]int, error)

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

func CertificatePoolForConfiguration added in v0.16.0

func CertificatePoolForConfiguration(c context.Context, conf *model.Configuration) (*x509.CertPool, error)

CertificatePoolForConfiguration returns the local trust pool selected by conf and supports cancellation. Stateless configurations receive an empty pool without filesystem access.

func ColorSpaceComponents added in v0.4.0

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

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

func ColorSpaceString added in v0.4.0

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

ColorSpaceString returns a string representation for sd's colorspace.

func CopyFile added in v0.10.0

func CopyFile(srcFilename, destFilename string, overwrite bool) (bool, error)

CopyFile copies srcFilename to destFilename.

func CreateContext added in v0.1.20

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

CreateContext creates a context for the given xref table and configuration.

func CreateContextWithXRefTable added in v0.1.20

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

CreateContextWithXRefTable creates a context with an xref table without pages for the given configuration.

func CreateXRefTableWithRootDict added in v0.3.13

func CreateXRefTableWithRootDict() (*model.XRefTable, error)

CreateXRefTableWithRootDict creates an xref table containing a catalog.

func CutPage added in v0.4.1

func CutPage(c context.Context, ctxSrc *model.Context, pageNr int, cut *model.Cut) (*model.Context, error)

CutPage cuts pageNr into tiles using horizontal or vertical cut points and optional styling. It supports cancellation. On failure, ctxSrc may contain orphaned objects and callers must discard any non-nil destination context returned with the error.

func DefaultBookletConfig added in v0.3.9

func DefaultBookletConfig() *model.NUp

DefaultBookletConfig returns the default configuration for a booklet.

func DetectPageTreeWatermarks added in v0.4.0

func DetectPageTreeWatermarks(c context.Context, ctx *model.Context) error

DetectPageTreeWatermarks checks the page tree for watermarks, records the result and supports cancellation.

func DetectWatermarks added in v0.3.1

func DetectWatermarks(c context.Context, ctx *model.Context) error

DetectWatermarks checks ctx for watermarks, records the result and supports cancellation.

func EnsureOutlines added in v0.4.2

func EnsureOutlines(c context.Context, ctx *model.Context, fName string, append bool) error

EnsureOutlines ensures outlines and supports cancellation.

func ExportBookmarksJSON added in v0.5.0

func ExportBookmarksJSON(c context.Context, ctx *model.Context, source string, w io.Writer) (bool, error)

ExportBookmarksJSON writes the bookmark tree for ctx as JSON and supports cancellation.

func ExtractImage added in v0.4.0

func ExtractImage(c context.Context, ctx *model.Context, sd *types.StreamDict, thumb bool, resourceID string, objNr int, stub bool) (*model.Image, error)

ExtractImage extracts an image from sd and supports cancellation.

func ExtractPageContent added in v0.4.0

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

ExtractPageContent extracts the consolidated page content stream for pageNr and supports cancellation.

func ExtractPageImages added in v0.4.0

func ExtractPageImages(c context.Context, ctx *model.Context, pageNr int, stub bool) (map[int]model.Image, error)

ExtractPageImages extracts all images used by pageNr and supports cancellation. Optionally return stubs only. Unsupported resources are handled according to ctx.UnsupportedResourcePolicy.

func ExtractPages added in v0.4.0

func ExtractPages(c context.Context, ctx *model.Context, pageNrs []int, usePgCache bool) (*model.Context, error)

ExtractPages extracts pageNrs into a new context and supports cancellation.

func FontObjNrs added in v0.4.0

func FontObjNrs(c context.Context, ctx *model.Context, pageNr int) ([]int, error)

FontObjNrs returns all font dictionary object numbers for pageNr and supports cancellation. Requires an optimized context.

func GridFromMultipleImages added in v0.14.0

func GridFromMultipleImages(c context.Context, ctx *model.Context, fileNames []string, nup *model.NUp, pagesDict types.Dict, pagesIndRef *types.IndirectRef) error

GridFromMultipleImages creates grid pages containing each image once and supports cancellation. On failure, ctx may contain partial objects or page-tree changes and its PageCount remains unchanged.

func GridFromOneImage added in v0.14.0

func GridFromOneImage(c context.Context, ctx *model.Context, fileName string, nup *model.NUp, pagesDict types.Dict, pagesIndRef *types.IndirectRef) error

GridFromOneImage creates one grid page with instances of one image and supports cancellation. On failure, ctx may contain partial objects and its PageCount remains unchanged.

func GridFromPDF added in v0.14.0

func GridFromPDF(c context.Context, ctx *model.Context, selectedPages types.IntSet, nup *model.NUp) error

GridFromPDF creates a grid version of the PDF represented by ctx and supports cancellation. On failure, the original page tree and PageCount remain authoritative; ctx may contain orphaned partial output objects.

func ImageBookletConfig added in v0.3.9

func ImageBookletConfig(val int, desc string, conf *model.Configuration) (*model.NUp, error)

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

func ImageGridConfig added in v0.2.3

func ImageGridConfig(rows, cols int, desc string, conf *model.Configuration) (*model.NUp, error)

ImageGridConfig returns a grid configuration for image files.

func ImageNUpConfig added in v0.2.3

func ImageNUpConfig(val int, desc string, conf *model.Configuration) (*model.NUp, error)

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

func ImageObjNrs added in v0.4.0

func ImageObjNrs(ctx *model.Context, pageNr int) []int

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

func ImportBookmarks added in v0.5.0

func ImportBookmarks(c context.Context, ctx *model.Context, rd io.Reader, replace bool) (bool, error)

ImportBookmarks creates/replaces bookmarks in ctx as provided by rd and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func InspectCertificate added in v0.11.0

func InspectCertificate(cert *x509.Certificate) (string, error)

InspectCertificate returns a string representation of cert.

func InvalidateCertificatePool added in v0.14.0

func InvalidateCertificatePool()

InvalidateCertificatePool marks the cached trusted certificate pool for reloading. The last successfully loaded pool remains available to in-flight API calls.

func KeywordsAdd added in v0.3.2

func KeywordsAdd(c context.Context, ctx *model.Context, keywords []string) error

KeywordsAdd adds keywords to the document info dict and supports cancellation.

func KeywordsList added in v0.3.2

func KeywordsList(c context.Context, ctx *model.Context) ([]string, error)

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

func KeywordsRemove added in v0.3.2

func KeywordsRemove(c context.Context, ctx *model.Context, keywords []string) (bool, error)

KeywordsRemove deletes keywords from the document info dict. It supports cancellation and returns true if at least one keyword was removed.

func ListAnnotations added in v0.4.0

func ListAnnotations(c context.Context, annots map[int]model.PgAnnots) (int, []string, error)

ListAnnotations returns a formatted list of annotations and supports cancellation.

func ListAnnotationsJSON added in v0.13.0

func ListAnnotationsJSON(c context.Context, annots map[int]model.PgAnnots) (int, []string, error)

ListAnnotationsJSON returns a JSON-formatted list of annotations and supports cancellation.

func ListImages added in v0.4.0

func ListImages(c context.Context, ctx *model.Context, selectedPages types.IntSet) ([]string, error)

ListImages returns a formatted list of embedded images and supports cancellation.

func ListInfo added in v0.5.0

func ListInfo(c context.Context, info *PDFInfo, selectedPages types.IntSet, fonts bool) ([]string, error)

ListInfo returns formatted info about ctx and supports cancellation.

func LoadCertificates added in v0.10.0

func LoadCertificates(c context.Context) error

LoadCertificates loads and caches certificates from the configured local certificate store for signature validation and supports cancellation. Failed loads are not cached and may be retried.

func LoadCertificatesFile added in v0.12.0

func LoadCertificatesFile(c context.Context, filename string) ([]*x509.Certificate, error)

LoadCertificatesFile loads certificates from filename. LoadCertificatesFile supports cancellation.

func MergeXRefTables

func MergeXRefTables(c context.Context, fName string, ctxSrc, ctxDest *model.Context, zip, dividerPage bool) (err error)

MergeXRefTables merges Context ctxSrc into ctxDest by appending its page tree and supports cancellation. zip ... zip 2 files together (eg. 1A,1B,2A,2B,3A,3B...) dividerPage ... insert blank page between merged files (not applicable for zipping)

func NDownPage added in v0.4.1

func NDownPage(c context.Context, ctxSrc *model.Context, pageNr, n int, cut *model.Cut) (*model.Context, error)

NDownPage creates n-down tiles for pageNr with optional styling and supports cancellation. On failure, ctxSrc may contain orphaned objects and callers must discard any non-nil destination context returned with the error.

func NUpFromMultipleImages added in v0.3.8

func NUpFromMultipleImages(c context.Context, ctx *model.Context, fileNames []string, nup *model.NUp, pagesDict types.Dict, pagesIndRef *types.IndirectRef) error

NUpFromMultipleImages creates pages in NUp-style rendering each image once and supports cancellation. On failure, ctx may contain partial objects or page-tree changes and its PageCount remains unchanged.

func NUpFromOneImage added in v0.3.8

func NUpFromOneImage(c context.Context, ctx *model.Context, fileName string, nup *model.NUp, pagesDict types.Dict, pagesIndRef *types.IndirectRef) error

NUpFromOneImage creates one page with instances of one image and supports cancellation. On failure, ctx may contain partial objects and its PageCount remains unchanged.

func NUpFromPDF added in v0.1.21

func NUpFromPDF(c context.Context, ctx *model.Context, selectedPages types.IntSet, nup *model.NUp) error

NUpFromPDF creates an n-up version of the PDF represented by ctx and supports cancellation. On failure, the original page tree and PageCount remain authoritative; ctx may contain orphaned partial output objects.

func NUpValuesForBooklets added in v0.7.0

func NUpValuesForBooklets() []int

NUpValuesForBooklets returns the supported booklet page counts per sheet.

func NewPagesForImage added in v0.10.0

func NewPagesForImage(c context.Context, xRefTable *model.XRefTable, r io.Reader, parentIndRef *types.IndirectRef, imp *Import) ([]*types.IndirectRef, error)

NewPagesForImage creates new page dicts in xRefTable for the image represented by r and supports cancellation.

func OptimizeXRefTable

func OptimizeXRefTable(c context.Context, ctx *model.Context) error

OptimizeXRefTable optimizes an xRefTable by locating redundant embedded fonts and images and supports cancellation.

func PDFBookletConfig added in v0.3.9

func PDFBookletConfig(val int, desc string, conf *model.Configuration) (*model.NUp, error)

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

func PDFGridConfig added in v0.2.3

func PDFGridConfig(rows, cols int, desc string, conf *model.Configuration) (*model.NUp, error)

PDFGridConfig returns a grid configuration for PDF files.

func PDFNUpConfig added in v0.2.3

func PDFNUpConfig(val int, desc string, conf *model.Configuration) (*model.NUp, error)

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

func PageNrFromDestination added in v0.10.0

func PageNrFromDestination(c context.Context, ctx *model.Context, dest types.Object) (int, error)

PageNrFromDestination returns the page number of a destination.

func ParseCutConfig added in v0.4.1

func ParseCutConfig(s string, u types.DisplayUnit) (*model.Cut, error)

ParseCutConfig parses a Cut command string into an internal structure. optionally: horizontalCut, verticalCut, bgcolor, border, margin, origin

func ParseCutConfigForN added in v0.4.1

func ParseCutConfigForN(n int, s string, u types.DisplayUnit) (*model.Cut, error)

ParseCutConfigForN parses a NDown command string into an internal structure. n, Optionally: border, margin, bgcolor

func ParseCutConfigForPoster added in v0.4.1

func ParseCutConfigForPoster(s string, u types.DisplayUnit) (*model.Cut, error)

ParseCutConfigForPoster parses a Cut command string into an internal structure. formsize(=papersize) or dimensions, optionally: scalefactor, border, margin, bgcolor

func ParseImageWatermarkDetails added in v0.3.1

func ParseImageWatermarkDetails(c context.Context, fileName, desc string, onTop bool, u types.DisplayUnit, conf *model.Configuration) (*model.Watermark, error)

ParseImageWatermarkDetails parses an image watermark/stamp command and supports cancellation.

func ParseNUpDetails added in v0.1.21

func ParseNUpDetails(s string, nup *model.NUp) error

ParseNUpDetails parses a NUp command string into an internal structure.

func ParseNUpGridDefinition added in v0.1.21

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

ParseNUpGridDefinition parses grid dimensions into a shared imposition configuration.

func ParseNUpValue added in v0.1.21

func ParseNUpValue(n int, nUp *model.NUp) error

ParseNUpValue parses the NUp value into an internal structure.

func ParseObject added in v0.1.16

func ParseObject(c context.Context, ctx *model.Context, offset int64, objNr, genNr int) (types.Object, error)

ParseObject parses an object at offset using c for cancellation.

func ParsePDFWatermarkDetails added in v0.3.1

func ParsePDFWatermarkDetails(c context.Context, fileName, desc string, onTop bool, u types.DisplayUnit, conf *model.Configuration) (*model.Watermark, error)

ParsePDFWatermarkDetails parses a PDF watermark/stamp command and supports cancellation.

func ParsePageDim added in v0.8.1

func ParsePageDim(v string, u types.DisplayUnit) (*types.Dim, string, error)

ParsePageDim parses page dim.

func ParseResizeConfig added in v0.4.0

func ParseResizeConfig(s string, u types.DisplayUnit) (*model.Resize, error)

ParseResizeConfig parses a Resize command string into an internal structure. Examples: "sc:.5", "form:A4, bgcol:#D00000", or "dim:400 200, border:on".

func ParseTextWatermarkDetails added in v0.3.1

func ParseTextWatermarkDetails(c context.Context, text, desc string, onTop bool, u types.DisplayUnit, conf *model.Configuration) (*model.Watermark, error)

ParseTextWatermarkDetails parses a text watermark/stamp command and supports cancellation.

func ParseZoomConfig added in v0.7.0

func ParseZoomConfig(s string, u types.DisplayUnit) (*model.Zoom, error)

ParseZoomConfig parses a Zoom command string into an internal structure.

func PermissionsList added in v0.5.0

func PermissionsList(p int) (list []string)

PermissionsList returns a list of set permissions.

func PosterPage added in v0.4.1

func PosterPage(c context.Context, ctxSrc *model.Context, pageNr int, cut *model.Cut) (*model.Context, error)

PosterPage creates poster tiles for pageNr using a form size or explicit dimensions and supports cancellation. On failure, ctxSrc may contain orphaned objects and callers must discard any non-nil destination context returned with the error.

func PropertiesAdd added in v0.3.2

func PropertiesAdd(c context.Context, ctx *model.Context, properties map[string]string) error

PropertiesAdd adds properties into the document info dict and supports cancellation.

func PropertiesRemove added in v0.3.2

func PropertiesRemove(c context.Context, ctx *model.Context, properties []string) (bool, error)

PropertiesRemove deletes specified document properties. It supports cancellation and returns true if at least one property was removed. If properties is empty, it removes all properties and catalog XMP metadata.

func Read added in v0.1.18

Read takes a readSeeker and generates a PDF model context, an in-memory representation containing a cross reference table. If the passed Go context is cancelled, reading will be interrupted.

func ReadFile added in v0.1.18

func ReadFile(c context.Context, inFile string, conf *model.Configuration) (*model.Context, error)

ReadFile reads a PDF file and builds the internal model context holding its cross reference table. If the passed Go context is cancelled, reading will be interrupted.

func RemoveAnnotations added in v0.4.0

func RemoveAnnotations(c context.Context, ctx *model.Context, selectedPages types.IntSet, idsAndTypes []string, objNrs []int, incr bool) (bool, error)

RemoveAnnotations removes annotations for selected pages by ID, type or object number and supports cancellation. All annotations for selected pages are removed if neither idsAndTypes nor objNrs are provided. On failure, ctx may contain partial changes and callers must discard it.

func RemoveAnnotationsFromPageDict added in v0.4.0

func RemoveAnnotationsFromPageDict(c context.Context, ctx *model.Context, annotTypes []model.AnnotationType, ids []string, objNrSet types.IntSet, pageDict types.Dict, pageDictObjNr, pageNr int, incr bool) (bool, error)

RemoveAnnotationsFromPageDict removes an annotation by type, ID or object number from pageDict and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func RemoveBookmarks added in v0.5.0

func RemoveBookmarks(c context.Context, ctx *model.Context) (bool, error)

RemoveBookmarks erases all bookmarks from ctx and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func RemoveWatermarks added in v0.2.5

func RemoveWatermarks(c context.Context, ctx *model.Context, selectedPages types.IntSet) error

RemoveWatermarks removes watermarks for all selected pages and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func RenderImage added in v0.3.5

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

RenderImage returns a reader for a decoded image stream.

func Resize added in v0.4.0

func Resize(c context.Context, ctx *model.Context, selectedPages types.IntSet, res *model.Resize) error

Resize resizes selectedPages using res and supports cancellation.

func RotatePages added in v0.1.20

func RotatePages(c context.Context, ctx *model.Context, selectedPages types.IntSet, rotation int) error

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

func SaveCertificates added in v0.14.0

func SaveCertificates(c context.Context, certs []*x509.Certificate, outFile string) error

SaveCertificates saves certificates as a PKCS#7 container, atomically replaces outFile and supports cancellation.

func StreamLength added in v0.4.0

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

StreamLength returns sd's stream length.

func UpdateImagesByObjNr added in v0.9.0

func UpdateImagesByObjNr(c context.Context, ctx *model.Context, rd io.Reader, objNr int) error

UpdateImagesByObjNr replaces an XObject and supports cancellation.

func UpdateImagesByPageNrAndId added in v0.9.0

func UpdateImagesByPageNrAndId(c context.Context, ctx *model.Context, rd io.Reader, pageNr int, id string) error

UpdateImagesByPageNrAndId replaces the XObject referenced by pageNr and id and supports cancellation.

func ValidateSignatures added in v0.10.0

func ValidateSignatures(c context.Context, ra io.ReaderAt, ctx *model.Context, all bool) ([]*model.SignatureValidationResult, error)

ValidateSignatures validates signature integrity, reports available trust evidence, performs a best-effort local assessment and supports cancellation.

func ValidateSignaturesWithCertificatePool added in v0.16.0

func ValidateSignaturesWithCertificatePool(c context.Context, ra io.ReaderAt, ctx *model.Context, all bool, rootCerts *x509.CertPool) ([]*model.SignatureValidationResult, error)

ValidateSignaturesWithCertificatePool validates signatures using rootCerts as the local trust pool and supports cancellation. A nil pool is treated as an empty local trust pool.

func ValidateWatermarkModeParam added in v0.13.0

func ValidateWatermarkModeParam(mode int, modeParm string, onTop bool) error

ValidateWatermarkModeParam validates the user supplied watermark/stamp mode parameter.

func Write added in v0.1.18

func Write(rd io.Reader, filePath string, overwrite bool) (bool, error)

Write rd to filepath and respect overwrite.

func WriteContext

func WriteContext(c context.Context, ctx *model.Context) error

WriteContext generates a PDF file for the cross reference table contained in Context and supports cancellation.

func WriteImage added in v0.1.16

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

WriteImage writes a PDF image object to disk.

func WriteIncrement added in v0.3.12

func WriteIncrement(c context.Context, ctx *model.Context) error

WriteIncrement writes a PDF increment and supports cancellation.

func WriteReader added in v0.3.12

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

WriteReader consumes r's content by writing it transactionally to a file at path and supports cancellation.

func Zoom added in v0.7.0

func Zoom(c context.Context, ctx *model.Context, selectedPages types.IntSet, zoom *model.Zoom) error

Zoom applies zoom to selected pages in ctx and supports cancellation.

Types

type AnnotListMaxLengths added in v0.8.1

type AnnotListMaxLengths struct {
	ObjNr, ID, Rect, Content, Type int
}

AnnotListMaxLengths contains the maximum display width of each annotation list column.

type AnnotationList added in v0.13.0

type AnnotationList struct {
	Header      Header                        `json:"header"`
	Annotations map[int][]AnnotationListEntry `json:"annotations"`
}

AnnotationList represents page annotations formatted for JSON output.

type AnnotationListEntry added in v0.13.0

type AnnotationListEntry struct {
	Type      string     `json:"type"`
	ObjNr     int        `json:"objNr"`
	ID        string     `json:"id,omitempty"`
	Rect      [4]float64 `json:"rect"`
	Content   *string    `json:"content"`
	CustomTyp string     `json:"customType,omitempty"`
}

AnnotationListEntry represents one page annotation formatted for JSON output.

type Bookmark added in v0.3.6

type Bookmark struct {
	Title    string `json:"title"`
	PageFrom int    `json:"page"`
	// PageThru is used for extraction only and reaches from PageFrom through the page before the next bookmark.
	PageThru int                `json:"-"`
	Bold     bool               `json:"bold,omitempty"`
	Italic   bool               `json:"italic,omitempty"`
	Color    *color.SimpleColor `json:"color,omitempty"`
	Kids     []Bookmark         `json:"kids,omitempty"`
	Parent   *Bookmark          `json:"-"`
}

Bookmark represents a PDF bookmark backed by an outline item.

func Bookmarks added in v0.5.0

func Bookmarks(c context.Context, ctx *model.Context) ([]Bookmark, error)

Bookmarks returns all bookmark information in ctx recursively and supports cancellation.

func BookmarksForOutlineItem added in v0.4.0

func BookmarksForOutlineItem(c context.Context, ctx *model.Context, item *types.IndirectRef, parent *Bookmark) ([]Bookmark, error)

BookmarksForOutlineItem returns the bookmarks tree for an outline item and supports cancellation.

func (Bookmark) Style added in v0.3.12

func (bm Bookmark) Style() int

Style returns an int corresponding to the bookmark style.

type BookmarkTree added in v0.5.0

type BookmarkTree struct {
	Header    Header     `json:"header"`
	Bookmarks []Bookmark `json:"bookmarks"`
}

BookmarkTree contains exported bookmark metadata and the bookmark hierarchy.

func ExportBookmarks added in v0.5.0

func ExportBookmarks(c context.Context, ctx *model.Context, source string) (*BookmarkTree, error)

ExportBookmarks returns the bookmark tree for ctx and supports cancellation.

type Font added in v0.3.5

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

Font is a Reader representing an embedded font.

func ExtractFont added in v0.4.0

func ExtractFont(c context.Context, ctx *model.Context, fontObject model.FontObject, objNr int) (*Font, error)

ExtractFont extracts a font from fontObject and supports cancellation.

func ExtractFormFonts added in v0.4.0

func ExtractFormFonts(c context.Context, ctx *model.Context) ([]Font, error)

ExtractFormFonts extracts all form fonts and supports cancellation. Unsupported resources are handled according to ctx.UnsupportedResourcePolicy.

func ExtractPageFonts added in v0.4.0

func ExtractPageFonts(c context.Context, ctx *model.Context, pageNr int, objNrs, skipped types.IntSet) ([]Font, error)

ExtractPageFonts extracts all fonts used by pageNr and supports cancellation. Unsupported resources are handled according to ctx.UnsupportedResourcePolicy.

type Header struct {
	Source   string   `json:"source,omitempty"`
	Version  string   `json:"version"`
	Creation string   `json:"creation"`
	ID       []string `json:"id,omitempty"`
	Title    string   `json:"title,omitempty"`
	Author   string   `json:"author,omitempty"`
	Creator  string   `json:"creator,omitempty"`
	Producer string   `json:"producer,omitempty"`
	Subject  string   `json:"subject,omitempty"`
	Keywords string   `json:"keywords,omitempty"`
}

Header contains metadata written to exported bookmark JSON.

type ImageListMaxLengths added in v0.5.0

type ImageListMaxLengths struct {
	PageNr, ObjNr, ID, Size, Filters int
}

ImageListMaxLengths contains the column widths for a formatted image list.

func Images added in v0.5.0

func Images(c context.Context, ctx *model.Context, selectedPages types.IntSet) ([]map[int]model.Image, *ImageListMaxLengths, error)

Images returns all embedded images of ctx and supports cancellation.

type Import added in v0.1.20

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

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

func DefaultImportConfig added in v0.1.20

func DefaultImportConfig() *Import

DefaultImportConfig returns the default configuration.

func ParseImportDetails added in v0.1.20

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

ParseImportDetails parses an Import command string into an internal structure.

func (Import) String added in v0.1.20

func (imp Import) String() string

String returns the string value of imp.

type Metadata added in v0.3.5

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

Metadata is a Reader representing a metadata dict.

func ExtractMetadata added in v0.4.0

func ExtractMetadata(c context.Context, ctx *model.Context) ([]Metadata, error)

ExtractMetadata returns all metadata of ctx and supports cancellation. Unsupported resources are handled according to ctx.UnsupportedResourcePolicy.

type PDFImage added in v0.1.16

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

PDFImage represents a XObject of subtype image.

type PDFInfo added in v0.5.0

type PDFInfo struct {
	FileName           string                          `json:"source,omitempty"`
	Version            string                          `json:"version"`
	PageCount          int                             `json:"pageCount"`
	PageBoundaries     []model.PageBoundaries          `json:"-"`
	Boundaries         map[string]model.PageBoundaries `json:"pageBoundaries,omitempty"`
	PageDimensions     map[types.Dim]bool              `json:"-"`
	Dimensions         []types.Dim                     `json:"pageSizes,omitempty"`
	Title              string                          `json:"title"`
	Author             string                          `json:"author"`
	Subject            string                          `json:"subject"`
	Producer           string                          `json:"producer"`
	Creator            string                          `json:"creator"`
	CreationDate       string                          `json:"creationDate"`
	ModificationDate   string                          `json:"modificationDate"`
	PageMode           string                          `json:"pageMode,omitempty"`
	PageLayout         string                          `json:"pageLayout,omitempty"`
	ViewerPref         *model.ViewerPreferences        `json:"viewerPreferences,omitempty"`
	Keywords           []string                        `json:"keywords"`
	Properties         map[string]string               `json:"properties"`
	Tagged             bool                            `json:"tagged"`
	Hybrid             bool                            `json:"hybrid"`
	Linearized         bool                            `json:"linearized"`
	UsingXRefStreams   bool                            `json:"usingXRefStreams"`
	UsingObjectStreams bool                            `json:"usingObjectStreams"`
	Watermarked        bool                            `json:"watermarked"`
	Thumbnails         bool                            `json:"thumbnails"`
	Form               bool                            `json:"form"`
	Signatures         bool                            `json:"signatures"`
	AppendOnly         bool                            `json:"appendOnly"`
	Outlines           bool                            `json:"bookmarks"`
	Names              bool                            `json:"names"`
	Encrypted          bool                            `json:"encrypted"`
	Permissions        int                             `json:"permissions"`
	Attachments        []model.Attachment              `json:"attachments,omitempty"`
	Unit               types.DisplayUnit               `json:"-"`
	UnitString         string                          `json:"unit"`
	Fonts              []model.FontInfo                `json:"fonts,omitempty"`
}

PDFInfo contains document properties and structural information for a PDF file.

func Info added in v0.5.0

func Info(c context.Context, ctx *model.Context, fileName string, selectedPages types.IntSet, fonts bool) (*PDFInfo, error)

Info returns info about ctx and supports cancellation.

type PageConfiguration added in v0.8.1

type PageConfiguration struct {
	PageDim  *types.Dim        // page dimensions in display unit; nil inherits each selected page's effective MediaBox.
	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.
	InpUnit  types.DisplayUnit // input display unit.
}

PageConfiguration represents the page config for the "pages insert" command.

func DefaultPageConfiguration added in v0.8.1

func DefaultPageConfiguration() *PageConfiguration

DefaultPageConfiguration returns the default configuration.

func ParsePageConfiguration added in v0.8.1

func ParsePageConfiguration(s string, u types.DisplayUnit) (*PageConfiguration, error)

ParsePageConfiguration parses a page configuration string into an internal structure.

func (PageConfiguration) String added in v0.8.1

func (p PageConfiguration) String() string

String returns the string value of p.

type VersionRequirementError added in v0.16.0

type VersionRequirementError = model.VersionRequirementError

VersionRequirementError reports an element requiring a newer PDF version.

Directories

Path Synopsis
Package color provides PDF color types and parsing utilities.
Package color provides PDF color types and parsing utilities.
Package create generates PDF documents from declarative descriptions.
Package create generates PDF documents from declarative descriptions.
Package draw writes PDF drawing primitives and table separators.
Package draw writes PDF drawing primitives and table separators.
Package fault classifies recoverable PDF conformance faults.
Package fault classifies recoverable PDF conformance faults.
Package font creates and manages PDF font dictionaries and resources.
Package font creates and manages PDF font dictionaries and resources.
Package form reads, writes, fills, and manages PDF form fields.
Package form reads, writes, fills, and manages PDF form fields.
Package format provides locale-independent PDF number formatting.
Package format provides locale-independent PDF number formatting.
Package matrix provides affine transformations for PDF coordinates.
Package matrix provides affine transformations for PDF coordinates.
Package model defines shared PDF processing state and configuration types.
Package model defines shared PDF processing state and configuration types.
Package pkcs7 implements parsing and generation of some PKCS#7 structures.
Package pkcs7 implements parsing and generation of some PKCS#7 structures.
Package primitives renders declarative page content and interactive form elements.
Package primitives renders declarative page content and interactive form elements.
Package safemath provides checked integer arithmetic for untrusted PDF data.
Package safemath provides checked integer arithmetic for untrusted PDF data.
Package sanitize validates and normalizes filesystem paths derived from PDF data.
Package sanitize validates and normalizes filesystem paths derived from PDF data.
Package scan tokenizes PDF object syntax.
Package scan tokenizes PDF object syntax.
Package sign validates PDF signatures and their certificate evidence.
Package sign validates PDF signatures and their certificate evidence.
Package types defines low-level PDF objects, geometry, streams, and layout values.
Package types defines low-level PDF objects, geometry, streams, and layout values.
Package validate implements validation against PDF 32000-1:2008.
Package validate implements validation against PDF 32000-1:2008.

Jump to

Keyboard shortcuts

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