Document

Overview

Document is a type in Aspose.PDF FOSS for Go.

Document is a PDF document.

This type provides 88 methods for working with Document objects in Go programs. Available methods include: AddBlankPage, AddBlankPageFromFormat, AddLayer, AddSVGObjectWatermark, AddSVGWatermark, AddSVGWatermarkFromStream, AddStamp, AddTextWatermark, Append, ApplyRedactions, Booklet, ChangePassword, and 76 additional methods. All public members are accessible to any Go application after installing the Aspose.PDF FOSS for Go package.

Methods

SignatureDescription
PageCount() → intPageCount returns the number of pages in the document.
Pages() → []*PagePages returns a live view of all pages in the document.
Page(n: int) → (*Page, error)Page returns a live view of the page at the given 1-based number.
Append(others: ...*Document)Append adds all pages from others to this document, merging their objects.
RemoveUnusedObjects() → intRemoveUnusedObjects removes objects from the document that are not reachable from any page.
SetPassword(userPassword: string)SetPassword configures the document to be encrypted when saved.
SetPermissions(p: Permissions)SetPermissions configures what operations a viewer allows on the encrypted document (printing, copying, modifying, etc.).
Permissions() → (Permissions, bool)Permissions returns the viewer-permission settings currently configured on this document, plus a boolean indicating whether the document is configured for encryption at all.
RemoveEncryption()RemoveEncryption clears any previously configured encryption (passwords and permissions) so the next Save produces a plaintext PDF.
ChangePassword(newUserPassword: string) → errorChangePassword re-encrypts the document with new passwords on the next Save, keeping the current encryption algorithm and permissions.
SetEncryption(opts: EncryptionOptions)SetEncryption configures every encryption-related setting at once from an EncryptionOptions struct.
WriteTo(w: io.Writer) → (int64, error)WriteTo writes the document to w.
Save(outputPath: string) → errorSave writes the document to outputPath.
AddBlankPage(width: float64) → errorAddBlankPage appends a blank page to the end of the document.
AddBlankPageFromFormat(format: PageFormat) → errorAddBlankPageFromFormat appends a blank page using a predefined page format.
InsertBlankPage(position: int, width: float64) → errorInsertBlankPage inserts a blank page at the given 1-based position.
InsertBlankPageFromFormat(position: int, format: PageFormat) → errorInsertBlankPageFromFormat inserts a blank page at the given position using a predefined page format.
Rotate(angle: RotationAngle, pageNums: ...int) → errorRotate rotates selected pages clockwise by angle (Rotate90, Rotate180, or Rotate270).
SetRotation(angle: RotationAngle, pageNums: ...int) → errorSetRotation sets selected pages to exactly angle (Rotate0, Rotate90, Rotate180, or Rotate270), replacing any existing rotation.
Reorder(order: []int) → errorReorder rearranges pages according to order, a slice of 1-based page numbers.
DeletePage(n: int) → errorDeletePage removes the page at the given 1-based number.
DeletePages(pageNums: ...int) → errorDeletePages removes the pages at the given 1-based page numbers.
Split() → ([]*Document, error)Split returns each page of the document as a separate *Document.
Extract(ranges: ...PageRange) → (*Document, error)Extract returns a new Document containing only the pages in the specified ranges.
EmbeddedFiles() → *EmbeddedFilesEmbeddedFiles returns the document-level embedded-file collection.
Flatten() → errorFlatten bakes the document’s interactive form fields into static page content and removes the AcroForm, so the result renders identically but is no longer fillable.
NewFlow(opts: FlowOptions) → *FlowNewFlow creates a flow that renders into the document d.
LoadFont(path: string) → (Font, error)LoadFont reads a TTF file, parses it, embeds it into the document, and returns a Font that can be used in TextStyle.Font.
LoadFontFromStream(r: io.Reader) → (Font, error)LoadFontFromStream is like LoadFont but reads from an io.Reader.
LoadFontByName(family: string, bold: bool) → (Font, error)LoadFontByName resolves a font by family name (with an optional bold / italic style) through the FontRepository — the folders and files registered with AddFontFolder / AddFontFile first, then the operating system’s font directories — embeds the matched face into the document, and returns a Font usable in TextStyle.Font.
SubsetFonts() → (int, error)SubsetFonts shrinks every embedded TTF (loaded via LoadFont) to only the glyphs actually drawn, replacing each /FontFile2 with a rebuilt subset program and switching the CIDFont’s /CIDToGIDMap from /Identity to a stream that maps the original glyph IDs (still used verbatim as CIDs in content streams) to the compact subset glyph IDs.
Form() → *FormForm returns the document’s AcroForm.
CreateForm(width: float64) → *XFormCreateForm creates an empty Form XObject of the given size (points).
ImportForm(form: *XForm) → (*XForm, error)ImportForm copies a Form XObject (and its whole resource graph: fonts, images, nested forms, …) from another document into this one, returning a new XForm ready to place with Page.AddForm.
ConvertToGrayscale() → errorConvertToGrayscale converts the document to grayscale in place: every device colour set in a content stream (text, vector graphics), every raster image, shading and annotation colour is mapped to its luminance grey.
SaveHTML(outputPath: string, opts: ...HTMLSaveOptions) → errorSaveHTML writes the document as an HTML file — self-contained by default; with ResourceDir/ResourceWriter the heavy parts become external files, and with SplitPages each page becomes its own _p.html.
WriteHTML(w: io.Writer, opts: ...HTMLSaveOptions) → errorWriteHTML writes the document as a single self-contained HTML file to w: per page, a raster background under a text layer (transparent in HTMLModeFaithful, visible in HTMLModeText) and link-annotation overlays.
ExtractImages() → ([][]Image, error)ExtractImages returns images from all pages (one slice per page).
ImageInfos() → ([][]ImageInfo, error)ImageInfos returns image metadata for all pages (one slice per page) without decoding pixel data.
OptimizeImages(opts: OptimizeImageOptions) → (int, error)OptimizeImages optimizes all images in the document to reduce file size.
NUp(opts: NUpOptions) → (*Document, error)NUp returns a new Document that imposes this document’s pages onto larger sheets in a Rows×Cols grid (e.g.
Booklet(opts: BookletOptions) → (*Document, error)Booklet returns a new Document that imposes this document’s pages two-up, reordered for saddle-stitch binding: print double-sided, fold the stack in half, and the pages read in order.
JavaScript() → *JavaScriptCollectionJavaScript returns the document-level JavaScript collection.
SaveLinearized(outputPath: string) → errorSaveLinearized writes the document to outputPath as a linearized (“fast web view”) PDF (ISO 32000-1 Annex F): the first page’s objects and a hint table sit at the front so a viewer can render page 1 before the whole file has downloaded.
WriteToLinearized(w: io.Writer) → (int64, error)WriteToLinearized writes the document as a linearized PDF to w (implements an io.WriterTo-style contract).
Info() → (DocumentInfo, error)Info returns the Info-dictionary metadata from this document.
SetInfo(info: DocumentInfo)SetInfo replaces the document’s Info dictionary with the given metadata.
ClearInfo()ClearInfo removes the Info dictionary entirely.
NamedDestinations() → *NamedDestinationsNamedDestinations returns the document’s named-destination collection.
OpenAction() → ActionOpenAction returns the action the viewer runs when the document is opened (/Catalog/OpenAction per ISO 32000-1 §12.3.2 / §12.6.1), or nil when none is set.
SetOpenAction(act: Action)SetOpenAction sets the action run when the document opens.
RemoveOpenAction()RemoveOpenAction clears any /Catalog/OpenAction.
AddLayer(name: string) → *LayerAddLayer creates a new layer (OCG) named name and registers it in the document’s optional-content properties.
Layers() → []*LayerLayers returns the document’s layers (OCGs), in /OCProperties/OCGs order.
Outlines() → *OutlineItemCollectionOutlines returns the document’s root outline collection.
SetPageLabels(ranges: []PageLabelRange) → errorSetPageLabels installs the document’s /PageLabels number tree so PDF viewers display labels like “i, ii, 1, 2, …” in the navigation pane and page indicators.
ClearPageLabels()ClearPageLabels removes the document’s /PageLabels entry.
Paragraphs() → ([]PageMarkup, error)Paragraphs returns the structured text of every page.
ConvertToPDFA(format: PDFAFormat) → (*PDFAValidationReport, error)ConvertToPDFA adjusts the document toward a PDF/A “b”-level conformance profile and returns a validation report describing any violations that remain.
ValidateRedactions() → errorValidateRedactions performs a pre-flight dry-run parseability check on every page that has at least one RedactAnnotation.
ApplyRedactions() → errorApplyRedactions destructively removes content (text glyphs, image XObjects, paths) inside every /Redact annotation’s /QuadPoints (or /Rect if /QuadPoints is empty).
RenderImage(pageNum: int, opts: RenderOptions) → (image.Image, error)RenderImage renders the 1-based page number to an image.
RenderTIFF(w: io.Writer, opts: RenderOptions, pageNums: ...int) → errorRenderTIFF renders the document to a single multi-page TIFF written to w.
ReplaceText(old: string, opts: ...ReplaceOptions) → (int, error)ReplaceText replaces every occurrence of old with replacement across all pages, returning the total number of replacements.
Sign(opts: SignOptions) → errorSign configures a digital signature applied on the next Save/WriteTo.
VerifySignatures() → ([]SignatureVerification, error)VerifySignatures verifies every digital signature in the document and returns one result per signature field, in document order.
AddStamp(s: Stamp, pageNums: ...int) → errorAddStamp draws a stamp onto the given 1-based pages (all pages when none are given) — convenient for watermarks, headers, footers, and page numbers.
LoadSVG(path: string) → (*SVG, error)LoadSVG reads and parses an SVG file once, returning a *SVG that can be passed to Page.AddSVGObject or Document.AddSVGObjectWatermark multiple times without re-parsing.
LoadSVGFromStream(r: io.Reader) → (*SVG, error)LoadSVGFromStream is the io.Reader variant of LoadSVG.
AddSVGWatermark(path: string, pageNums: ...int) → errorAddSVGWatermark applies an SVG watermark to all pages (when pageNums is empty) or to the specified 1-based page numbers.
AddSVGWatermarkFromStream(r: io.Reader, pageNums: ...int) → errorAddSVGWatermarkFromStream is the io.Reader variant of AddSVGWatermark.
SetSVGFontResolver(fn: SVGFontResolver)SetSVGFontResolver installs a custom resolver.
AddSVGObjectWatermark(svg: *SVG, pageNums: ...int) → errorAddSVGObjectWatermark uses a pre-parsed *SVG for the watermark content.
TaggedContent() → *TaggedContentTaggedContent returns the document’s tagged-content facade, creating the structure tree and the /MarkInfo, /ViewerPreferences and /StructTreeRoot catalog entries on first call.
ExtractText(opts: ...TextExtractOptions) → ([]string, error)ExtractText returns the text content of each page (one entry per page, 0-indexed).
AddTextWatermark(text: string, style: TextStyle, pageNums: ...int) → errorAddTextWatermark adds a text watermark to selected pages of the document.
ExtractTextWithLayout() → ([][]TextLine, error)ExtractTextWithLayout returns structured text lines for each page.
SearchText(query: string, opts: ...SearchOptions) → ([]TextMatch, error)SearchText finds every occurrence of query across all pages of the document, returning matches page by page in reading order.
GenerateTOC(opts: ...TOCOptions) → (int, error)GenerateTOC builds a table of contents from the document’s outline (bookmark) tree and inserts it as new page(s) at the front of the document.
ValidatePDFA(format: PDFAFormat) → *PDFAValidationReportValidatePDFA checks the document against a PDF/A “b”-level conformance profile and returns a report of violations.
ValidatePDFUA() → *PDFUAValidationReportValidatePDFUA checks the document against a subset of PDF/UA-1 (ISO 14289-1, universal accessibility) and returns a report of violations.
CreateTilingPattern(width: float64) → *TilingPatternCreateTilingPattern creates an empty tiling pattern whose cell is width×height points.
XMP() → (XMPMetadata, error)XMP returns the document’s XMP metadata parsed from the /Catalog/Metadata stream.
XMPRaw() → ([]byte, error)XMPRaw returns the raw bytes of the XMP packet from /Catalog/Metadata, or nil when the document has no XMP stream.
SetXMP(meta: XMPMetadata) → errorSetXMP serialises meta into a standard XMP packet and stores it as the /Catalog/Metadata stream (uncompressed, /Type /Metadata /Subtype /XML per ISO 32000-1 §14.3.2).
SetXMPRaw(data: []byte) → errorSetXMPRaw stores data verbatim as the /Catalog/Metadata stream — an escape hatch for callers that produce their own XMP packet.
ClearXMP()ClearXMP removes the /Catalog/Metadata entry.
SyncInfoToXMP() → errorSyncInfoToXMP builds an XMP packet from the document’s current /Info dictionary and installs it, so the two metadata stores agree (ISO 32000-1 §14.3.2 recommends consistency when both are present).

See Also

 English