api

package
v0.16.2 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 41 Imported by: 291

Documentation

Overview

Package api lets you integrate pdfcpu's operations into your Go backend.

There are two api layers supporting all pdfcpu operations:

  1. The file based layer (used by pdfcpu's cli)
  2. The io.ReadSeeker/io.Writer based layer for backend integration.

For any pdfcpu command there are two functions.

The file based function always calls the io.ReadSeeker/io.Writer based function:

func CommandFile(c context.Context, inFile, outFile string, conf *pdf.Configuration) error
func Command(c context.Context, rs io.ReadSeeker, w io.Writer, conf *pdf.Configuration) error

eg. for optimization:

func OptimizeFile(c context.Context, inFile, outFile string, conf *pdf.Configuration) error
func Optimize(c context.Context, rs io.ReadSeeker, w io.Writer, conf *pdf.Configuration) error

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrAttachmentOutputCollision signals attachments resolving to the same output path.
	ErrAttachmentOutputCollision = errors.New("attachment output collision")

	// ErrBookletImageOutputConflict signals that booklet output aliases an image input.
	ErrBookletImageOutputConflict = errors.New("booklet image output aliases input")

	// ErrCircularBookmarks signals a circular bookmark tree.
	ErrCircularBookmarks = pdfcpu.ErrCircularBookmarks

	// ErrConfigurationNotWritable signals that the selected configuration mode forbids writes.
	ErrConfigurationNotWritable = errors.New("configuration is not writable")

	// ErrConfigurationResetRequired signals a configuration schema older than the schema required by this build.
	ErrConfigurationResetRequired = model.ErrConfigurationResetRequired

	// ErrConfigurationSchemaTooNew signals a configuration schema newer than the schemas supported by this build.
	ErrConfigurationSchemaTooNew = model.ErrConfigurationSchemaTooNew

	// ErrDuplicateCertificateDestination signals certificate inputs targeting the same installed file.
	ErrDuplicateCertificateDestination = errors.New("duplicate certificate destination")

	// ErrDuplicatePostScriptName aliases the lower-layer duplicate-name sentinel.
	ErrDuplicatePostScriptName = font.ErrDuplicatePostScriptName

	// ErrExistingBookmarks signals that adding bookmarks would conflict with existing bookmarks.
	ErrExistingBookmarks = pdfcpu.ErrExistingBookmarks

	// ErrGridImageOutputConflict signals that grid output aliases an image input.
	ErrGridImageOutputConflict = errors.New("grid image output aliases input")

	// ErrImportImagesOutputConflict signals that import-images output aliases an image input.
	ErrImportImagesOutputConflict = errors.New("import images output aliases image input")

	// ErrInvalidBookmark signals an invalid bookmark tree.
	ErrInvalidBookmark = pdfcpu.ErrInvalidBookmark

	// ErrInvalidBookmarkJSON signals malformed bookmark JSON data.
	ErrInvalidBookmarkJSON = pdfcpu.ErrInvalidBookmarkJSON

	// ErrInvalidCSV signals malformed or incomplete CSV form data.
	ErrInvalidCSV = errors.New("invalid csv input file")

	// ErrInvalidConfigurationMode signals an unsupported configuration loading mode.
	ErrInvalidConfigurationMode = errors.New("invalid configuration mode")

	// ErrInvalidConfigurationSchema signals malformed configuration schema metadata.
	ErrInvalidConfigurationSchema = model.ErrInvalidConfigurationSchema

	// ErrInvalidCutConfiguration signals an invalid cut configuration.
	ErrInvalidCutConfiguration = errors.New("invalid cut configuration")

	// ErrInvalidFormData signals structurally invalid decoded form data.
	ErrInvalidFormData = errors.New("invalid form data")

	// ErrInvalidImageSelection signals an invalid image object or page resource selection.
	ErrInvalidImageSelection = errors.New("invalid image selection")

	// ErrInvalidImportConfiguration signals an invalid image import configuration.
	ErrInvalidImportConfiguration = errors.New("invalid import configuration")

	// ErrInvalidJSON signals invalid JSON form data.
	ErrInvalidJSON = errors.New("invalid JSON encoding")

	// ErrInvalidPageBoundaries signals invalid page boundaries for an operation.
	ErrInvalidPageBoundaries = errors.New("invalid page boundaries")

	// ErrInvalidPageConfiguration signals an invalid page configuration.
	ErrInvalidPageConfiguration = errors.New("invalid page configuration")

	// ErrInvalidPageLayout signals an unsupported page layout.
	ErrInvalidPageLayout = errors.New("invalid page layout")

	// ErrInvalidPageMode signals an unsupported page mode.
	ErrInvalidPageMode = errors.New("invalid page mode")

	// ErrInvalidResizeConfiguration signals an invalid resize configuration.
	ErrInvalidResizeConfiguration = errors.New("invalid resize configuration")

	// ErrInvalidRotation signals a rotation that is not a multiple of 90 degrees.
	ErrInvalidRotation = errors.New("invalid rotation")

	// ErrInvalidSplitPageNumberSequence signals an invalid split page number sequence.
	ErrInvalidSplitPageNumberSequence = errors.New("invalid split page number sequence")

	// ErrInvalidSplitSpan signals an invalid split span.
	ErrInvalidSplitSpan = errors.New("invalid split span")

	// ErrInvalidUnicodePlane signals an invalid Unicode plane.
	ErrInvalidUnicodePlane = errors.New("invalid Unicode plane")

	// ErrInvalidZoomConfiguration signals an invalid zoom configuration.
	ErrInvalidZoomConfiguration = errors.New("invalid zoom configuration")

	// ErrMissingAnnotation signals a missing required annotation.
	ErrMissingAnnotation = pdfcpu.ErrMissingAnnotation

	// ErrMissingBookletConfiguration signals a missing booklet configuration.
	ErrMissingBookletConfiguration = errors.New("missing booklet configuration")

	// ErrMissingBookmarks signals that no bookmarks were provided.
	ErrMissingBookmarks = errors.New("missing bookmarks")

	// ErrMissingBoxConfiguration signals a missing box configuration.
	ErrMissingBoxConfiguration = errors.New("missing box configuration")

	// ErrMissingCertificate signals a missing required certificate.
	ErrMissingCertificate = pdfcpu.ErrMissingCertificate

	// ErrMissingCertificateInput signals a missing required certificate input file.
	ErrMissingCertificateInput = errors.New("missing certificate input")

	// ErrMissingConfiguration signals a missing pdfcpu configuration.
	ErrMissingConfiguration = errors.New("missing configuration")

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

	// ErrMissingCutConfiguration signals a missing cut configuration.
	ErrMissingCutConfiguration = errors.New("missing cut configuration")

	// ErrMissingDigestFunction signals a missing required digest function.
	ErrMissingDigestFunction = errors.New("missing digest function")

	// ErrMissingFontInput signals a missing required font input file.
	ErrMissingFontInput = errors.New("missing font input")

	// ErrMissingFormInput signals a missing required form input reader or file.
	ErrMissingFormInput = errors.New("missing form input")

	// ErrMissingGridConfiguration signals a missing grid configuration.
	ErrMissingGridConfiguration = errors.New("missing grid configuration")

	// ErrMissingImageInput signals a missing required image input.
	ErrMissingImageInput = errors.New("missing image input")

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

	// ErrMissingJSONInput signals a missing required JSON input file.
	ErrMissingJSONInput = errors.New("missing JSON input")

	// ErrMissingJSONOutput signals a missing required JSON output file.
	ErrMissingJSONOutput = errors.New("missing JSON output")

	// ErrMissingJSONReader signals a missing required JSON input reader.
	ErrMissingJSONReader = errors.New("missing JSON reader")

	// ErrMissingJSONWriter signals a missing required JSON output writer.
	ErrMissingJSONWriter = errors.New("missing JSON writer")

	// ErrMissingNUpConfiguration signals a missing n-up configuration.
	ErrMissingNUpConfiguration = errors.New("missing n-up configuration")

	// ErrMissingPageBoundaries signals missing required page boundaries.
	ErrMissingPageBoundaries = errors.New("missing page boundaries")

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

	// ErrMissingPDFInput signals a missing required PDF input file.
	ErrMissingPDFInput = errors.New("missing PDF input")

	// ErrMissingPDFOutput signals a missing required PDF output file.
	ErrMissingPDFOutput = errors.New("missing PDF output")

	// ErrMissingPDFReadSeeker signals a missing required PDF input reader.
	ErrMissingPDFReadSeeker = errors.New("missing PDF read seeker")

	// ErrMissingPDFReadWriteSeeker signals a missing required PDF input/output seeker.
	ErrMissingPDFReadWriteSeeker = errors.New("missing PDF read write seeker")

	// ErrMissingPDFWriter signals a missing required PDF output writer.
	ErrMissingPDFWriter = errors.New("missing PDF writer")

	// ErrMissingReader signals a missing required reader.
	ErrMissingReader = pdfcpu.ErrMissingReader

	// ErrMissingResizeConfiguration signals a missing resize configuration.
	ErrMissingResizeConfiguration = errors.New("missing resize configuration")

	// ErrMissingSplitPageNumbers signals missing split page numbers.
	ErrMissingSplitPageNumbers = errors.New("missing split page numbers")

	// ErrMissingWatermarkConfiguration signals a missing required watermark configuration.
	ErrMissingWatermarkConfiguration = pdfcpu.ErrMissingWatermarkConfiguration

	// ErrMissingWatermarks signals missing required watermarks.
	ErrMissingWatermarks = pdfcpu.ErrMissingWatermarks

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

	// ErrMissingZoomConfiguration signals a missing zoom configuration.
	ErrMissingZoomConfiguration = errors.New("missing zoom configuration")

	// ErrNoAttachmentAdded signals that no attachment was added.
	ErrNoAttachmentAdded = errors.New("no attachment added")

	// ErrNoAttachmentRemoved signals that no attachment was removed.
	ErrNoAttachmentRemoved = errors.New("no attachment removed")

	// ErrNoBookmarks signals that a PDF has no bookmarks to process.
	ErrNoBookmarks = pdfcpu.ErrNoBookmarks

	// ErrNoCertificates signals that a certificate file contains no usable certificates.
	ErrNoCertificates = pdfcpu.ErrNoCertificates

	// ErrNoFormData signals missing form data for a form fill operation.
	ErrNoFormData = errors.New("missing form data")

	// ErrNoFormFieldsAffected signals that a form operation did not change any fields.
	ErrNoFormFieldsAffected = errors.New("no form fields affected")

	// ErrNoKeywordRemoved signals that a remove operation did not match any keyword.
	ErrNoKeywordRemoved = errors.New("no keyword removed")

	// ErrNoOp is retained for source compatibility.
	// Deprecated: viewer-preferences reset operations are idempotent and no longer return ErrNoOp.
	ErrNoOp = errors.New("no operation")

	// ErrNoOutlines is retained for source compatibility.
	// Deprecated: use ErrNoBookmarks.
	ErrNoOutlines = ErrNoBookmarks

	// ErrNoPropertyRemoved signals that a remove operation did not match any property.
	ErrNoPropertyRemoved = errors.New("no property removed")

	// ErrNoSignatures signals that a PDF has no signatures to process.
	ErrNoSignatures = pdfcpu.ErrNoSignatures

	// ErrNUpImageOutputConflict signals that n-up output aliases an image input.
	ErrNUpImageOutputConflict = errors.New("n-up image output aliases input")

	// ErrOutlines is retained for source compatibility.
	// Deprecated: use ErrExistingBookmarks.
	ErrOutlines = ErrExistingBookmarks

	// ErrUnknownFont aliases the lower-layer unknown-font sentinel.
	ErrUnknownFont = font.ErrUnknownFont

	// ErrUnsupportedCertificateFile signals an unsupported certificate input file.
	ErrUnsupportedCertificateFile = pdfcpu.ErrUnsupportedCertificateFile

	// ErrUnsupportedConfigurationSchema signals a configuration schema newer than the supported range.
	ErrUnsupportedConfigurationSchema = errors.New("unsupported configuration schema")

	// ErrUnsupportedFontFile signals an unsupported font input file.
	ErrUnsupportedFontFile = errors.New("unsupported font file")

	// ErrUnsupportedFormDataFormat signals an unsupported form data format.
	ErrUnsupportedFormDataFormat = errors.New("unsupported data format")

	// ErrUpdateImagesOutputConflict signals that update-images output aliases the image input.
	ErrUpdateImagesOutputConflict = errors.New("update images output aliases image input")

	// ErrUserFontNotFound is retained as a compatibility alias for ErrUnknownFont.
	ErrUserFontNotFound = font.ErrUnknownFont

	// ErrVersionTooLow signals that an element requires a newer declared PDF version.
	ErrVersionTooLow = pdfcpu.ErrVersionTooLow
)

Functions

func AddAnnotations added in v0.3.12

func AddAnnotations(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, ann model.AnnotationRenderer, conf *model.Configuration) (err error)

AddAnnotations adds annotations for selected pages in rs, writes the result to w and supports cancellation.

func AddAnnotationsAsIncrement added in v0.3.12

func AddAnnotationsAsIncrement(c context.Context, rws io.ReadWriteSeeker, selectedPages []string, ar model.AnnotationRenderer, conf *model.Configuration) (err error)

AddAnnotationsAsIncrement adds annotations for selected pages in rws, writes a PDF increment and supports cancellation.

func AddAnnotationsFile added in v0.3.12

func AddAnnotationsFile(c context.Context, inFile, outFile string, selectedPages []string, ar model.AnnotationRenderer, conf *model.Configuration, incr bool) (err error)

AddAnnotationsFile adds annotations for selected pages to inFile, writes the result to outFile and supports cancellation.

func AddAnnotationsMap added in v0.3.12

func AddAnnotationsMap(c context.Context, rs io.ReadSeeker, w io.Writer, m map[int][]model.AnnotationRenderer, conf *model.Configuration) (err error)

AddAnnotationsMap adds annotations in m to corresponding pages of rs, writes the result to w and supports cancellation.

func AddAnnotationsMapAsIncrement added in v0.3.12

func AddAnnotationsMapAsIncrement(c context.Context, rws io.ReadWriteSeeker, m map[int][]model.AnnotationRenderer, conf *model.Configuration) (err error)

AddAnnotationsMapAsIncrement adds annotations in m to corresponding pages of rws, writes a PDF increment and supports cancellation.

func AddAnnotationsMapFile added in v0.3.12

func AddAnnotationsMapFile(c context.Context, inFile, outFile string, m map[int][]model.AnnotationRenderer, conf *model.Configuration, incr bool) (err error)

AddAnnotationsMapFile adds annotations in m to corresponding pages of inFile, writes the result to outFile and supports cancellation.

func AddAttachments

func AddAttachments(c context.Context, rs io.ReadSeeker, w io.Writer, files []string, coll bool, conf *model.Configuration) (err error)

AddAttachments embeds files into a PDF context read from rs, writes the result to w and supports cancellation. Each file is either a filename or a filename and description separated by a comma.

func AddAttachmentsFile added in v0.2.3

func AddAttachmentsFile(c context.Context, inFile, outFile string, files []string, coll bool, conf *model.Configuration) (err error)

AddAttachmentsFile embeds files into a PDF context read from inFile, writes the result to outFile and supports cancellation.

Example

ExampleAddAttachmentsFile demonstrates add attachments file.

// Attach 3 files to in.pdf.
AddAttachmentsFile(context.Background(), "in.pdf", "", []string{"img.jpg", "attach.pdf", "test.zip"}, false, nil)

func AddBookmarks added in v0.3.12

func AddBookmarks(c context.Context, rs io.ReadSeeker, w io.Writer, bms []pdfcpu.Bookmark, replace bool, conf *model.Configuration) (err error)

AddBookmarks adds bookmarks to the PDF context read from rs, writes the result to w and supports cancellation.

func AddBookmarksFile added in v0.3.12

func AddBookmarksFile(c context.Context, inFile, outFile string, bms []pdfcpu.Bookmark, replace bool, conf *model.Configuration) (err error)

AddBookmarksFile adds bookmarks to the PDF context read from inFile, writes the result to outFile and supports cancellation.

func AddBoxes added in v0.3.8

func AddBoxes(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, pb *model.PageBoundaries, conf *model.Configuration) (err error)

AddBoxes adds page boundaries for selected pages of rs, writes the result to w and supports cancellation.

func AddBoxesFile added in v0.3.8

func AddBoxesFile(c context.Context, inFile, outFile string, selectedPages []string, pb *model.PageBoundaries, conf *model.Configuration) (err error)

AddBoxesFile adds page boundaries for selected pages of inFile, writes the result to outFile and supports cancellation.

func AddImageWatermarksFile added in v0.3.4

func AddImageWatermarksFile(c context.Context, inFile, outFile string, selectedPages []string, onTop bool, fileName, desc string, conf *model.Configuration) error

AddImageWatermarksFile adds image stamps/watermarks to all selected pages of inFile, writes the result to outFile and supports cancellation.

func AddImageWatermarksForReaderFile added in v0.3.12

func AddImageWatermarksForReaderFile(c context.Context, inFile, outFile string, selectedPages []string, onTop bool, r io.Reader, desc string, conf *model.Configuration) error

AddImageWatermarksForReaderFile adds image stamps/watermarks to all selected pages of inFile for r, writes the result to outFile and supports cancellation.

func AddKeywords added in v0.3.2

func AddKeywords(c context.Context, rs io.ReadSeeker, w io.Writer, keywords []string, conf *model.Configuration) (err error)

AddKeywords adds keywords to rs's infodict, writes the result to w and supports cancellation.

func AddKeywordsFile added in v0.3.2

func AddKeywordsFile(c context.Context, inFile, outFile string, keywords []string, conf *model.Configuration) (err error)

AddKeywordsFile adds keywords to inFile's infodict, writes the result to outFile and supports cancellation.

func AddPDFWatermarksFile added in v0.3.4

func AddPDFWatermarksFile(c context.Context, inFile, outFile string, selectedPages []string, onTop bool, fileName, desc string, conf *model.Configuration) error

AddPDFWatermarksFile adds PDF stamps/watermarks to inFile, writes the result to outFile and supports cancellation.

func AddPDFWatermarksForReadSeekerFile added in v0.13.0

func AddPDFWatermarksForReadSeekerFile(c context.Context, inFile, outFile string, selectedPages []string, onTop bool, rs io.ReadSeeker, pageNrSrc int, desc string, conf *model.Configuration) error

AddPDFWatermarksForReadSeekerFile adds PDF stamps/watermarks to inFile for rs, writes the result to outFile and supports cancellation.

func AddProperties added in v0.3.2

func AddProperties(c context.Context, rs io.ReadSeeker, w io.Writer, properties map[string]string, conf *model.Configuration) (err error)

AddProperties adds properties to rs's infodict, writes the result to w and supports cancellation.

func AddPropertiesFile added in v0.3.2

func AddPropertiesFile(c context.Context, inFile, outFile string, properties map[string]string, conf *model.Configuration) (err error)

AddPropertiesFile adds properties to inFile's infodict, writes the result to outFile and supports cancellation.

func AddTextWatermarksFile added in v0.3.4

func AddTextWatermarksFile(c context.Context, inFile, outFile string, selectedPages []string, onTop bool, text, desc string, conf *model.Configuration) error

AddTextWatermarksFile adds text stamps/watermarks to all selected pages of inFile, writes the result to outFile and supports cancellation.

func AddWatermarks added in v0.1.16

func AddWatermarks(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, wm *model.Watermark, conf *model.Configuration) (err error)

AddWatermarks adds watermarks to all selected pages in rs, writes the result to w and supports cancellation.

func AddWatermarksFile added in v0.2.3

func AddWatermarksFile(c context.Context, inFile, outFile string, selectedPages []string, wm *model.Watermark, conf *model.Configuration) (err error)

AddWatermarksFile adds watermarks to all selected pages of inFile, writes the result to outFile and supports cancellation.

Example

ExampleAddWatermarksFile demonstrates add watermarks file.

// Unique abbreviations are accepted for all watermark descriptor parameters.
// eg. sc = scalefactor or rot = rotation

// Add a "Demo" watermark to all pages of in.pdf along the diagonal running from lower left to upper right.
onTop := false
update := false
wm, _ := TextWatermark(context.Background(), "Demo", "", onTop, update, types.POINTS, nil)
AddWatermarksFile(context.Background(), "in.pdf", "", nil, wm, nil)

// Stamp all odd pages of in.pdf in red "Confidential" in 48 point Courier
// using a rotation angle of 45 degrees and an absolute scalefactor of 1.0.
onTop = true
wm, _ = TextWatermark(context.Background(), "Confidential", "font:Courier, points:48, col: 1 0 0, rot:45, scale:1 abs, ", onTop, update, types.POINTS, nil)
AddWatermarksFile(context.Background(), "in.pdf", "", []string{"odd"}, wm, nil)

// Add image stamps to in.pdf using absolute scaling and a negative rotation of 90 degrees.
wm, _ = ImageWatermark(context.Background(), "image.png", "scalefactor:.5 a, rot:-90", onTop, update, types.POINTS, nil)
AddWatermarksFile(context.Background(), "in.pdf", "", nil, wm, nil)

// Add a PDF stamp to all pages of in.pdf using the 2nd page of stamp.pdf, use absolute scaling of 0.5
// and rotate along the 2nd diagonal running from upper left to lower right corner.
wm, _ = PDFWatermark(context.Background(), "stamp.pdf:2", "scale:.5 abs, diagonal:2", onTop, update, types.POINTS, nil)
AddWatermarksFile(context.Background(), "in.pdf", "", nil, wm, nil)

func AddWatermarksMap added in v0.3.8

func AddWatermarksMap(c context.Context, rs io.ReadSeeker, w io.Writer, m map[int]*model.Watermark, conf *model.Configuration) (err error)

AddWatermarksMap adds watermarks in m to corresponding pages in rs, writes the result to w and supports cancellation.

func AddWatermarksMapFile added in v0.3.8

func AddWatermarksMapFile(c context.Context, inFile, outFile string, m map[int]*model.Watermark, conf *model.Configuration) (err error)

AddWatermarksMapFile adds watermarks to corresponding pages in m of inFile, writes the result to outFile and supports cancellation.

func AddWatermarksSliceMap added in v0.3.10

func AddWatermarksSliceMap(c context.Context, rs io.ReadSeeker, w io.Writer, m map[int][]*model.Watermark, conf *model.Configuration) (err error)

AddWatermarksSliceMap adds watermarks in m to corresponding pages in rs, writes the result to w and supports cancellation.

func AddWatermarksSliceMapFile added in v0.3.10

func AddWatermarksSliceMapFile(c context.Context, inFile, outFile string, m map[int][]*model.Watermark, conf *model.Configuration) (err error)

AddWatermarksSliceMapFile adds watermarks to corresponding pages in m of inFile, writes the result to outFile and supports cancellation.

func Annotations added in v0.5.0

func Annotations(c context.Context, rs io.ReadSeeker, selectedPages []string, conf *model.Configuration) (m map[int]model.PgAnnots, err error)

Annotations returns page annotations of rs for selected pages and supports cancellation.

func Attachments added in v0.5.0

func Attachments(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (aa []model.Attachment, err error)

Attachments returns rs's attachments and supports cancellation.

func Booklet added in v0.3.9

func Booklet(c context.Context, rs io.ReadSeeker, w io.Writer, imgFiles, selectedPages []string, nup *model.NUp, conf *model.Configuration) (err error)

Booklet arranges PDF pages on larger sheets, writes the result to w and supports cancellation.

func BookletFile added in v0.3.9

func BookletFile(c context.Context, inFiles []string, outFile string, selectedPages []string, nup *model.NUp, conf *model.Configuration) (err error)

BookletFile rearranges PDF pages or images into a booklet layout, writes the result to outFile and supports cancellation.

func BookletFromImages added in v0.3.9

func BookletFromImages(c context.Context, conf *model.Configuration, imageFileNames []string, nup *model.NUp) (ctx *model.Context, err error)

BookletFromImages creates a booklet from images and supports cancellation. On error, callers must discard any non-nil context returned with the error.

func Bookmarks added in v0.5.0

func Bookmarks(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (bms []pdfcpu.Bookmark, err error)

Bookmarks returns rs's bookmark hierarchy and supports cancellation.

func Box added in v0.3.8

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

Box parses a box definition.

func Boxes added in v0.5.0

func Boxes(c context.Context, rs io.ReadSeeker, selectedPages []string, conf *model.Configuration) (pb []model.PageBoundaries, err error)

Boxes returns rs's page boundaries for selected pages and supports cancellation.

func ChangeOwnerPassword

func ChangeOwnerPassword(c context.Context, rs io.ReadSeeker, w io.Writer, pwOld, pwNew string, conf *model.Configuration) (err error)

ChangeOwnerPassword reads a PDF stream from rs, changes the owner password, writes the encrypted PDF stream to w and supports cancellation. A configuration containing the current passwords is required.

func ChangeOwnerPasswordFile added in v0.2.3

func ChangeOwnerPasswordFile(c context.Context, inFile, outFile string, pwOld, pwNew string, conf *model.Configuration) (err error)

ChangeOwnerPasswordFile reads inFile, changes the owner password, writes the result to outFile and supports cancellation. A configuration containing the current passwords is required.

Example

ExampleChangeOwnerPasswordFile demonstrates change owner password file.

// Changing the owner password for an AES-256 encrypted file.
conf := model.NewAESConfiguration("upw", "opw", 256)
ChangeOwnerPasswordFile(context.Background(), "in.pdf", "", "opw", "opwNew", conf)

func ChangeUserPassword

func ChangeUserPassword(c context.Context, rs io.ReadSeeker, w io.Writer, pwOld, pwNew string, conf *model.Configuration) (err error)

ChangeUserPassword reads a PDF stream from rs, changes the user password, writes the encrypted PDF stream to w and supports cancellation. A configuration containing the current passwords is required.

func ChangeUserPasswordFile added in v0.2.3

func ChangeUserPasswordFile(c context.Context, inFile, outFile string, pwOld, pwNew string, conf *model.Configuration) (err error)

ChangeUserPasswordFile reads inFile, changes the user password, writes the result to outFile and supports cancellation. A configuration containing the current passwords is required.

Example

ExampleChangeUserPasswordFile demonstrates change user password file.

// Changing the user password for an AES-256 encrypted file.
conf := model.NewAESConfiguration("upw", "opw", 256)
ChangeUserPasswordFile(context.Background(), "in.pdf", "", "upw", "upwNew", conf)

func Collect added in v0.3.2

func Collect(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, conf *model.Configuration) (err error)

Collect creates a custom PDF page sequence for selected pages of rs, writes it to w and supports cancellation.

func CollectFile added in v0.3.2

func CollectFile(c context.Context, inFile, outFile string, selectedPages []string, conf *model.Configuration) (err error)

CollectFile creates a custom PDF page sequence for inFile, writes the result to outFile and supports cancellation.

func Create added in v0.4.0

func Create(c context.Context, rs io.ReadSeeker, rd io.Reader, w io.Writer, conf *model.Configuration) (err error)

Create renders the PDF structure represented by rs into w and supports cancellation. If rs is present, new PDF content will be appended including any empty pages needed. rd is a JSON representation of PDF page content which may include form data.

func CreateCheatSheetsUserFonts added in v0.3.7

func CreateCheatSheetsUserFonts(c context.Context, fontNames []string) error

CreateCheatSheetsUserFonts atomically generates a batch of user-font cheat sheets and supports cancellation.

func CreateFile added in v0.4.0

func CreateFile(c context.Context, inFilePDF, inFileJSON, outFilePDF string, conf *model.Configuration) (err error)

CreateFile renders the PDF structure represented by inFileJSON into outFilePDF and supports cancellation. If inFilePDF is present, new PDF content will be appended including any empty pages needed. inFileJSON represents PDF page content which may include form data.

func CreatePDFFile added in v0.2.3

func CreatePDFFile(c context.Context, xRefTable *model.XRefTable, outFile string, conf *model.Configuration) error

CreatePDFFile creates a PDF file for an xRefTable and supports cancellation.

func CreateUserFontCheatSheets added in v0.16.0

func CreateUserFontCheatSheets(c context.Context, dir, fn string) error

CreateUserFontCheatSheets atomically generates and publishes one PDF for each covered Unicode plane and supports cancellation.

func Crop added in v0.3.8

func Crop(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, b *model.Box, conf *model.Configuration) (err error)

Crop adds crop boxes for selected pages of rs, writes the result to w and supports cancellation.

func CropFile added in v0.3.8

func CropFile(c context.Context, inFile, outFile string, selectedPages []string, b *model.Box, conf *model.Configuration) (err error)

CropFile adds crop boxes for selected pages of inFile, writes the result to outFile and supports cancellation.

func Cut added in v0.4.1

func Cut(c context.Context, rs io.ReadSeeker, outDir, fileName string, selectedPages []string, cut *model.Cut, conf *model.Configuration) (err error)

Cut applies cutConf for selected pages of rs, writes results to outDir and supports cancellation. Each generated output is written atomically. Outputs completed before cancellation remain in outDir.

func CutFile added in v0.4.1

func CutFile(c context.Context, inFile, outDir, outFile string, selectedPages []string, cut *model.Cut, conf *model.Configuration) (err error)

CutFile applies cutConf for selected pages of inFile, writes results to outDir and supports cancellation. Each generated output is written atomically. Outputs completed before cancellation remain in outDir.

func Decrypt

func Decrypt(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

Decrypt reads an encrypted PDF stream from rs, writes the decrypted PDF stream to w and supports cancellation. A configuration containing at least the current passwords is required.

func DecryptFile added in v0.2.3

func DecryptFile(c context.Context, inFile, outFile string, conf *model.Configuration) (err error)

DecryptFile decrypts inFile, writes the result to outFile and supports cancellation. A configuration containing at least the current passwords is required.

Example

ExampleDecryptFile demonstrates decrypt file.

// Decrypting an AES-256 encrypted file.
conf := model.NewAESConfiguration("upw", "opw", 256)
DecryptFile(context.Background(), "in.pdf", "", conf)

func DefaultBookletConfig added in v0.14.0

func DefaultBookletConfig() *model.NUp

DefaultBookletConfig returns the default configuration for a booklet.

func DefaultImportConfig added in v0.14.0

func DefaultImportConfig() *pdfcpu.Import

DefaultImportConfig returns the default image import configuration.

func DisableConfigDir deprecated added in v0.3.6

func DisableConfigDir()

DisableConfigDir disables the configuration directory. Any needed default configuration will be loaded from configuration.go Since the config dir also contains the user font dir, this also limits font usage to the default core font set No user fonts will be available.

Deprecated: use LoadConfiguration with ConfigurationModeStateless.

func Encrypt

func Encrypt(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

Encrypt reads a PDF stream from rs, writes the encrypted PDF stream to w and supports cancellation. A configuration containing at least the current passwords is required.

func EncryptFile added in v0.2.3

func EncryptFile(c context.Context, inFile, outFile string, conf *model.Configuration) (err error)

EncryptFile encrypts inFile, writes the result to outFile and supports cancellation. A configuration containing at least the current passwords is required.

Example

ExampleEncryptFile demonstrates encrypt file.

// Encrypting a file using AES-256.
conf := model.NewAESConfiguration("upw", "opw", 256)
EncryptFile(context.Background(), "in.pdf", "", conf)

func EnsureDefaultConfigAt deprecated added in v0.3.6

func EnsureDefaultConfigAt(path string) error

EnsureDefaultConfigAt switches to the pdfcpu config dir located at path. If path/pdfcpu is not existent, it will be created including config.yml

Deprecated: use LoadConfiguration with ConfigurationOptions.Root.

func ExportBookmarksFile added in v0.5.0

func ExportBookmarksFile(c context.Context, inFilePDF, outFileJSON string, conf *model.Configuration) (err error)

ExportBookmarksFile extracts bookmark data from inFilePDF, writes it to outFileJSON and supports cancellation.

func ExportBookmarksJSON added in v0.5.0

func ExportBookmarksJSON(c context.Context, rs io.ReadSeeker, w io.Writer, source string, conf *model.Configuration) (err error)

ExportBookmarksJSON extracts bookmark data from rs, writes the result to w and supports cancellation.

func ExportForm added in v0.4.0

func ExportForm(c context.Context, rs io.ReadSeeker, source string, conf *model.Configuration) (formGroup *form.FormGroup, err error)

ExportForm extracts form data originating from source from rs and supports cancellation.

func ExportFormFile added in v0.4.0

func ExportFormFile(c context.Context, inFilePDF, outFileJSON string, conf *model.Configuration) (err error)

ExportFormFile extracts form data from inFilePDF, writes the result to outFileJSON and supports cancellation.

func ExportFormJSON added in v0.5.0

func ExportFormJSON(c context.Context, rs io.ReadSeeker, w io.Writer, source string, conf *model.Configuration) (err error)

ExportFormJSON extracts form data originating from source from rs, writes the result to w and supports cancellation.

func ExtractAttachments

func ExtractAttachments(c context.Context, rs io.ReadSeeker, outDir string, fileNames []string, conf *model.Configuration) (err error)

ExtractAttachments extracts embedded files from a PDF context read from rs into outDir and supports cancellation.

func ExtractAttachmentsFile added in v0.2.3

func ExtractAttachmentsFile(c context.Context, inFile, outDir string, files []string, conf *model.Configuration) (err error)

ExtractAttachmentsFile extracts embedded files from a PDF context read from inFile into outDir and supports cancellation.

Example

ExampleExtractAttachmentsFile demonstrates extract attachments file.

// Extract 1 attachment from in.pdf into outDir.
ExtractAttachmentsFile(context.Background(), "in.pdf", "outDir", []string{"img.jpg"}, nil)

// Extract all attachments from in.pdf into outDir
ExtractAttachmentsFile(context.Background(), "in.pdf", "outDir", nil, nil)

func ExtractAttachmentsRaw added in v0.3.12

func ExtractAttachmentsRaw(c context.Context, rs io.ReadSeeker, outDir string, fileNames []string, conf *model.Configuration) (aa []model.Attachment, err error)

ExtractAttachmentsRaw extracts embedded files from a PDF context read from rs and supports cancellation. outDir is retained for API compatibility and is otherwise ignored.

func ExtractContent

func ExtractContent(c context.Context, rs io.ReadSeeker, selectedPages []string, digestContent func(io.Reader, int) error, conf *model.Configuration) (err error)

ExtractContent retrieves and digests PDF sources for selected pages and supports cancellation.

func ExtractContentFile added in v0.2.3

func ExtractContentFile(c context.Context, inFile, outDir string, selectedPages []string, conf *model.Configuration) (err error)

ExtractContentFile dumps PDF sources into outDir for selected pages and supports cancellation.

Example

ExampleExtractContentFile demonstrates extract content file.

// Extract content for all pages in PDF syntax from in.pdf into outDir.
ExtractContentFile(context.Background(), "in.pdf", "outDir", nil, nil)

func ExtractFonts

func ExtractFonts(c context.Context, rs io.ReadSeeker, selectedPages []string, digestFont func(pdfcpu.Font) error, conf *model.Configuration) (err error)

ExtractFonts retrieves and digests embedded fontfiles from rs for selected pages. Unsupported resources are handled according to conf.UnsupportedResourcePolicy. In skip mode err contains an *UnsupportedResourceError after all supported fonts have been digested. Extraction supports cancellation.

func ExtractFontsFile added in v0.2.3

func ExtractFontsFile(c context.Context, inFile, outDir string, selectedPages []string, conf *model.Configuration) (err error)

ExtractFontsFile writes embedded fontfiles from inFile into outDir for selected pages. Unsupported resources are handled according to conf.UnsupportedResourcePolicy. In skip mode err contains an *UnsupportedResourceError after all supported fonts have been written. Extraction supports cancellation.

Example

ExampleExtractFontsFile demonstrates extract fonts file.

// Extract embedded fonts for pages 1-3 from in.pdf into outDir.
ExtractFontsFile(context.Background(), "in.pdf", "outDir", []string{"1-3"}, nil)

func ExtractImages

func ExtractImages(c context.Context, rs io.ReadSeeker, selectedPages []string, digestImage func(model.Image, bool, int) error, conf *model.Configuration) (err error)

ExtractImages extracts and digests embedded image resources from rs for selected pages. Unsupported resources are handled according to conf.UnsupportedResourcePolicy. In skip mode err contains an *UnsupportedResourceError after all supported images have been digested. Extraction supports cancellation.

func ExtractImagesFile added in v0.2.3

func ExtractImagesFile(c context.Context, inFile, outDir string, selectedPages []string, conf *model.Configuration) (err error)

ExtractImagesFile dumps embedded image resources from inFile into outDir for selected pages. Unsupported resources are handled according to conf.UnsupportedResourcePolicy. In skip mode err contains an *UnsupportedResourceError after all supported images have been written. Extraction supports cancellation.

Example

ExampleExtractImagesFile demonstrates extract images file.

// Extract embedded images from in.pdf into outDir.
ExtractImagesFile(context.Background(), "in.pdf", "outDir", nil, nil)

func ExtractImagesRaw added in v0.3.12

func ExtractImagesRaw(c context.Context, rs io.ReadSeeker, selectedPages []string, conf *model.Configuration) (images []map[int]model.Image, err error)

ExtractImagesRaw returns image maps containing readers for images on selectedPages. Note: may be memory intensive. Unsupported resources are handled according to conf.UnsupportedResourcePolicy. In skip mode err contains an *UnsupportedResourceError and images contains all successfully extracted images. Extraction supports cancellation and may be memory intensive.

func ExtractMetadata added in v0.1.16

func ExtractMetadata(c context.Context, rs io.ReadSeeker, digestMetadata func(pdfcpu.Metadata) error, conf *model.Configuration) (err error)

ExtractMetadata retrieves and digests all metadata dict entries for rs. Unsupported resources are handled according to conf.UnsupportedResourcePolicy. In skip mode err contains an *UnsupportedResourceError after all supported metadata has been digested. Extraction supports cancellation.

func ExtractMetadataFile added in v0.2.3

func ExtractMetadataFile(c context.Context, inFile, outDir string, conf *model.Configuration) (err error)

ExtractMetadataFile dumps all metadata dict entries for inFile into outDir. Unsupported resources are handled according to conf.UnsupportedResourcePolicy. In skip mode err contains an *UnsupportedResourceError after all supported metadata has been written. Extraction supports cancellation.

Example

ExampleExtractMetadataFile demonstrates extract metadata file.

// Extract all metadata from in.pdf into outDir.
ExtractMetadataFile(context.Background(), "in.pdf", "outDir", nil)

func ExtractPage added in v0.8.0

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

ExtractPage extracts pageNr out of ctx into an io.Reader and supports cancellation.

func ExtractPages

func ExtractPages(c context.Context, rs io.ReadSeeker, selectedPages []string, digestPage func(io.Reader, int) error, conf *model.Configuration) (err error)

ExtractPages retrieves and digests single page PDF files for selected pages and supports cancellation.

func ExtractPagesFile added in v0.2.3

func ExtractPagesFile(c context.Context, inFile, outDir string, selectedPages []string, conf *model.Configuration) (err error)

ExtractPagesFile generates single page PDF files for selected pages and supports cancellation.

Example

ExampleExtractPagesFile demonstrates extract pages file.

// Extract all even numbered pages from in.pdf into outDir.
ExtractPagesFile(context.Background(), "in.pdf", "outDir", []string{"even"}, nil)

func FillForm added in v0.4.0

func FillForm(c context.Context, rs io.ReadSeeker, rd io.Reader, w io.Writer, conf *model.Configuration) (err error)

FillForm populates the form rs with data from rd, writes the result to w and supports cancellation.

func FillFormFile added in v0.4.0

func FillFormFile(c context.Context, inFilePDF, inFileJSON, outFilePDF string, conf *model.Configuration) (err error)

FillFormFile populates the form inFilePDF with data from inFileJSON, writes the result to outFilePDF and supports cancellation.

func FormFields added in v0.5.0

func FormFields(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (fields []form.Field, err error)

FormFields returns all form fields of rs and supports cancellation.

func GetPermissions added in v0.3.4

func GetPermissions(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (p *int16, err error)

GetPermissions returns the permissions for rs and supports cancellation.

func GetPermissionsFile added in v0.3.4

func GetPermissionsFile(c context.Context, inFile string, conf *model.Configuration) (p *int16, err error)

GetPermissionsFile returns the permissions for inFile and supports cancellation.

func Grid added in v0.14.0

func Grid(c context.Context, rs io.ReadSeeker, w io.Writer, imgFiles, selectedPages []string, nup *model.NUp, conf *model.Configuration) (err error)

Grid rearranges PDF pages or images into page grids, writes the result to w and supports cancellation. Either rs or imgFiles will be used.

func GridFile added in v0.14.0

func GridFile(c context.Context, inFiles []string, outFile string, selectedPages []string, nup *model.NUp, conf *model.Configuration) (err error)

GridFile rearranges PDF pages or images into page grids, writes the result to outFile and supports cancellation.

func GridFromImage added in v0.14.0

func GridFromImage(c context.Context, conf *model.Configuration, imageFileNames []string, nup *model.NUp) (ctx *model.Context, err error)

GridFromImage creates a page grid context for one or more images and supports cancellation. On error, callers must discard any non-nil context returned with the error.

func HasWatermarks added in v0.3.1

func HasWatermarks(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (ok bool, err error)

HasWatermarks checks rs for watermarks and supports cancellation.

func HasWatermarksFile added in v0.3.1

func HasWatermarksFile(c context.Context, inFile string, conf *model.Configuration) (ok bool, err error)

HasWatermarksFile checks inFile for watermarks and supports cancellation.

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.3.9

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.3.9

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

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

func ImageWatermark added in v0.3.4

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

ImageWatermark returns an image watermark configuration and supports cancellation.

func ImageWatermarkForReader added in v0.3.12

func ImageWatermarkForReader(c context.Context, rd io.Reader, desc string, onTop, update bool, u types.DisplayUnit) (*model.Watermark, error)

ImageWatermarkForReader returns an image watermark configuration for r and supports cancellation.

func Images added in v0.5.0

func Images(c context.Context, rs io.ReadSeeker, selectedPages []string, conf *model.Configuration) (ii []map[int]model.Image, err error)

Images returns all embedded images of rs and supports cancellation.

func Import added in v0.3.8

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

Import parses an Import command string into an internal structure.

func ImportBookmarks added in v0.5.0

func ImportBookmarks(c context.Context, rs io.ReadSeeker, rd io.Reader, w io.Writer, replace bool, conf *model.Configuration) (err error)

ImportBookmarks creates or replaces bookmarks in rs, writes the result to w and supports cancellation.

func ImportBookmarksFile added in v0.5.0

func ImportBookmarksFile(c context.Context, inFilePDF, inFileJSON, outFilePDF string, replace bool, conf *model.Configuration) (err error)

ImportBookmarksFile creates or replaces bookmarks in inFilePDF, writes the result to outFilePDF and supports cancellation.

func ImportCertificates added in v0.10.0

func ImportCertificates(c context.Context, inFiles []string) (ss []string, err error)

ImportCertificates validates and installs certificate files into the pdfcpu configuration directory while supporting cancellation. Existing destinations with the same derived name are replaced transactionally.

func ImportImages added in v0.1.20

func ImportImages(c context.Context, rs io.ReadSeeker, w io.Writer, imgs []io.Reader, imp *pdfcpu.Import, conf *model.Configuration) (err error)

ImportImages appends PDF pages containing images to rs, writes the result to w and supports cancellation. If rs == nil a new PDF file will be written to w.

func ImportImagesFile added in v0.2.3

func ImportImagesFile(c context.Context, imgFiles []string, outFile string, imp *pdfcpu.Import, conf *model.Configuration) (err error)

ImportImagesFile appends PDF pages containing images to outFile and supports cancellation. The output file is created if necessary.

Example

ExampleImportImagesFile demonstrates import images file.

// Convert an image into a single page of out.pdf which will be created if necessary.
// The page dimensions will match the image dimensions.
// If out.pdf already exists, append a new page.
// Use the default import configuration.
ImportImagesFile(context.Background(), []string{"image.png"}, "out.pdf", nil, nil)

// Import images by creating an A3 page for each image.
// Images are page centered with 1.0 relative scaling.
// Import an image as a new page of the existing out.pdf.
imp, _ := Import("form:A3, pos:c, s:1.0", types.POINTS)
ImportImagesFile(context.Background(), []string{"a1.png", "a2.jpg", "a3.tiff"}, "out.pdf", imp, nil)

func InsertPages added in v0.2.3

func InsertPages(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, before bool, pageConf *pdfcpu.PageConfiguration, conf *model.Configuration) (err error)

InsertPages inserts a blank page before or after every selected page, writes the result to w and supports cancellation.

func InsertPagesFile added in v0.2.3

func InsertPagesFile(c context.Context, inFile, outFile string, selectedPages []string, before bool, pageConf *pdfcpu.PageConfiguration, conf *model.Configuration) (err error)

InsertPagesFile inserts a blank page before or after every selected page, writes the result to outFile and supports cancellation.

Example

ExampleInsertPagesFile demonstrates insert pages file.

// Insert a blank page into in.pdf before page #3.
InsertPagesFile(context.Background(), "in.pdf", "", []string{"3"}, true, nil, nil)

// Insert a blank page into in.pdf after every page.
InsertPagesFile(context.Background(), "in.pdf", "", nil, false, nil, nil)

func InspectCertificates added in v0.11.0

func InspectCertificates(c context.Context, inFiles []string) (ss []string, err error)

InspectCertificates loads and inspects certificates from inFiles and supports cancellation.

func InstallFonts added in v0.3.1

func InstallFonts(c context.Context, fileNames []string) error

InstallFonts transactionally installs true type fonts and supports cancellation.

func Keywords added in v0.5.0

func Keywords(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (ss []string, err error)

Keywords returns the keywords of rs's info dict and supports cancellation.

func ListBookmarks added in v0.14.0

func ListBookmarks(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (ss []string, err error)

ListBookmarks returns a formatted list of rs's bookmarks and supports cancellation.

func ListBookmarksFile added in v0.14.0

func ListBookmarksFile(c context.Context, inFile string, conf *model.Configuration) (ss []string, err error)

ListBookmarksFile returns a formatted list of inFile's bookmarks and supports cancellation.

func ListBoxes added in v0.3.8

func ListBoxes(c context.Context, rs io.ReadSeeker, selectedPages []string, pb *model.PageBoundaries, conf *model.Configuration) (ss []string, err error)

ListBoxes returns formatted page boundaries for selected pages of rs and supports cancellation.

func ListBoxesFile added in v0.3.8

func ListBoxesFile(c context.Context, inFile string, selectedPages []string, pb *model.PageBoundaries, conf *model.Configuration) (ss []string, err error)

ListBoxesFile returns formatted page boundaries for selected pages of inFile and supports cancellation.

func ListCertificates added in v0.14.0

func ListCertificates(c context.Context, json bool) (ss []string, err error)

ListCertificates returns installed certificates and supports cancellation.

func ListFonts added in v0.3.1

func ListFonts(c context.Context) ([]string, error)

ListFonts returns a list of supported fonts and supports cancellation.

func ListFormFields added in v0.4.0

func ListFormFields(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (fields []string, err error)

ListFormFields returns a rendered list of all form fields in rs and supports cancellation.

func ListImages added in v0.3.12

func ListImages(c context.Context, rs io.ReadSeeker, selectedPages []string, conf *model.Configuration) (ss []string, err error)

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

func ListPageLayout added in v0.6.0

func ListPageLayout(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (ss []string, err error)

ListPageLayout lists rs's page layout and supports cancellation.

func ListPageLayoutFile added in v0.6.0

func ListPageLayoutFile(c context.Context, inFile string, conf *model.Configuration) (ss []string, err error)

ListPageLayoutFile lists inFile's page layout and supports cancellation.

func ListPageMode added in v0.6.0

func ListPageMode(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (ss []string, err error)

ListPageMode lists rs's page mode and supports cancellation.

func ListPageModeFile added in v0.6.0

func ListPageModeFile(c context.Context, inFile string, conf *model.Configuration) (ss []string, err error)

ListPageModeFile lists inFile's page mode and supports cancellation.

func ListViewerPreferences added in v0.6.0

func ListViewerPreferences(c context.Context, rs io.ReadSeeker, all bool, conf *model.Configuration) (ss []string, err error)

ListViewerPreferences returns rs's viewer preferences and supports cancellation.

func ListViewerPreferencesFile added in v0.6.0

func ListViewerPreferencesFile(c context.Context, inFile string, all, json bool, conf *model.Configuration) (ss []string, err error)

ListViewerPreferencesFile lists inFile's viewer preferences and supports cancellation.

func ListViewerPreferencesFileJSON added in v0.6.0

func ListViewerPreferencesFileJSON(c context.Context, inFile string, all bool, conf *model.Configuration) (ss []string, err error)

ListViewerPreferencesFileJSON lists inFile's viewer preferences in JSON and supports cancellation.

func ListViewerPreferencesJSON added in v0.14.0

func ListViewerPreferencesJSON(c context.Context, rs io.ReadSeeker, all bool, conf *model.Configuration) ([]string, error)

ListViewerPreferencesJSON returns rs's viewer preferences in JSON and supports cancellation.

func LoadConfiguration added in v0.3.7

func LoadConfiguration(options ConfigurationOptions) (*model.Configuration, error)

LoadConfiguration loads an independent configuration using options.

func LockFormFields added in v0.4.0

func LockFormFields(c context.Context, rs io.ReadSeeker, w io.Writer, fieldIDsOrNames []string, conf *model.Configuration) (err error)

LockFormFields turns form fields in rs into read-only, writes the result to w and supports cancellation.

func LockFormFieldsFile added in v0.4.0

func LockFormFieldsFile(c context.Context, inFile, outFile string, fieldIDsOrNames []string, conf *model.Configuration) error

LockFormFieldsFile turns form fields of inFile into read-only, writes the result to outFile and supports cancellation.

func Merge

func Merge(c context.Context, destFile string, inFiles []string, w io.Writer, conf *model.Configuration, dividerPage bool) (err error)

Merge concatenates inFiles and supports cancellation. if destFile is supplied it appends the result to destfile (=MERGEAPPEND) if no destFile supplied it writes the result to the first entry of inFiles (=MERGECREATE).

func MergeAppendFile added in v0.3.3

func MergeAppendFile(c context.Context, inFiles []string, outFile string, dividerPage bool, conf *model.Configuration) (err error)

MergeAppendFile appends inFiles to outFile and supports cancellation.

Example

ExampleMergeAppendFile demonstrates merge append file.

// Merge inFiles by concatenation in the order specified and write the result to out.pdf.
// If out.pdf already exists it will be preserved and serves as the beginning of the merge result.
inFiles := []string{"in1.pdf", "in2.pdf"}
MergeAppendFile(context.Background(), inFiles, "out.pdf", false, nil)

func MergeCreateFile added in v0.3.3

func MergeCreateFile(c context.Context, inFiles []string, outFile string, dividerPage bool, conf *model.Configuration) (err error)

MergeCreateFile merges inFiles, writes the result to outFile and supports cancellation.

Example

ExampleMergeCreateFile demonstrates merge create file.

// Merge inFiles by concatenation in the order specified and write the result to out.pdf.
// out.pdf will be overwritten.
inFiles := []string{"in1.pdf", "in2.pdf"}
MergeCreateFile(context.Background(), inFiles, "out.pdf", false, nil)

func MergeCreateZip added in v0.6.0

func MergeCreateZip(c context.Context, rs1, rs2 io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

MergeCreateZip zips rs1 and rs2 into w and supports cancellation.

func MergeCreateZipFile added in v0.6.0

func MergeCreateZipFile(c context.Context, inFile1, inFile2, outFile string, conf *model.Configuration) (err error)

MergeCreateZipFile zips inFile1 and inFile2 into outFile and supports cancellation.

func MergeRaw added in v0.4.1

func MergeRaw(c context.Context, rsc []io.ReadSeeker, w io.Writer, dividerPage bool, conf *model.Configuration) (err error)

MergeRaw merges a sequence of PDF streams, writes the result to w and supports cancellation.

func MultiFillForm added in v0.4.0

func MultiFillForm(c context.Context, inFilePDF string, rd io.Reader, outDir, fileName string, format form.DataFormat, merge bool, conf *model.Configuration) error

MultiFillForm populates multiple instances of inFilePDF's form with data from rd, writes the result to outDir and supports cancellation.

func MultiFillFormFile added in v0.4.0

func MultiFillFormFile(c context.Context, inFilePDF, inFileData, outDir, outFilePDF string, merge bool, conf *model.Configuration) (err error)

MultiFillFormFile populates multiple instances of inFilePDF's form with data from inFileData and writes the result to outDir. The output file will be written to outFilePDF with incrementing numerical suffix unless the input JSON uses "filename" or the input CSV contains a @filename field. MultiFillFormFile supports cancellation.

func NDown added in v0.4.1

func NDown(c context.Context, rs io.ReadSeeker, outDir, fileName string, selectedPages []string, n int, cut *model.Cut, conf *model.Configuration) (err error)

NDown applies n & cutConf for selected pages of rs, writes results to outDir and supports cancellation. Each generated output is written atomically. Outputs completed before cancellation remain in outDir.

func NDownFile added in v0.4.1

func NDownFile(c context.Context, inFile, outDir, outFile string, selectedPages []string, n int, cut *model.Cut, conf *model.Configuration) (err error)

NDownFile applies n & cutConf for selected pages of inFile, writes results to outDir and supports cancellation. Each generated output is written atomically. Outputs completed before cancellation remain in outDir.

func NUp added in v0.1.21

func NUp(c context.Context, rs io.ReadSeeker, w io.Writer, imgFiles, selectedPages []string, nup *model.NUp, conf *model.Configuration) (err error)

NUp rearranges PDF pages or images into page grids, writes the result to w and supports cancellation. Either rs or imgFiles will be used.

func NUpFile added in v0.2.3

func NUpFile(c context.Context, inFiles []string, outFile string, selectedPages []string, nup *model.NUp, conf *model.Configuration) (err error)

NUpFile rearranges PDF pages or images into page grids, writes the result to outFile and supports cancellation.

Example

ExampleNUpFile demonstrates n up file.

// 4-Up in.pdf and write result to out.pdf.
nup, _ := PDFNUpConfig(4, "", nil)
inFiles := []string{"in.pdf"}
NUpFile(context.Background(), inFiles, "out.pdf", nil, nup, nil)

// 9-Up a sequence of images using format Tabloid w/o borders and no margins.
nup, _ = ImageNUpConfig(9, "f:Tabloid, b:off, margin:0", nil)
inFiles = []string{"in1.png", "in2.jpg", "in3.tiff"}
NUpFile(context.Background(), inFiles, "out.pdf", nil, nup, nil)

// TestGridFromPDF
nup, _ = PDFGridConfig(1, 3, "f:LegalL", nil)
inFiles = []string{"in.pdf"}
NUpFile(context.Background(), inFiles, "out.pdf", nil, nup, nil)

// TestGridFromImages
nup, _ = ImageGridConfig(4, 2, "d:500 500, m:20, b:off", nil)
inFiles = []string{"in1.png", "in2.jpg", "in3.tiff"}
NUpFile(context.Background(), inFiles, "out.pdf", nil, nup, nil)

func NUpFromImage added in v0.3.8

func NUpFromImage(c context.Context, conf *model.Configuration, imageFileNames []string, nup *model.NUp) (ctx *model.Context, err error)

NUpFromImage creates n-up pages from images and supports cancellation. On error, callers must discard any non-nil context returned with the error.

func NUpValues added in v0.14.0

func NUpValues() []int

NUpValues returns the supported n-up page counts per sheet.

func NUpValuesForBooklets added in v0.14.0

func NUpValuesForBooklets() []int

NUpValuesForBooklets returns the supported booklet page counts per sheet.

func Optimize

func Optimize(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration, options *ProgressOptions) (err error)

Optimize reads and optimizes a PDF stream, supports cancellation and reports optional semantic progress. A nil options pointer disables progress reporting. Supplied options are not modified.

func OptimizeContext added in v0.1.18

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

OptimizeContext optimizes ctx and supports cancellation.

func OptimizeFile added in v0.2.3

func OptimizeFile(c context.Context, inFile, outFile string, conf *model.Configuration, options *ProgressOptions) (err error)

OptimizeFile reads inFile, writes the optimized PDF to outFile and supports cancellation and optional progress reporting. An empty outFile or one equal to inFile replaces inFile. A nil options pointer disables progress reporting. Supplied options are not modified.

Example

ExampleOptimizeFile demonstrates optimize file.

conf := model.NewDefaultConfiguration()

// Set passwords for encrypted files.
conf.UserPW = "upw"
conf.OwnerPW = "opw"

// Configure end of line sequence for writing.
conf.Eol = types.EolLF

// Create an optimized version of in.pdf and write it to out.pdf.
OptimizeFile(context.Background(), "in.pdf", "out.pdf", conf, nil)

// Create an optimized version of inFile.
// If you want to modify the original file, pass an empty string for outFile.
// Use nil for a default configuration.
OptimizeFile(context.Background(), "in.pdf", "", nil, nil)

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.3.9

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

PDFGridConfig returns a grid configuration for PDF files.

func PDFInfo added in v0.5.0

func PDFInfo(c context.Context, rs io.ReadSeeker, fileName string, selectedPages []string, fonts bool, conf *model.Configuration) (info *pdfcpu.PDFInfo, err error)

PDFInfo returns information about rs and supports cancellation. PDFInfo always uses relaxed validation.

func PDFMultiWatermarkForReadSeeker added in v0.6.0

func PDFMultiWatermarkForReadSeeker(c context.Context, rs io.ReadSeeker, startPageNrSrc, startPageNrDest int, desc string, onTop, update bool, u types.DisplayUnit) (*model.Watermark, error)

PDFMultiWatermarkForReadSeeker returns a PDF watermark configuration and supports cancellation. Define a source PDF watermark/stamp sequence using rs from page startPageNrSrc thru the last page of rs. Apply this sequence to the destination PDF file starting at page startPageNrDest for selected pages.

func PDFNUpConfig added in v0.3.9

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

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

func PDFWatermark added in v0.3.4

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

PDFWatermark returns a PDF watermark configuration and supports cancellation.

func PDFWatermarkForReadSeeker added in v0.6.0

func PDFWatermarkForReadSeeker(c context.Context, rs io.ReadSeeker, pageNrSrc int, desc string, onTop, update bool, u types.DisplayUnit) (*model.Watermark, error)

PDFWatermarkForReadSeeker returns a PDF watermark configuration and supports cancellation. Apply watermark/stamp to destination file with pageNrSrc of rs for selected pages. If pageNr == 0 apply a multi watermark/stamp applying all src pages in ascending manner to destination pages.

func PageBoundaries added in v0.3.8

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

PageBoundaries parses a list of box definitions and assignments.

func PageBoundariesFromBoxList added in v0.3.8

func PageBoundariesFromBoxList(s string) (*model.PageBoundaries, error)

PageBoundariesFromBoxList parses a list of box types.

func PageCount added in v0.2.3

func PageCount(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (count int, err error)

PageCount returns rs's page count and supports cancellation.

func PageCountFile added in v0.3.1

func PageCountFile(c context.Context, inFile string) (count int, err error)

PageCountFile returns inFile's page count and supports cancellation.

func PageDims added in v0.2.4

func PageDims(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (pd []types.Dim, err error)

PageDims returns media box dimensions for rs in ascending page order and supports cancellation.

func PageDimsFile added in v0.2.5

func PageDimsFile(c context.Context, inFile string) (pd []types.Dim, err error)

PageDimsFile returns media box dimensions for inFile in ascending page order and supports cancellation.

func PageLayout added in v0.6.0

func PageLayout(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (pl *model.PageLayout, err error)

PageLayout returns rs's page layout and supports cancellation.

func PageLayoutFile added in v0.6.0

func PageLayoutFile(c context.Context, inFile string, conf *model.Configuration) (pl *model.PageLayout, err error)

PageLayoutFile returns inFile's page layout and supports cancellation.

func PageMode added in v0.6.0

func PageMode(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (pm *model.PageMode, err error)

PageMode returns rs's page mode and supports cancellation.

func PageModeFile added in v0.6.0

func PageModeFile(c context.Context, inFile string, conf *model.Configuration) (pm *model.PageMode, err error)

PageModeFile returns inFile's page mode and supports cancellation.

func PagesForPageCollection added in v0.3.2

func PagesForPageCollection(pageCount int, pageSelection []string) ([]int, error)

PagesForPageCollection returns a slice of page numbers for a page collection. Any page number in any order any number of times allowed.

func PagesForPageRange added in v0.3.6

func PagesForPageRange(from, thru int) []int

PagesForPageRange returns a slice of page numbers for a valid page range. It returns nil for non-positive or descending ranges.

func PagesForPageSelection deprecated added in v0.3.2

func PagesForPageSelection(pageCount int, pageSelection []string, ensureAllForNone bool, _ bool) (types.IntSet, error)

PagesForPageSelection returns the selected page numbers.

Deprecated: Use PagesForSelection. The log argument is ignored.

func PagesForSelection added in v0.16.0

func PagesForSelection(pageCount int, pageSelection []string, ensureAllForNone bool) (types.IntSet, error)

PagesForSelection returns a set of page numbers for an ascending page sequence where each page number may appear only once.

func ParseGridDefinition added in v0.14.0

func ParseGridDefinition(rows, cols int, nup *model.NUp) error

ParseGridDefinition applies grid dimensions to a grid configuration.

func ParseNUpDetails added in v0.14.0

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

ParseNUpDetails parses an n-up command string into nup.

func ParseNUpGridDefinition deprecated added in v0.14.0

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

ParseNUpGridDefinition applies grid dimensions to a shared imposition configuration.

Deprecated: use ParseGridDefinition for grid command handling.

func ParseNUpValue added in v0.14.0

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

ParseNUpValue applies an n-up page count to nup.

func ParsePageSelection

func ParsePageSelection(s string) ([]string, error)

ParsePageSelection ensures a correct page selection expression.

func PatchFile added in v0.12.0

func PatchFile(c context.Context, fileName string, bb []byte, offset int64) error

PatchFile writes bb at offset in a staged copy, replaces fileName after the update succeeds and supports cancellation.

func Permissions added in v0.5.0

func Permissions(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (p int, err error)

Permissions returns user access permissions for rs and supports cancellation.

func PermissionsList added in v0.14.0

func PermissionsList(c context.Context, rs io.ReadSeeker, conf *model.Configuration) ([]string, error)

PermissionsList returns formatted user access permissions for rs and supports cancellation.

func Poster added in v0.4.1

func Poster(c context.Context, rs io.ReadSeeker, outDir, fileName string, selectedPages []string, cut *model.Cut, conf *model.Configuration) (err error)

Poster applies cut for selected pages of rs, writes poster tiles into outDir and supports cancellation. Each generated output is written atomically. Outputs completed before cancellation remain in outDir.

func PosterFile added in v0.4.1

func PosterFile(c context.Context, inFile, outDir, outFile string, selectedPages []string, cut *model.Cut, conf *model.Configuration) (err error)

PosterFile applies cut for selected pages of inFile, writes poster tiles into outDir and supports cancellation. Each generated output is written atomically. Outputs completed before cancellation remain in outDir.

func PrepareImportConfiguration added in v0.14.0

func PrepareImportConfiguration(imp *pdfcpu.Import) (*pdfcpu.Import, error)

PrepareImportConfiguration applies image import defaults and validates the result without performing I/O.

func Properties added in v0.5.0

func Properties(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (m map[string]string, err error)

Properties returns rs's properties as recorded in infoDict and supports cancellation.

func ReadAndValidate added in v0.7.0

func ReadAndValidate(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (*model.Context, error)

ReadAndValidate returns a validated model.Context and supports cancellation.

func ReadContext added in v0.1.18

func ReadContext(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (ctx *model.Context, err error)

ReadContext uses an io.ReadSeeker to build an internal PDF context and supports cancellation.

func ReadContextFile added in v0.2.3

func ReadContextFile(c context.Context, inFile string) (*model.Context, error)

ReadContextFile returns inFile's validated context and supports cancellation.

func ReadValidateAndOptimize added in v0.5.0

func ReadValidateAndOptimize(c context.Context, rs io.ReadSeeker, conf *model.Configuration, options *ProgressOptions) (ctx *model.Context, err error)

ReadValidateAndOptimize returns an optimized model.Context, supports cancellation and reports optional semantic progress. conf.Cmd is expected to be configured properly. A nil options pointer disables progress reporting. Supplied options are not modified.

func RemainingPagesForPageRemoval deprecated added in v0.7.0

func RemainingPagesForPageRemoval(pageCount int, pageSelection []string, _ bool) (types.IntSet, error)

RemainingPagesForPageRemoval returns the pages remaining after applying pageSelection.

Deprecated: Use RemainingPagesForRemoval. The log argument is ignored.

func RemainingPagesForRemoval added in v0.16.0

func RemainingPagesForRemoval(pageCount int, pageSelection []string) (types.IntSet, error)

RemainingPagesForRemoval returns the pages remaining after applying pageSelection.

func RemoveAnnotations added in v0.3.12

func RemoveAnnotations(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages, idsAndTypes []string, objNrs []int, conf *model.Configuration) (err error)

RemoveAnnotations removes annotations for selected pages by ID and object number from a PDF context read from rs, writes the result to w and supports cancellation.

func RemoveAnnotationsAsIncrement added in v0.3.12

func RemoveAnnotationsAsIncrement(c context.Context, rws io.ReadWriteSeeker, selectedPages, idsAndTypes []string, objNrs []int, conf *model.Configuration) (err error)

RemoveAnnotationsAsIncrement removes annotations for selected pages by IDs and object number from a PDF context read from rws, writes out a PDF increment and supports cancellation.

func RemoveAnnotationsFile added in v0.3.12

func RemoveAnnotationsFile(c context.Context, inFile, outFile string, selectedPages, idsAndTypes []string, objNrs []int, conf *model.Configuration, incr bool) (err error)

RemoveAnnotationsFile removes annotations for selected pages by ID and object number from a PDF context read from inFile, writes the result to outFile and supports cancellation.

func RemoveAttachments

func RemoveAttachments(c context.Context, rs io.ReadSeeker, w io.Writer, files []string, conf *model.Configuration) (err error)

RemoveAttachments deletes embedded files from a PDF context read from rs, writes the result to w and supports cancellation.

func RemoveAttachmentsFile added in v0.2.3

func RemoveAttachmentsFile(c context.Context, inFile, outFile string, files []string, conf *model.Configuration) (err error)

RemoveAttachmentsFile deletes embedded files from a PDF context read from inFile, writes the result to outFile and supports cancellation.

Example

ExampleRemoveAttachmentsFile demonstrates remove attachments file.

// Remove 1 attachment from in.pdf.
RemoveAttachmentsFile(context.Background(), "in.pdf", "", []string{"img.jpg"}, nil)

// Remove all attachments from in.pdf
RemoveAttachmentsFile(context.Background(), "in.pdf", "", nil, nil)

func RemoveBookmarks added in v0.5.0

func RemoveBookmarks(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

RemoveBookmarks deletes bookmarks from rs, writes the result to w and supports cancellation.

func RemoveBookmarksFile added in v0.5.0

func RemoveBookmarksFile(c context.Context, inFile, outFile string, conf *model.Configuration) (err error)

RemoveBookmarksFile deletes bookmarks from inFile, writes the result to outFile and supports cancellation.

func RemoveBoxes added in v0.3.8

func RemoveBoxes(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, pb *model.PageBoundaries, conf *model.Configuration) (err error)

RemoveBoxes removes page boundaries for selected pages of rs, writes the result to w and supports cancellation.

func RemoveBoxesFile added in v0.3.8

func RemoveBoxesFile(c context.Context, inFile, outFile string, selectedPages []string, pb *model.PageBoundaries, conf *model.Configuration) (err error)

RemoveBoxesFile removes page boundaries for selected pages of inFile, writes the result to outFile and supports cancellation.

func RemoveFormFields added in v0.4.0

func RemoveFormFields(c context.Context, rs io.ReadSeeker, w io.Writer, fieldIDsOrNames []string, conf *model.Configuration) (err error)

RemoveFormFields deletes form fields in rs, writes the result to w and supports cancellation.

func RemoveFormFieldsFile added in v0.4.0

func RemoveFormFieldsFile(c context.Context, inFile, outFile string, fieldIDsOrNames []string, conf *model.Configuration) error

RemoveFormFieldsFile deletes form fields in inFile, writes the result to outFile and supports cancellation.

func RemoveKeywords added in v0.3.2

func RemoveKeywords(c context.Context, rs io.ReadSeeker, w io.Writer, keywords []string, conf *model.Configuration) (err error)

RemoveKeywords deletes keywords from rs's infodict, writes the result to w and supports cancellation.

func RemoveKeywordsFile added in v0.3.2

func RemoveKeywordsFile(c context.Context, inFile, outFile string, keywords []string, conf *model.Configuration) (err error)

RemoveKeywordsFile deletes keywords from inFile's infodict, writes the result to outFile and supports cancellation.

func RemovePages added in v0.2.3

func RemovePages(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, conf *model.Configuration) (err error)

RemovePages removes selected pages from rs, writes the result to w and supports cancellation.

func RemovePagesFile added in v0.2.3

func RemovePagesFile(c context.Context, inFile, outFile string, selectedPages []string, conf *model.Configuration) (err error)

RemovePagesFile removes selected pages from inFile, writes the result to outFile and supports cancellation.

Example

ExampleRemovePagesFile demonstrates remove pages file.

// Remove pages 2 and 8 of in.pdf.
RemovePagesFile(context.Background(), "in.pdf", "", []string{"2", "8"}, nil)

// Remove first 2 pages of in.pdf.
RemovePagesFile(context.Background(), "in.pdf", "", []string{"-2"}, nil)

// Remove all pages >= 10 of in.pdf.
RemovePagesFile(context.Background(), "in.pdf", "", []string{"10-"}, nil)

func RemoveProperties added in v0.3.2

func RemoveProperties(c context.Context, rs io.ReadSeeker, w io.Writer, properties []string, conf *model.Configuration) (err error)

RemoveProperties deletes properties from rs's infodict, writes the result to w and supports cancellation.

func RemovePropertiesFile added in v0.3.2

func RemovePropertiesFile(c context.Context, inFile, outFile string, properties []string, conf *model.Configuration) (err error)

RemovePropertiesFile deletes properties from inFile's infodict, writes the result to outFile and supports cancellation.

func RemoveSignatures added in v0.12.0

func RemoveSignatures(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

RemoveSignatures removes all digital signatures from rs, writes to w and supports cancellation.

func RemoveSignaturesFile added in v0.12.0

func RemoveSignaturesFile(c context.Context, inFile, outFile string, conf *model.Configuration) (err error)

RemoveSignaturesFile removes all digital signatures from inFile, writes to outFile if provided, otherwise overwrites inFile, and supports cancellation.

func RemoveWatermarks added in v0.2.5

func RemoveWatermarks(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, conf *model.Configuration) (err error)

RemoveWatermarks removes watermarks from all selected pages in rs, writes the result to w and supports cancellation.

func RemoveWatermarksFile added in v0.2.5

func RemoveWatermarksFile(c context.Context, inFile, outFile string, selectedPages []string, conf *model.Configuration) (err error)

RemoveWatermarksFile removes watermarks from all selected pages of inFile, writes the result to outFile and supports cancellation.

Example

ExampleRemoveWatermarksFile demonstrates remove watermarks file.

// Add a "Demo" stamp to all pages of in.pdf along the diagonal running from lower left to upper right.
onTop := true
update := false
wm, _ := TextWatermark(context.Background(), "Demo", "", onTop, update, types.POINTS, nil)
AddWatermarksFile(context.Background(), "in.pdf", "", nil, wm, nil)

// Update stamp for correction:
update = true
wm, _ = TextWatermark(context.Background(), "Confidential", "", onTop, update, types.POINTS, nil)
AddWatermarksFile(context.Background(), "in.pdf", "", nil, wm, nil)

// Add another watermark on top of page 1
wm, _ = TextWatermark(context.Background(), "Footer stamp", "c:.5 1 1, pos:bc", onTop, update, types.POINTS, nil)
AddWatermarksFile(context.Background(), "in.pdf", "", nil, wm, nil)

// Remove watermark on page 1
RemoveWatermarksFile(context.Background(), "in.pdf", "", []string{"1"}, nil)

// Remove all watermarks
RemoveWatermarksFile(context.Background(), "in.pdf", "", nil, nil)

func ResetConfigurationWithOptions added in v0.16.0

func ResetConfigurationWithOptions(options ConfigurationOptions) (*model.Configuration, error)

ResetConfigurationWithOptions replaces config.yml at the selected root with the built-in configuration.

func ResetFormFields added in v0.4.0

func ResetFormFields(c context.Context, rs io.ReadSeeker, w io.Writer, fieldIDsOrNames []string, conf *model.Configuration) (err error)

ResetFormFields resets form fields of rs, writes the result to w and supports cancellation.

func ResetFormFieldsFile added in v0.4.0

func ResetFormFieldsFile(c context.Context, inFile, outFile string, fieldIDsOrNames []string, conf *model.Configuration) error

ResetFormFieldsFile resets form fields of inFile, writes the result to outFile and supports cancellation.

func ResetPageLayout added in v0.6.0

func ResetPageLayout(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

ResetPageLayout resets rs's page layout, writes the result to w and supports cancellation. It is idempotent and writes output even when rs has no page layout.

func ResetPageLayoutFile added in v0.6.0

func ResetPageLayoutFile(c context.Context, inFile, outFile string, conf *model.Configuration) (err error)

ResetPageLayoutFile resets inFile's page layout, writes the result to outFile and supports cancellation. It is idempotent and writes output even when inFile has no page layout.

func ResetPageMode added in v0.6.0

func ResetPageMode(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

ResetPageMode resets rs's page mode, writes the result to w and supports cancellation. It is idempotent and writes output even when rs has no page mode.

func ResetPageModeFile added in v0.6.0

func ResetPageModeFile(c context.Context, inFile, outFile string, conf *model.Configuration) (err error)

ResetPageModeFile resets inFile's page mode, writes the result to outFile and supports cancellation. It is idempotent and writes output even when inFile has no page mode.

func ResetViewerPreferences added in v0.6.0

func ResetViewerPreferences(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

ResetViewerPreferences resets rs's viewer preferences and writes the result to w. If rs has no viewer preferences, it still writes the unchanged PDF and returns success.

func ResetViewerPreferencesFile added in v0.6.0

func ResetViewerPreferencesFile(c context.Context, inFile, outFile string, conf *model.Configuration) (err error)

ResetViewerPreferencesFile resets inFile's viewer preferences and writes the result to outFile. If inFile has no viewer preferences, it still writes the unchanged PDF and returns success.

func Resize added in v0.4.0

func Resize(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, resize *model.Resize, conf *model.Configuration) (err error)

Resize applies resizeConf for selected pages of rs, writes the result to w and supports cancellation.

func ResizeFile added in v0.4.0

func ResizeFile(c context.Context, inFile, outFile string, selectedPages []string, resize *model.Resize, conf *model.Configuration) (err error)

ResizeFile applies resizeConf for selected pages of inFile, writes the result to outFile and supports cancellation.

func Rotate added in v0.1.20

func Rotate(c context.Context, rs io.ReadSeeker, w io.Writer, rotation int, selectedPages []string, conf *model.Configuration) (err error)

Rotate rotates selected pages of rs clockwise, writes the result to w and supports cancellation.

func RotateFile added in v0.2.3

func RotateFile(c context.Context, inFile, outFile string, rotation int, selectedPages []string, conf *model.Configuration) (err error)

RotateFile rotates selected pages of inFile clockwise, writes the result to outFile and supports cancellation.

Example

ExampleRotateFile demonstrates rotate file.

// Rotate all pages of in.pdf, clockwise by 90 degrees and write the result to out.pdf.
RotateFile(context.Background(), "in.pdf", "out.pdf", 90, nil, nil)

// Rotate the first page of in.pdf by 180 degrees.
// If you want to modify the original file, pass an empty string as outFile.
RotateFile(context.Background(), "in.pdf", "", 180, []string{"1"}, nil)

func SetPageLayout added in v0.6.0

func SetPageLayout(c context.Context, rs io.ReadSeeker, w io.Writer, val model.PageLayout, conf *model.Configuration) (err error)

SetPageLayout sets rs's page layout, writes the result to w and supports cancellation.

func SetPageLayoutFile added in v0.6.0

func SetPageLayoutFile(c context.Context, inFile, outFile string, val model.PageLayout, conf *model.Configuration) (err error)

SetPageLayoutFile sets inFile's page layout, writes the result to outFile and supports cancellation.

func SetPageMode added in v0.6.0

func SetPageMode(c context.Context, rs io.ReadSeeker, w io.Writer, val model.PageMode, conf *model.Configuration) (err error)

SetPageMode sets rs's page mode, writes the result to w and supports cancellation.

func SetPageModeFile added in v0.6.0

func SetPageModeFile(c context.Context, inFile, outFile string, val model.PageMode, conf *model.Configuration) (err error)

SetPageModeFile sets inFile's page mode, writes the result to outFile and supports cancellation.

func SetPermissions added in v0.2.3

func SetPermissions(c context.Context, rs io.ReadSeeker, w io.Writer, conf *model.Configuration) (err error)

SetPermissions sets user access permissions and supports cancellation. inFile has to be encrypted. A configuration containing the current passwords is required.

func SetPermissionsFile added in v0.2.3

func SetPermissionsFile(c context.Context, inFile, outFile string, conf *model.Configuration) (err error)

SetPermissionsFile sets inFile's user access permissions and supports cancellation. inFile has to be encrypted. A configuration containing the current passwords is required.

Example

ExampleSetPermissionsFile demonstrates set permissions file.

// Setting all permissions for the AES-256 encrypted in.pdf.
conf := model.NewAESConfiguration("upw", "opw", 256)
conf.Permissions = model.PermissionsAll
SetPermissionsFile(context.Background(), "in.pdf", "", conf)

// Restricting permissions for the AES-256 encrypted in.pdf.
conf = model.NewAESConfiguration("upw", "opw", 256)
conf.Permissions = model.PermissionsNone
SetPermissionsFile(context.Background(), "in.pdf", "", conf)

func SetViewerPreferences added in v0.6.0

func SetViewerPreferences(c context.Context, rs io.ReadSeeker, w io.Writer, vp model.ViewerPreferences, conf *model.Configuration) (err error)

SetViewerPreferences sets rs's viewer preferences, writes the result to w and supports cancellation.

func SetViewerPreferencesFile added in v0.6.0

func SetViewerPreferencesFile(c context.Context, inFile, outFile string, vp model.ViewerPreferences, conf *model.Configuration) (err error)

SetViewerPreferencesFile sets inFile's viewer preferences, writes the result to outFile and supports cancellation.

func SetViewerPreferencesFileFromJSONBytes added in v0.6.0

func SetViewerPreferencesFileFromJSONBytes(c context.Context, inFile, outFile string, jsonBytes []byte, conf *model.Configuration) (err error)

SetViewerPreferencesFileFromJSONBytes sets inFile's viewer preferences corresponding to jsonBytes, writes the result to outFile and supports cancellation.

func SetViewerPreferencesFileFromJSONFile added in v0.6.0

func SetViewerPreferencesFileFromJSONFile(c context.Context, inFilePDF, outFilePDF, inFileJSON string, conf *model.Configuration) error

SetViewerPreferencesFileFromJSONFile sets inFile's viewer preferences corresponding to inFileJSON, writes the result to outFile and supports cancellation.

func SetViewerPreferencesFromJSONBytes added in v0.6.0

func SetViewerPreferencesFromJSONBytes(c context.Context, rs io.ReadSeeker, w io.Writer, jsonBytes []byte, conf *model.Configuration) error

SetViewerPreferencesFromJSONBytes sets rs's viewer preferences corresponding to jsonBytes, writes the result to w and supports cancellation.

func SetViewerPreferencesFromJSONReader added in v0.6.0

func SetViewerPreferencesFromJSONReader(c context.Context, rs io.ReadSeeker, w io.Writer, rd io.Reader, conf *model.Configuration) error

SetViewerPreferencesFromJSONReader sets rs's viewer preferences corresponding to rd, writes the result to w and supports cancellation.

func Split

func Split(c context.Context, rs io.ReadSeeker, outDir, fileName string, span int, conf *model.Configuration) (err error)

Split generates a sequence of PDF files in outDir and supports cancellation. Files completed before cancellation remain published.

func SplitByPageNr added in v0.6.0

func SplitByPageNr(c context.Context, rs io.ReadSeeker, outDir, fileName string, pageNrs []int, conf *model.Configuration) (err error)

SplitByPageNr splits rs before the specified page numbers and supports cancellation. Files completed before cancellation remain published.

func SplitByPageNrFile added in v0.6.0

func SplitByPageNrFile(c context.Context, inFile, outDir string, pageNrs []int, conf *model.Configuration) (err error)

SplitByPageNrFile splits inFile before the specified page numbers and supports cancellation. Files completed before cancellation remain published.

func SplitFile added in v0.2.3

func SplitFile(c context.Context, inFile, outDir string, span int, conf *model.Configuration) (err error)

SplitFile generates a sequence of PDF files in outDir and supports cancellation. Files completed before cancellation remain published.

Example

ExampleSplitFile demonstrates split file.

// Create single page PDFs for in.pdf in outDir using the default configuration.
SplitFile(context.Background(), "in.pdf", "outDir", 1, nil)

// Create dual page PDFs for in.pdf in outDir using the default configuration.
SplitFile(context.Background(), "in.pdf", "outDir", 2, nil)

// Create a sequence of PDFs representing bookmark sections.
SplitFile(context.Background(), "in.pdf", "outDir", 0, nil)

func TextWatermark added in v0.3.4

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

TextWatermark returns a text watermark configuration and supports cancellation.

func Trim

func Trim(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, conf *model.Configuration) (err error)

Trim generates a trimmed version of rs, writes the result to w and supports cancellation.

func TrimFile added in v0.2.3

func TrimFile(c context.Context, inFile, outFile string, selectedPages []string, conf *model.Configuration) (err error)

TrimFile generates a trimmed version of inFile, writes the result to outFile and supports cancellation.

Example

ExampleTrimFile demonstrates trim file.

// Create a trimmed version of in.pdf containing odd page numbers only.
TrimFile(context.Background(), "in.pdf", "outFile", []string{"odd"}, nil)

// Create a trimmed version of in.pdf containing the first two pages only.
// If you want to modify the original file, pass an empty string for outFile.
TrimFile(context.Background(), "in.pdf", "", []string{"1-2"}, nil)

func UnlockFormFields added in v0.4.0

func UnlockFormFields(c context.Context, rs io.ReadSeeker, w io.Writer, fieldIDsOrNames []string, conf *model.Configuration) (err error)

UnlockFormFields makes form fields in rs writable, writes the result to w and supports cancellation.

func UnlockFormFieldsFile added in v0.4.0

func UnlockFormFieldsFile(c context.Context, inFile, outFile string, fieldIDsOrNames []string, conf *model.Configuration) error

UnlockFormFieldsFile makes form fields of inFile writable, writes the result to outFile and supports cancellation.

func UpdateImageWatermarksFile added in v0.3.4

func UpdateImageWatermarksFile(c context.Context, inFile, outFile string, selectedPages []string, onTop bool, fileName, desc string, conf *model.Configuration) error

UpdateImageWatermarksFile updates image stamps/watermarks for all selected pages of inFile, writes the result to outFile and supports cancellation.

func UpdateImages added in v0.9.0

func UpdateImages(c context.Context, rs io.ReadSeeker, rd io.Reader, w io.Writer, objNr, pageNr int, id string, conf *model.Configuration) (err error)

UpdateImages replaces the XObject identified by objNr or (pageNr and resourceId) and supports cancellation.

func UpdateImagesFile added in v0.9.0

func UpdateImagesFile(c context.Context, inFile, imageFile, outFile string, objNr, pageNr int, id string, conf *model.Configuration) (err error)

UpdateImagesFile replaces the XObject identified by objNr or (pageNr and resourceId) and supports cancellation.

func UpdatePDFWatermarksFile added in v0.3.4

func UpdatePDFWatermarksFile(c context.Context, inFile, outFile string, selectedPages []string, onTop bool, fileName, desc string, conf *model.Configuration) error

UpdatePDFWatermarksFile updates PDF stamps/watermarks for all selected pages of inFile, writes the result to outFile and supports cancellation.

func UpdateTextWatermarksFile added in v0.3.4

func UpdateTextWatermarksFile(c context.Context, inFile, outFile string, selectedPages []string, onTop bool, text, desc string, conf *model.Configuration) error

UpdateTextWatermarksFile updates text stamps/watermarks for all selected pages of inFile, writes the result to outFile and supports cancellation.

func Validate

func Validate(c context.Context, rs io.ReadSeeker, conf *model.Configuration, options *ProgressOptions) error

Validate validates a PDF stream, supports cancellation and reports optional semantic progress. A nil options pointer disables progress reporting.

func ValidateContext added in v0.1.18

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

ValidateContext validates ctx and supports cancellation.

func ValidateContextWithReport added in v0.16.0

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

ValidateContextWithReport validates ctx and returns its accepted validation divergences.

func ValidateFile added in v0.2.3

func ValidateFile(c context.Context, inFile string, conf *model.Configuration, options *ProgressOptions) error

ValidateFile validates inFile, supports cancellation and reports optional semantic progress. A nil options pointer disables progress reporting. Supplied options are not modified.

Example

ExampleValidateFile demonstrates validate file.

// Use the default configuration to validate in.pdf.
ValidateFile(context.Background(), "in.pdf", nil, nil)

func ValidateFileWithReport added in v0.16.0

func ValidateFileWithReport(c context.Context, inFile string, conf *model.Configuration, options *ProgressOptions) (report model.ValidationReport, err error)

ValidateFileWithReport validates inFile and returns its accepted validation divergences.

func ValidateFiles added in v0.3.13

func ValidateFiles(c context.Context, inFiles []string, conf *model.Configuration, options *ProgressOptions) error

ValidateFiles validates inFiles, supports cancellation and reports optional semantic progress. A nil options pointer disables progress reporting. Supplied options are not modified.

func ValidateImportImagesOutput added in v0.14.0

func ValidateImportImagesOutput(imgFiles []string, outFile string) error

ValidateImportImagesOutput validates that outFile does not alias a file-based image input. A "-" image input denotes stdin and is ignored.

func ValidateSignatures added in v0.10.0

func ValidateSignatures(c context.Context, inFile string, all bool, conf *model.Configuration) (results []*model.SignatureValidationResult, err error)

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

func ValidateSignaturesFile added in v0.10.0

func ValidateSignaturesFile(c context.Context, inFile string, all, full bool, conf *model.Configuration) ([]string, error)

ValidateSignaturesFile presents observed signature, certificate, timestamp and revocation evidence together with a local assessment and supports cancellation. all: processes all signatures meaning not only the authoritative/certified signature.. full: detailed output including certificate paths, observed evidence and problems encountered.

func ValidateSignaturesRaw added in v0.14.0

func ValidateSignaturesRaw(c context.Context, rs ReadSeekerAt, all bool, conf *model.Configuration) (results []*model.SignatureValidationResult, err error)

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

func ValidateUpdateImagesOutput added in v0.14.0

func ValidateUpdateImagesOutput(imageFile, outFile string) error

ValidateUpdateImagesOutput ensures outFile does not alias imageFile.

func ValidateWithReport added in v0.16.0

func ValidateWithReport(c context.Context, rs io.ReadSeeker, conf *model.Configuration, options *ProgressOptions) (report model.ValidationReport, err error)

ValidateWithReport validates a PDF stream and returns its accepted validation divergences.

func ViewerPreferences added in v0.6.0

func ViewerPreferences(c context.Context, rs io.ReadSeeker, conf *model.Configuration) (vp *model.ViewerPreferences, v *model.Version, err error)

ViewerPreferences returns rs's viewer preferences and supports cancellation.

func ViewerPreferencesFile added in v0.6.0

func ViewerPreferencesFile(c context.Context, inFile string, all bool, conf *model.Configuration) (vp *model.ViewerPreferences, err error)

ViewerPreferencesFile returns inFile's viewer preferences and supports cancellation.

func WatermarkContext added in v0.3.1

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

WatermarkContext applies wm for selected pages to ctx and supports cancellation. On failure, ctx may contain partial changes and callers must discard it.

func Write

func Write(c context.Context, ctx *model.Context, w io.Writer, conf *model.Configuration) error

Write writes ctx using w and supports cancellation.

func WriteContentToDisk added in v0.13.0

func WriteContentToDisk(c context.Context, outDir, fnBase string) func(io.Reader, int) error

WriteContentToDisk returns a closure for writing content transactionally to disk with cancellation.

func WriteContext added in v0.1.18

func WriteContext(c context.Context, ctx *model.Context, w io.Writer) (err error)

WriteContext writes ctx to w and supports cancellation.

func WriteContextFile added in v0.3.1

func WriteContextFile(c context.Context, ctx *model.Context, outFile string) (err error)

WriteContextFile writes ctx to outFile and supports cancellation.

func WriteFontToDisk added in v0.13.0

func WriteFontToDisk(c context.Context, outDir, fnBase string) func(pdfcpu.Font) error

WriteFontToDisk returns a closure for writing a font file transactionally to disk with cancellation.

func WriteImageToDisk added in v0.13.0

func WriteImageToDisk(c context.Context, outDir, fileName string) func(model.Image, bool, int) error

WriteImageToDisk returns a closure for writing an image transactionally to disk with cancellation.

func WriteIncr added in v0.7.0

func WriteIncr(c context.Context, ctx *model.Context, rws io.ReadWriteSeeker, conf *model.Configuration) error

WriteIncr writes ctx as increment using rws and supports cancellation.

func WriteIncrement added in v0.3.12

func WriteIncrement(c context.Context, ctx *model.Context, w io.Writer) (err error)

WriteIncrement writes a PDF increment for ctx to w and supports cancellation.

func WriteMetadataToDisk added in v0.13.0

func WriteMetadataToDisk(c context.Context, outDir, fnBase string) func(pdfcpu.Metadata) error

WriteMetadataToDisk returns a closure for writing metadata transactionally to disk with cancellation.

func WritePageToDisk added in v0.13.0

func WritePageToDisk(c context.Context, outDir, fnBase string) func(io.Reader, int) error

WritePageToDisk returns a closure for writing a single page PDF transactionally with cancellation.

func Zoom added in v0.7.0

func Zoom(c context.Context, rs io.ReadSeeker, w io.Writer, selectedPages []string, zoom *model.Zoom, conf *model.Configuration) (err error)

Zoom applies zoom for selected pages of rs, writes the result to w and supports cancellation.

func ZoomFile added in v0.7.0

func ZoomFile(c context.Context, inFile, outFile string, selectedPages []string, zoom *model.Zoom, conf *model.Configuration) (err error)

ZoomFile applies zoom for selected pages of inFile, writes the result to outFile and supports cancellation.

Types

type ConfigurationInitialization added in v0.16.0

type ConfigurationInitialization struct {
	// Configuration is the loaded effective configuration.
	Configuration *model.Configuration

	// Created is true when config.yml was created by this initialization.
	Created bool
}

ConfigurationInitialization reports the result of initializing a configuration tree.

func InitializeConfigurationWithOptions added in v0.16.0

func InitializeConfigurationWithOptions(options ConfigurationOptions) (*ConfigurationInitialization, error)

InitializeConfigurationWithOptions loads or initializes the selected configuration tree and reports whether config.yml was created.

type ConfigurationInspection added in v0.16.0

type ConfigurationInspection struct {
	// Mode is the selected configuration mode.
	Mode ConfigurationMode `json:"mode"`

	// Source identifies how Root was selected.
	Source ConfigurationSource `json:"source"`

	// Default is true when the operating system's default root was selected.
	Default bool `json:"default"`

	// Stateless is true when built-in configuration is in use without filesystem resources.
	Stateless bool `json:"stateless"`

	// WriteCapable is true when the selected mode permits configuration writes.
	WriteCapable bool `json:"writeCapable"`

	// Root describes the selected configuration root.
	Root ConfigurationPathInspection `json:"root"`

	// Paths contains resolved configuration resource paths.
	Paths ConfigurationPathsInspection `json:"paths"`

	// Schema describes detected and supported configuration schemas.
	Schema ConfigurationSchemaInspection `json:"schema"`

	// Network contains configured outbound-network settings.
	Network ConfigurationNetworkInspection `json:"network"`

	// Limits contains configured input-driven resource limits.
	Limits ConfigurationLimitsInspection `json:"limits"`
}

ConfigurationInspection describes selected configuration and filesystem state without exposing secret-bearing operation state.

func InspectConfiguration added in v0.16.0

func InspectConfiguration(options ConfigurationOptions) (*ConfigurationInspection, error)

InspectConfiguration reports selected configuration and filesystem state without modifying either. Automatic mode reads existing state without initializing missing resources.

type ConfigurationLimitsInspection added in v0.16.0

type ConfigurationLimitsInspection struct {
	// MaxInputBytes limits each PDF input and stdin spool. Zero means unlimited.
	MaxInputBytes int64 `json:"maxInputBytes"`

	// MaxObjectBytes limits an indirect-object buffer, excluding stream payloads.
	MaxObjectBytes int64 `json:"maxObjectBytes"`

	// MaxStreamBytes limits encoded stream bytes read from a PDF.
	MaxStreamBytes int64 `json:"maxStreamBytes"`

	// MaxDecodeBytes limits decoded stream bytes produced by filters.
	MaxDecodeBytes int64 `json:"maxDecodeBytes"`

	// MaxImagePixels limits decoded or rendered image dimensions.
	MaxImagePixels int64 `json:"maxImagePixels"`

	// MaxImageBytes limits decoded or rendered image buffer sizes.
	MaxImageBytes int64 `json:"maxImageBytes"`

	// MaxObjectCount limits the cross-reference object number range.
	MaxObjectCount int `json:"maxObjectCount"`

	// MaxObjectStreamCount limits object stream entry counts.
	MaxObjectStreamCount int `json:"maxObjectStreamCount"`

	// MaxObjectStreamFirst limits object stream prolog bytes.
	MaxObjectStreamFirst int64 `json:"maxObjectStreamFirst"`

	// MaxXRefEntries limits entries in a cross-reference section.
	MaxXRefEntries int `json:"maxXRefEntries"`

	// MaxRecursionDepth limits recursive parsing and object graph traversal.
	MaxRecursionDepth int `json:"maxRecursionDepth"`
}

ConfigurationLimitsInspection contains configured input-driven resource limits.

type ConfigurationMode added in v0.16.0

type ConfigurationMode int

ConfigurationMode controls configuration discovery and filesystem access.

const (
	// ConfigurationModeAuto discovers, reads and initializes configuration state when required.
	ConfigurationModeAuto ConfigurationMode = iota

	// ConfigurationModeReadOnly reads an existing configuration tree without modifying it.
	ConfigurationModeReadOnly

	// ConfigurationModeStateless uses built-in configuration without accessing configuration state on disk.
	ConfigurationModeStateless
)

func (ConfigurationMode) MarshalText added in v0.16.0

func (mode ConfigurationMode) MarshalText() ([]byte, error)

MarshalText returns the stable text representation for mode.

func (ConfigurationMode) String added in v0.16.0

func (mode ConfigurationMode) String() string

String returns the stable name for mode.

type ConfigurationNetworkInspection added in v0.16.0

type ConfigurationNetworkInspection struct {
	// Offline disables outbound network activity.
	Offline bool `json:"offline"`

	// HTTPTimeoutSeconds is the general HTTP timeout in seconds.
	HTTPTimeoutSeconds int `json:"httpTimeoutSeconds"`

	// CRLTimeoutSeconds is the certificate-revocation-list timeout in seconds.
	CRLTimeoutSeconds int `json:"crlTimeoutSeconds"`

	// OCSPTimeoutSeconds is the Online Certificate Status Protocol timeout in seconds.
	OCSPTimeoutSeconds int `json:"ocspTimeoutSeconds"`

	// PreferredRevocationChecker identifies the preferred certificate revocation mechanism.
	PreferredRevocationChecker string `json:"preferredRevocationChecker"`

	// AllowedRevocationHosts lists private hosts permitted for certificate revocation checks.
	AllowedRevocationHosts []string `json:"allowedRevocationHosts"`
}

ConfigurationNetworkInspection contains configured outbound-network settings.

type ConfigurationOptions added in v0.16.0

type ConfigurationOptions struct {
	// Root is the parent directory of the pdfcpu configuration directory. An empty root requests mode-specific discovery.
	Root string

	// Mode controls configuration discovery and filesystem access. Its zero value selects automatic mode.
	Mode ConfigurationMode
}

ConfigurationOptions controls configuration loading.

type ConfigurationPathInspection added in v0.16.0

type ConfigurationPathInspection struct {
	// Path is the resolved filesystem path. It is empty when the resource is unavailable.
	Path string `json:"path"`

	// Available is true when the selected mode provides this resource.
	Available bool `json:"available"`

	// Exists is true when Path exists.
	Exists bool `json:"exists"`

	// Writable is true when the current process may write to Path.
	Writable bool `json:"writable"`
}

ConfigurationPathInspection describes one configuration filesystem path.

type ConfigurationPathsInspection added in v0.16.0

type ConfigurationPathsInspection struct {
	// Config describes config.yml.
	Config ConfigurationPathInspection `json:"config"`

	// Fonts describes the user-font directory.
	Fonts ConfigurationPathInspection `json:"fonts"`

	// Certificates describes the trusted-certificate directory.
	Certificates ConfigurationPathInspection `json:"certificates"`
}

ConfigurationPathsInspection contains resolved configuration resource paths.

type ConfigurationSchemaCompatibilityError added in v0.16.0

type ConfigurationSchemaCompatibilityError = model.ConfigurationSchemaCompatibilityError

ConfigurationSchemaCompatibilityError reports an incompatible persisted configuration schema.

type ConfigurationSchemaInspection added in v0.16.0

type ConfigurationSchemaInspection struct {
	// Detected is the schema version read from the selected configuration.
	Detected int `json:"detected"`

	// MinimumSupported is the oldest schema version supported by this build.
	MinimumSupported int `json:"minimumSupported"`

	// MaximumSupported is the newest schema version supported by this build.
	MaximumSupported int `json:"maximumSupported"`
}

ConfigurationSchemaInspection describes configuration schema compatibility.

type ConfigurationSource added in v0.16.0

type ConfigurationSource string

ConfigurationSource identifies how the configuration root was selected.

const (
	// ConfigurationSourceFlag identifies an explicit root or stateless selection, including a command-line flag.
	ConfigurationSourceFlag ConfigurationSource = "flag"

	// ConfigurationSourceEnvironment identifies a root selected by the environment.
	ConfigurationSourceEnvironment ConfigurationSource = "environment"

	// ConfigurationSourceOSDefault identifies the operating system's default configuration root.
	ConfigurationSourceOSDefault ConfigurationSource = "os-default"
)

type FontCheatSheetResult added in v0.16.0

type FontCheatSheetResult struct {
	Paths []string
}

FontCheatSheetResult identifies cheat-sheet PDFs that were published before the operation returned.

func CreateCheatSheetsUserFontsWithResult added in v0.16.0

func CreateCheatSheetsUserFontsWithResult(c context.Context, fontNames []string) (result FontCheatSheetResult, err error)

CreateCheatSheetsUserFontsWithResult atomically generates a batch of user-font cheat sheets, supports cancellation and reports published paths.

func CreateUserFontCheatSheetsWithResult added in v0.16.0

func CreateUserFontCheatSheetsWithResult(c context.Context, dir, fn string) (result FontCheatSheetResult, err error)

CreateUserFontCheatSheetsWithResult atomically generates and publishes one PDF for each covered Unicode plane, supports cancellation and reports published paths.

type FontInstallResult added in v0.16.0

type FontInstallResult struct {
	Warnings []error
}

FontInstallResult reports non-fatal cleanup failures encountered while installing fonts.

func InstallFontsWithResult added in v0.16.0

func InstallFontsWithResult(c context.Context, fileNames []string) (result FontInstallResult, err error)

InstallFontsWithResult transactionally installs true type fonts, supports cancellation and reports non-fatal cleanup warnings. Cancellation before publication leaves the installed font directory unchanged.

type PageSpan added in v0.4.0

type PageSpan struct {
	// From is the first page number of this span.
	From int

	// Thru is the last page number of this span.
	Thru int

	// Reader provides the PDF stream for this span.
	Reader io.Reader
}

PageSpan represents a contiguous page range and its generated PDF stream.

func SplitRaw added in v0.4.0

func SplitRaw(c context.Context, rs io.ReadSeeker, span int, conf *model.Configuration) (ps []*PageSpan, err error)

SplitRaw returns page spans for the PDF stream read from rs obeying given split span. If span == 1 splitting results in single page PDFs. If span == 0 we split along given bookmarks (level 1 only). Default span: 1 SplitRaw is not used within this repository and supports cancellation.

type ProgressError added in v0.16.0

type ProgressError struct {
	// Event is the event rejected by the observer.
	Event ProgressEvent

	// Err is the error returned by the observer.
	Err error
}

ProgressError reports a failure returned by a ProgressObserver.

func (*ProgressError) Error added in v0.16.0

func (e *ProgressError) Error() string

Error implements error.

func (*ProgressError) Unwrap added in v0.16.0

func (e *ProgressError) Unwrap() error

Unwrap returns the observer failure.

type ProgressEvent added in v0.16.0

type ProgressEvent struct {
	// Stage identifies the operation stage that is about to begin.
	Stage ProgressStage

	// Input identifies the current input when known.
	Input string

	// Item is the one-based current input position when known.
	Item int

	// Total is the total number of inputs when known.
	Total int
}

ProgressEvent describes the current stage of one API operation.

type ProgressObserver added in v0.16.0

type ProgressObserver func(ProgressEvent) error

ProgressObserver receives ordered events synchronously before each reported stage begins. Returning an error aborts the operation. File operations treat observer failures like processing failures and clean up staged output before returning the error.

type ProgressOptions added in v0.16.0

type ProgressOptions struct {
	// Observer receives progress events. A nil observer disables observation.
	Observer ProgressObserver

	// Input identifies the current input for stream-based operations.
	Input string

	// Item is the one-based current input position when known.
	Item int

	// Total is the total number of inputs when known.
	Total int
}

ProgressOptions configures optional per-call progress observation.

type ProgressStage added in v0.16.0

type ProgressStage string

ProgressStage identifies a stable, coarse operation stage.

const (
	// ProgressStageReading identifies input reading.
	ProgressStageReading ProgressStage = "reading"

	// ProgressStageValidating identifies PDF validation.
	ProgressStageValidating ProgressStage = "validating"

	// ProgressStageOptimizing identifies PDF optimization.
	ProgressStageOptimizing ProgressStage = "optimizing"

	// ProgressStageProcessing identifies operation-specific processing.
	ProgressStageProcessing ProgressStage = "processing"

	// ProgressStageWriting identifies output serialization.
	ProgressStageWriting ProgressStage = "writing"

	// ProgressStageCommitting identifies publication of staged output.
	ProgressStageCommitting ProgressStage = "committing"

	// ProgressStageCleanup identifies cleanup after an operation.
	ProgressStageCleanup ProgressStage = "cleanup"

	// ProgressStageRollback identifies restoration after an operation failure.
	ProgressStageRollback ProgressStage = "rollback"
)

type ReadSeekerAt added in v0.14.0

type ReadSeekerAt interface {
	io.ReadSeeker
	io.ReaderAt
}

ReadSeekerAt supports PDF parsing and positional signature verification.

type UnsupportedResourceError added in v0.14.0

type UnsupportedResourceError struct {
	// Err contains the contextual errors for all skipped resources.
	Err error
}

UnsupportedResourceError aggregates resources skipped during an otherwise successful extraction.

func (*UnsupportedResourceError) Error added in v0.14.0

func (e *UnsupportedResourceError) Error() string

Error returns the aggregated unsupported-resource error text.

func (*UnsupportedResourceError) Unwrap added in v0.14.0

func (e *UnsupportedResourceError) Unwrap() error

Unwrap returns the aggregated unsupported-resource causes.

type VersionRequirementError added in v0.16.0

type VersionRequirementError = pdfcpu.VersionRequirementError

VersionRequirementError reports an element requiring a newer PDF version.

Jump to

Keyboard shortcuts

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