Documentation
¶
Overview ¶
Package asposepdf is a pure Go PDF library — no CGo, no native dependencies, standard library only, MIT-licensed. It reads, creates, edits, renders, signs, encrypts, converts, and validates PDF documents.
Capabilities include: page manipulation (split, merge, extract, rotate, N-up/booklet imposition); text extraction in reading order with layout, search (literal/regex) and replace; drawing text (with word wrap, Unicode, RTL/Arabic shaping), vector graphics (paths, gradients, tiling patterns) and tables with automatic pagination; a flow document generator; TrueType and OpenType font embedding with subsetting; AcroForm reading, filling, creation, styling and flattening with JSON/FDF/XFDF interchange; the full annotation family with generated appearance streams; encryption (RC4-128, AES-128, AES-256) and digital signatures (PKCS#7, PAdES, DocMDP certification, RFC 3161 timestamps, multiple signatures) with verification; bookmarks, named destinations, page labels, Info and XMP metadata, embedded files, optional-content layers; PDF/A validation and conversion, Tagged PDF authoring and PDF/UA validation; redaction; linearization (fast web view); and a unified size optimizer.
Converters: render pages to PNG, JPEG, GIF, BMP and multi-page TIFF with the built-in dependency-free rasterizer; export documents to HTML (four modes, including fillable forms), SVG (true vector) and Markdown; convert Markdown (CommonMark + GFM, 652/652 official test suite), SVG and raster images to PDF. The ai subpackage adds AI copilots — summarization, OCR with a searchable-PDF pipeline, document Q&A and image description — over any OpenAI-compatible endpoint.
The public API is shaped to mirror Aspose.PDF for .NET (Document, Page, TextFragment, Table, Form, OutlineItemCollection, …), adapted to Go idioms: error returns, io.Reader/io.Writer streams, and exported functions over constructors. Spec references follow ISO 32000-1 (PDF 1.7) and ISO 32000-2 (PDF 2.0).
Index ¶
- Constants
- Variables
- func AddFontFile(path string)
- func AddFontFolder(path string)
- func AddSystemFonts()
- func AssembleDestinationText(ops []DiffOperation) string
- func AssembleSourceText(ops []DiffOperation) string
- func ClearFontSources()
- func Encrypt(inputPath, outputPath, userPassword, ownerPassword string) error
- func MeasureText(text string, style TextStyle) (float64, error)
- type AFRelationship
- type AbsorbedCell
- type AbsorbedRow
- type AbsorbedTable
- type Action
- type ActionType
- type Annotation
- type AnnotationCollection
- func (c *AnnotationCollection) Add(a Annotation) error
- func (c *AnnotationCollection) All() []Annotation
- func (c *AnnotationCollection) At(index int) Annotation
- func (c *AnnotationCollection) Count() int
- func (c *AnnotationCollection) Delete(a Annotation) bool
- func (c *AnnotationCollection) DeleteAt(index int) error
- func (c *AnnotationCollection) Flatten() error
- type AnnotationType
- type BarcodeField
- func (b *BarcodeField) Flatten() error
- func (b *BarcodeField) FullName() string
- func (b *BarcodeField) IsReadOnly() bool
- func (b *BarcodeField) IsRequired() bool
- func (b *BarcodeField) PageIndex() int
- func (b *BarcodeField) PartialName() string
- func (b *BarcodeField) Rect() Rectangle
- func (b *BarcodeField) SetStyle(s FieldStyle) error
- func (bc *BarcodeField) SetSymbology(s BarcodeSymbology) error
- func (bc *BarcodeField) SetValue(value string) error
- func (b *BarcodeField) Style() FieldStyle
- func (bc *BarcodeField) Symbology() BarcodeSymbology
- type BarcodeSymbology
- type BmpDevice
- type BookletBinding
- type BookletOptions
- type BorderEffect
- type BorderInfo
- type BorderSide
- type BorderStyle
- type ButtonAppearance
- type ButtonField
- func (f *ButtonField) Action() Action
- func (b *ButtonField) Flatten() error
- func (b *ButtonField) FullName() string
- func (b *ButtonField) IsReadOnly() bool
- func (b *ButtonField) IsRequired() bool
- func (b *ButtonField) PageIndex() int
- func (b *ButtonField) PartialName() string
- func (b *ButtonField) Rect() Rectangle
- func (f *ButtonField) SetAction(act Action)
- func (f *ButtonField) SetAppearance(a ButtonAppearance) error
- func (f *ButtonField) SetReadOnly(v bool)
- func (b *ButtonField) SetStyle(s FieldStyle) error
- func (f *ButtonField) SetValue(s string) error
- func (b *ButtonField) Style() FieldStyle
- func (f *ButtonField) Value() string
- type ButtonIconPosition
- type CaretAnnotation
- func (a *CaretAnnotation) AnnotationType() AnnotationType
- func (d *CaretAnnotation) BorderStyle() BorderStyle
- func (d *CaretAnnotation) BorderWidth() float64
- func (d *CaretAnnotation) DashPattern() []float64
- func (a *CaretAnnotation) RegenerateAppearance()
- func (d *CaretAnnotation) SetBorderStyle(s BorderStyle)
- func (d *CaretAnnotation) SetBorderWidth(w float64)
- func (d *CaretAnnotation) SetColor(c *Color)
- func (d *CaretAnnotation) SetDashPattern(p []float64)
- func (d *CaretAnnotation) SetRect(r Rectangle)
- func (a *CaretAnnotation) SetSymbol(s CaretSymbol)
- func (a *CaretAnnotation) Symbol() CaretSymbol
- type CaretSymbol
- type Cell
- func (c *Cell) Background() *Color
- func (c *Cell) Border() *BorderInfo
- func (c *Cell) ColSpan() int
- func (c *Cell) Image() (path string, hasImage bool)
- func (c *Cell) Margin() *MarginInfo
- func (c *Cell) Row() *Row
- func (c *Cell) RowSpan() int
- func (c *Cell) SetBackground(col *Color) *Cell
- func (c *Cell) SetBorder(b BorderInfo) *Cell
- func (c *Cell) SetColSpan(n int) *Cell
- func (c *Cell) SetHAlign(h HAlign) *Cell
- func (c *Cell) SetImage(path string) *Cell
- func (c *Cell) SetImageFromStream(r io.Reader) *Cell
- func (c *Cell) SetMargin(m MarginInfo) *Cell
- func (c *Cell) SetRowSpan(n int) *Cell
- func (c *Cell) SetText(text string) *Cell
- func (c *Cell) SetTextStyle(s TextStyle) *Cell
- func (c *Cell) SetVAlign(v VAlign) *Cell
- func (c *Cell) Text() string
- func (c *Cell) TextStyle() *TextStyle
- type CertifyPermission
- type CheckboxField
- func (f *CheckboxField) Checked() bool
- func (b *CheckboxField) Flatten() error
- func (b *CheckboxField) FullName() string
- func (b *CheckboxField) IsReadOnly() bool
- func (b *CheckboxField) IsRequired() bool
- func (b *CheckboxField) PageIndex() int
- func (b *CheckboxField) PartialName() string
- func (b *CheckboxField) Rect() Rectangle
- func (f *CheckboxField) SetChecked(v bool)
- func (f *CheckboxField) SetReadOnly(v bool)
- func (f *CheckboxField) SetRequired(v bool)
- func (b *CheckboxField) SetStyle(s FieldStyle) error
- func (f *CheckboxField) SetValue(s string) error
- func (b *CheckboxField) Style() FieldStyle
- func (f *CheckboxField) Value() string
- type ChoiceOption
- type CircleAnnotation
- func (a *CircleAnnotation) AnnotationType() AnnotationType
- func (d *CircleAnnotation) BorderStyle() BorderStyle
- func (d *CircleAnnotation) BorderWidth() float64
- func (d *CircleAnnotation) DashPattern() []float64
- func (a *CircleAnnotation) InteriorColor() *Color
- func (a *CircleAnnotation) RegenerateAppearance()
- func (d *CircleAnnotation) SetBorderStyle(s BorderStyle)
- func (d *CircleAnnotation) SetBorderWidth(w float64)
- func (d *CircleAnnotation) SetColor(c *Color)
- func (d *CircleAnnotation) SetDashPattern(p []float64)
- func (a *CircleAnnotation) SetInteriorColor(c *Color)
- func (d *CircleAnnotation) SetRect(r Rectangle)
- type Collection
- func (c *Collection) Files() []*EmbeddedFile
- func (c *Collection) InitialFile() string
- func (c *Collection) IsPortfolio() bool
- func (c *Collection) Remove()
- func (c *Collection) Schema() *CollectionSchema
- func (c *Collection) SetInitialFile(name string)
- func (c *Collection) SetSort(field string, ascending bool)
- func (c *Collection) SetView(v CollectionView)
- func (c *Collection) Sort() (field string, ascending bool, ok bool)
- func (c *Collection) View() CollectionView
- type CollectionField
- func (f *CollectionField) DisplayName() string
- func (f *CollectionField) IsDerived() bool
- func (f *CollectionField) IsEditable() bool
- func (f *CollectionField) IsVisible() bool
- func (f *CollectionField) Key() string
- func (f *CollectionField) Order() int
- func (f *CollectionField) SetDisplayName(s string)
- func (f *CollectionField) SetEditable(v bool)
- func (f *CollectionField) SetOrder(n int)
- func (f *CollectionField) SetVisible(v bool)
- func (f *CollectionField) Type() CollectionFieldType
- type CollectionFieldType
- type CollectionItem
- func (i *CollectionItem) Date(field string) (value time.Time, ok bool)
- func (i *CollectionItem) Fields() []string
- func (i *CollectionItem) Number(field string) (value float64, ok bool)
- func (i *CollectionItem) Remove(field string) bool
- func (i *CollectionItem) SetDate(field string, t time.Time)
- func (i *CollectionItem) SetNumber(field string, value float64)
- func (i *CollectionItem) SetText(field, value string)
- func (i *CollectionItem) Text(field string) string
- type CollectionSchema
- func (s *CollectionSchema) Add(key, displayName string, typ CollectionFieldType) *CollectionField
- func (s *CollectionSchema) Count() int
- func (s *CollectionSchema) Field(key string) *CollectionField
- func (s *CollectionSchema) Fields() []*CollectionField
- func (s *CollectionSchema) Keys() []string
- func (s *CollectionSchema) Remove(key string) bool
- type CollectionView
- type Color
- type ComboBoxField
- func (f *ComboBoxField) AddOption(o ChoiceOption)
- func (b *ComboBoxField) Flatten() error
- func (b *ComboBoxField) FullName() string
- func (b *ComboBoxField) IsReadOnly() bool
- func (b *ComboBoxField) IsRequired() bool
- func (f *ComboBoxField) Options() []ChoiceOption
- func (b *ComboBoxField) PageIndex() int
- func (b *ComboBoxField) PartialName() string
- func (b *ComboBoxField) Rect() Rectangle
- func (f *ComboBoxField) RemoveOption(index int) error
- func (f *ComboBoxField) Selected() int
- func (f *ComboBoxField) SetEditable(v bool)
- func (f *ComboBoxField) SetReadOnly(v bool)
- func (f *ComboBoxField) SetRequired(v bool)
- func (f *ComboBoxField) SetSelected(index int) error
- func (b *ComboBoxField) SetStyle(s FieldStyle) error
- func (f *ComboBoxField) SetValue(s string) error
- func (b *ComboBoxField) Style() FieldStyle
- func (f *ComboBoxField) Value() string
- type ComparisonOptions
- type ComparisonResult
- func (r *ComparisonResult) HasChanges() bool
- func (r *ComparisonResult) Operations() []DiffOperation
- func (r *ComparisonResult) PageOperations(pageNum int) []DiffOperation
- func (r *ComparisonResult) Pages() [][]DiffOperation
- func (r *ComparisonResult) SaveMarkup(path string, opts ...DiffMarkupOptions) error
- func (r *ComparisonResult) Statistics() ComparisonStatistics
- func (r *ComparisonResult) WriteMarkup(w io.Writer, opts ...DiffMarkupOptions) error
- type ComparisonStatistics
- type DateField
- func (b *DateField) Flatten() error
- func (d *DateField) Format() string
- func (b *DateField) FullName() string
- func (b *DateField) IsReadOnly() bool
- func (b *DateField) IsRequired() bool
- func (b *DateField) PageIndex() int
- func (b *DateField) PartialName() string
- func (b *DateField) Rect() Rectangle
- func (b *DateField) SetStyle(s FieldStyle) error
- func (b *DateField) Style() FieldStyle
- type Destination
- type DestinationFit
- type DestinationFitB
- type DestinationFitBH
- type DestinationFitBV
- type DestinationFitH
- type DestinationFitR
- type DestinationFitV
- type DestinationType
- type DestinationXYZ
- func (d *DestinationXYZ) DestinationType() DestinationType
- func (d *DestinationXYZ) HasLeft() bool
- func (d *DestinationXYZ) HasTop() bool
- func (d *DestinationXYZ) HasZoom() bool
- func (d *DestinationXYZ) Left() float64
- func (d *DestinationXYZ) Page() *Page
- func (d *DestinationXYZ) Top() float64
- func (d *DestinationXYZ) Zoom() float64
- type DiffMarkupOptions
- type DiffMarkupSide
- type DiffOperation
- type DiffOutputStyle
- type DigestAlgorithm
- type DocRecognitionMode
- type DocSaveOptions
- type Document
- func ImageToDocument(path string, opts ...ImageToDocumentOptions) (*Document, error)
- func ImageToDocumentFromStream(r io.Reader, opts ...ImageToDocumentOptions) (*Document, error)
- func MarkdownToDocument(path string, opts ...MarkdownOptions) (*Document, error)
- func MarkdownToDocumentFromStream(r io.Reader, opts ...MarkdownOptions) (*Document, error)
- func NewDocument(width, height float64) *Document
- func NewDocumentFromFormat(format PageFormat) *Document
- func Open(path string) (*Document, error)
- func OpenStream(r io.Reader) (*Document, error)
- func OpenStreamWithCertificate(r io.Reader, cert *x509.Certificate, key crypto.Decrypter) (*Document, error)
- func OpenStreamWithPassword(r io.Reader, password string) (*Document, error)
- func OpenWithCertificate(path string, cert *x509.Certificate, key crypto.Decrypter) (*Document, error)
- func OpenWithPassword(path, password string) (*Document, error)
- func (d *Document) AddBlankPage(width, height float64) error
- func (d *Document) AddBlankPageFromFormat(format PageFormat) error
- func (d *Document) AddLayer(name string) *Layer
- func (d *Document) AddSVGObjectWatermark(svg *SVG, pageNums ...int) error
- func (d *Document) AddSVGWatermark(path string, pageNums ...int) error
- func (d *Document) AddSVGWatermarkFromStream(r io.Reader, pageNums ...int) error
- func (d *Document) AddStamp(s Stamp, pageNums ...int) error
- func (d *Document) AddTextWatermark(text string, style TextStyle, pageNums ...int) error
- func (d *Document) AddValidationInfo(opts ...ValidationOptions) error
- func (d *Document) Append(others ...*Document)
- func (d *Document) ApplyRedactions() error
- func (d *Document) AttachInvoice(xmlData []byte, opts ...InvoiceOptions) (*PDFAValidationReport, error)
- func (d *Document) Booklet(opts BookletOptions) (*Document, error)
- func (d *Document) ChangePassword(newUserPassword, newOwnerPassword string) error
- func (d *Document) ClearInfo()
- func (d *Document) ClearPageLabels()
- func (d *Document) ClearXMP()
- func (d *Document) Collection() *Collection
- func (d *Document) ConvertToGrayscale() error
- func (d *Document) ConvertToPDFA(format PDFAFormat) (*PDFAValidationReport, error)
- func (d *Document) CreateForm(width, height float64) *XForm
- func (d *Document) CreateTilingPattern(width, height float64) *TilingPattern
- func (d *Document) CreateType3Font() *Type3Font
- func (d *Document) DeletePage(n int) error
- func (d *Document) DeletePages(pageNums ...int) error
- func (d *Document) EmbeddedFiles() *EmbeddedFiles
- func (d *Document) Extract(ranges ...PageRange) (*Document, error)
- func (d *Document) ExtractImages() ([][]Image, error)
- func (d *Document) ExtractText(opts ...TextExtractOptions) ([]string, error)
- func (d *Document) ExtractTextWithLayout() ([][]TextLine, error)
- func (d *Document) FiguresNeedingAltText() ([]*FigureAlt, error)
- func (d *Document) Flatten() error
- func (d *Document) FlattenTransparency(opts ...FlattenTransparencyOptions) (int, error)
- func (d *Document) Form() *Form
- func (d *Document) GenerateTOC(opts ...TOCOptions) (int, error)
- func (d *Document) ImageInfos() ([][]ImageInfo, error)
- func (d *Document) ImportForm(form *XForm) (*XForm, error)
- func (d *Document) Info() (DocumentInfo, error)
- func (d *Document) InsertBlankPage(position int, width, height float64) error
- func (d *Document) InsertBlankPageFromFormat(position int, format PageFormat) error
- func (d *Document) Invoice() (*Invoice, error)
- func (d *Document) JavaScript() *JavaScriptCollection
- func (d *Document) Layers() []*Layer
- func (d *Document) LoadFont(path string) (Font, error)
- func (d *Document) LoadFontByName(family string, bold, italic bool) (Font, error)
- func (d *Document) LoadFontFromStream(r io.Reader) (Font, error)
- func (d *Document) LoadSVG(path string) (*SVG, error)
- func (d *Document) LoadSVGFromStream(r io.Reader) (*SVG, error)
- func (d *Document) NUp(opts NUpOptions) (*Document, error)
- func (d *Document) NamedDestinations() *NamedDestinations
- func (d *Document) NeedsRepair() bool
- func (d *Document) NewFlow(opts FlowOptions) *Flow
- func (d *Document) OpenAction() Action
- func (d *Document) Optimize(opts OptimizationOptions) (OptimizationResult, error)
- func (d *Document) OptimizeImages(opts OptimizeImageOptions) (int, error)
- func (d *Document) Outlines() *OutlineItemCollection
- func (d *Document) Page(n int) (*Page, error)
- func (d *Document) PageCount() int
- func (d *Document) Pages() []*Page
- func (d *Document) Paragraphs() ([]PageMarkup, error)
- func (d *Document) Permissions() (Permissions, bool)
- func (d *Document) RemoveEncryption()
- func (d *Document) RemoveOpenAction()
- func (d *Document) RemoveUnusedObjects() int
- func (d *Document) RenderImage(pageNum int, opts RenderOptions) (image.Image, error)
- func (d *Document) RenderTIFF(w io.Writer, opts RenderOptions, pageNums ...int) error
- func (d *Document) Reorder(order []int) error
- func (d *Document) RepairReport() RepairReport
- func (d *Document) ReplaceText(old, replacement string, opts ...ReplaceOptions) (int, error)
- func (d *Document) Rotate(angle RotationAngle, pageNums ...int) error
- func (d *Document) Sanitize(opts HiddenDataSanitizationOptions) (HiddenDataSanitizationResult, error)
- func (d *Document) Save(outputPath string) error
- func (d *Document) SaveDocx(path string, opts ...DocSaveOptions) error
- func (d *Document) SaveEpub(path string, opts ...EpubSaveOptions) error
- func (d *Document) SaveHTML(outputPath string, opts ...HTMLSaveOptions) error
- func (d *Document) SaveLinearized(outputPath string) error
- func (d *Document) SaveMarkdown(path string, opts ...MarkdownSaveOptions) error
- func (d *Document) SaveSVG(path string, opts ...SVGSaveOptions) error
- func (d *Document) SaveXlsx(path string, opts ...XlsxSaveOptions) error
- func (d *Document) SearchText(query string, opts ...SearchOptions) ([]TextMatch, error)
- func (d *Document) SetEncryption(opts EncryptionOptions)
- func (d *Document) SetInfo(info DocumentInfo)
- func (d *Document) SetOpenAction(act Action)
- func (d *Document) SetPageLabels(ranges []PageLabelRange) error
- func (d *Document) SetPassword(userPassword, ownerPassword string)
- func (d *Document) SetPermissions(p Permissions)
- func (d *Document) SetRotation(angle RotationAngle, pageNums ...int) error
- func (d *Document) SetSVGFontResolver(fn SVGFontResolver)
- func (d *Document) SetXMP(meta XMPMetadata) error
- func (d *Document) SetXMPRaw(data []byte) error
- func (d *Document) Sign(opts SignOptions) error
- func (d *Document) SignatureNames() []string
- func (d *Document) Split() ([]*Document, error)
- func (d *Document) SubsetFonts() (int, error)
- func (d *Document) SyncInfoToXMP() error
- func (d *Document) TaggedContent() *TaggedContent
- func (d *Document) UnembedFonts() (int, error)
- func (d *Document) ValidatePDFA(format PDFAFormat) *PDFAValidationReport
- func (d *Document) ValidatePDFUA() *PDFUAValidationReport
- func (d *Document) ValidateRedactions() error
- func (d *Document) VerifySignature(fieldName string, opts ...ValidationOptions) (SignatureVerification, error)
- func (d *Document) VerifySignatures(opts ...ValidationOptions) ([]SignatureVerification, error)
- func (d *Document) WriteDocx(w io.Writer, opts ...DocSaveOptions) error
- func (d *Document) WriteEpub(w io.Writer, opts ...EpubSaveOptions) error
- func (d *Document) WriteHTML(w io.Writer, opts ...HTMLSaveOptions) error
- func (d *Document) WriteMarkdown(w io.Writer, opts ...MarkdownSaveOptions) error
- func (d *Document) WriteTo(w io.Writer) (int64, error)
- func (d *Document) WriteToLinearized(w io.Writer) (int64, error)
- func (d *Document) WriteXlsx(w io.Writer, opts ...XlsxSaveOptions) error
- func (d *Document) XMP() (XMPMetadata, error)
- func (d *Document) XMPRaw() ([]byte, error)
- type DocumentInfo
- type EditOperationsOrder
- type EmbeddedFile
- func (f *EmbeddedFile) AFRelationship() AFRelationship
- func (f *EmbeddedFile) CollectionItem() *CollectionItem
- func (f *EmbeddedFile) Data() ([]byte, error)
- func (f *EmbeddedFile) Description() string
- func (f *EmbeddedFile) MIMEType() string
- func (f *EmbeddedFile) Name() string
- func (f *EmbeddedFile) Save(path string) error
- func (f *EmbeddedFile) SetAFRelationship(r AFRelationship)
- func (f *EmbeddedFile) SetDescription(s string)
- func (f *EmbeddedFile) Size() int
- func (f *EmbeddedFile) WriteTo(w io.Writer) (int64, error)
- type EmbeddedFiles
- func (e *EmbeddedFiles) Add(path string) (*EmbeddedFile, error)
- func (e *EmbeddedFiles) AddFromStream(name string, r io.Reader) (*EmbeddedFile, error)
- func (e *EmbeddedFiles) All() []*EmbeddedFile
- func (e *EmbeddedFiles) Clear()
- func (e *EmbeddedFiles) Count() int
- func (e *EmbeddedFiles) Get(name string) *EmbeddedFile
- func (e *EmbeddedFiles) Has(name string) bool
- func (e *EmbeddedFiles) Names() []string
- func (e *EmbeddedFiles) Remove(name string) bool
- type EncryptionAlgorithm
- type EncryptionOptions
- type EpubSaveOptions
- type Field
- type FieldStyle
- type FigureAlt
- type FileAttachmentAnnotation
- func (a *FileAttachmentAnnotation) AFRelationship() AFRelationship
- func (a *FileAttachmentAnnotation) AnnotationType() AnnotationType
- func (b *FileAttachmentAnnotation) Color() *Color
- func (b *FileAttachmentAnnotation) Contents() string
- func (a *FileAttachmentAnnotation) FileBytes() []byte
- func (a *FileAttachmentAnnotation) FileDescription() string
- func (a *FileAttachmentAnnotation) FileMIMEType() string
- func (a *FileAttachmentAnnotation) FileName() string
- func (a *FileAttachmentAnnotation) FileSize() int
- func (b *FileAttachmentAnnotation) Flatten() error
- func (a *FileAttachmentAnnotation) HasFile() bool
- func (a *FileAttachmentAnnotation) Icon() FileAttachmentIcon
- func (b *FileAttachmentAnnotation) PageIndex() int
- func (b *FileAttachmentAnnotation) Rect() Rectangle
- func (a *FileAttachmentAnnotation) RegenerateAppearance()
- func (a *FileAttachmentAnnotation) SetAFRelationship(r AFRelationship)
- func (b *FileAttachmentAnnotation) SetColor(c *Color)
- func (b *FileAttachmentAnnotation) SetContents(s string)
- func (a *FileAttachmentAnnotation) SetFile(path string) error
- func (a *FileAttachmentAnnotation) SetFileDescription(s string)
- func (a *FileAttachmentAnnotation) SetFileFromStream(r io.Reader, name string) error
- func (a *FileAttachmentAnnotation) SetIcon(i FileAttachmentIcon)
- func (b *FileAttachmentAnnotation) SetRect(r Rectangle)
- func (b *FileAttachmentAnnotation) SetTitle(s string)
- func (b *FileAttachmentAnnotation) Title() string
- type FileAttachmentIcon
- type FileDiffOutputGenerator
- type FileSelectBoxField
- func (b *FileSelectBoxField) Flatten() error
- func (b *FileSelectBoxField) FullName() string
- func (b *FileSelectBoxField) IsReadOnly() bool
- func (b *FileSelectBoxField) IsRequired() bool
- func (b *FileSelectBoxField) PageIndex() int
- func (b *FileSelectBoxField) PartialName() string
- func (b *FileSelectBoxField) Rect() Rectangle
- func (b *FileSelectBoxField) SetStyle(s FieldStyle) error
- func (b *FileSelectBoxField) Style() FieldStyle
- type FlattenTransparencyOptions
- type FloatSide
- type FloatingBox
- func (b *FloatingBox) AddHeading(level int, text string, style TextStyle) *FloatingBox
- func (b *FloatingBox) AddImage(path string, width, height float64) *FloatingBox
- func (b *FloatingBox) AddImageAlt(path string, width, height float64, alt string) *FloatingBox
- func (b *FloatingBox) AddList(items []string, ordered bool, style TextStyle) *FloatingBox
- func (b *FloatingBox) AddParagraph(text string, style TextStyle) *FloatingBox
- func (b *FloatingBox) AddSpacer(height float64) *FloatingBox
- func (b *FloatingBox) SetBackground(c *Color) *FloatingBox
- func (b *FloatingBox) SetBorder(border BorderInfo) *FloatingBox
- func (b *FloatingBox) SetPadding(m MarginInfo) *FloatingBox
- func (b *FloatingBox) SetSpacing(gap float64) *FloatingBox
- type Flow
- func (f *Flow) AddColumnBreak() *Flow
- func (f *Flow) AddFloatBox(box *FloatingBox, side FloatSide, width float64) *Flow
- func (f *Flow) AddFloatingBox(box *FloatingBox) *Flow
- func (f *Flow) AddHeading(level int, text string, style TextStyle) *Flow
- func (f *Flow) AddImage(path string, width, height float64) *Flow
- func (f *Flow) AddImageAlt(path string, width, height float64, alt string) *Flow
- func (f *Flow) AddList(items []string, ordered bool, style TextStyle) *Flow
- func (f *Flow) AddMarkdown(md string) *Flow
- func (f *Flow) AddParagraph(text string, style TextStyle) *Flow
- func (f *Flow) AddSpacer(height float64) *Flow
- func (f *Flow) AddTable(t *Table) *Flow
- func (f *Flow) Render() (int, error)
- func (f *Flow) SetMarkdownOptions(o MarkdownOptions) *Flow
- type FlowOptions
- type Font
- type FontMetrics
- type Form
- func (f *Form) AddBarcodeField(pageNum int, rect Rectangle, name string, symbology BarcodeSymbology, ...) (*BarcodeField, error)
- func (f *Form) AddCheckbox(pageNum int, rect Rectangle, name string) (*CheckboxField, error)
- func (f *Form) AddComboBox(pageNum int, rect Rectangle, name string, options []ChoiceOption) (*ComboBoxField, error)
- func (f *Form) AddDateField(pageNum int, rect Rectangle, name, format string) (*DateField, error)
- func (f *Form) AddFileSelectField(pageNum int, rect Rectangle, name string) (*FileSelectBoxField, error)
- func (f *Form) AddListBox(pageNum int, rect Rectangle, name string, options []ChoiceOption) (*ListBoxField, error)
- func (f *Form) AddNumberField(pageNum int, rect Rectangle, name string, opts NumberFormatOptions) (*NumberField, error)
- func (f *Form) AddPasswordField(pageNum int, rect Rectangle, name string) (*PasswordBoxField, error)
- func (f *Form) AddPushButton(pageNum int, rect Rectangle, name string, caption string) (*ButtonField, error)
- func (f *Form) AddRadioGroup(name string, items []RadioItem) (*RadioButtonField, error)
- func (f *Form) AddRichTextField(pageNum int, rect Rectangle, name string) (*RichTextBoxField, error)
- func (f *Form) AddTextField(pageNum int, rect Rectangle, name string) (*TextBoxField, error)
- func (f *Form) ExportFDF() ([]byte, error)
- func (f *Form) ExportJSON(opts ...JSONExportOptions) ([]byte, error)
- func (f *Form) ExportXFDF() ([]byte, error)
- func (f *Form) Field(name string) Field
- func (f *Form) Fields() []Field
- func (f *Form) Flatten() error
- func (f *Form) HasField(name string) bool
- func (f *Form) ImportFDF(data []byte) (int, error)
- func (f *Form) ImportJSON(data []byte) (int, error)
- func (f *Form) ImportXFDF(data []byte) (int, error)
- func (f *Form) NeedAppearances() bool
- func (f *Form) ReadFDF(r io.Reader) (int, error)
- func (f *Form) ReadJSON(r io.Reader) (int, error)
- func (f *Form) ReadXFDF(r io.Reader) (int, error)
- func (f *Form) RemoveField(name string) bool
- func (f *Form) SetNeedAppearances(v bool)
- func (f *Form) WriteFDF(w io.Writer) error
- func (f *Form) WriteJSON(w io.Writer, opts ...JSONExportOptions) error
- func (f *Form) WriteXFDF(w io.Writer) error
- type FormFieldType
- type FreeTextAnnotation
- func (a *FreeTextAnnotation) AnnotationType() AnnotationType
- func (a *FreeTextAnnotation) BorderEffect() BorderEffect
- func (a *FreeTextAnnotation) BorderEffectIntensity() float64
- func (d *FreeTextAnnotation) BorderStyle() BorderStyle
- func (d *FreeTextAnnotation) BorderWidth() float64
- func (a *FreeTextAnnotation) CalloutPoints() []Point
- func (a *FreeTextAnnotation) Contents() string
- func (d *FreeTextAnnotation) DashPattern() []float64
- func (a *FreeTextAnnotation) EndLineEnding() LineEndingStyle
- func (a *FreeTextAnnotation) InnerRect() Rectangle
- func (a *FreeTextAnnotation) Intent() FreeTextIntent
- func (a *FreeTextAnnotation) RegenerateAppearance()
- func (a *FreeTextAnnotation) SetBorderEffect(e BorderEffect)
- func (a *FreeTextAnnotation) SetBorderEffectIntensity(i float64)
- func (d *FreeTextAnnotation) SetBorderStyle(s BorderStyle)
- func (d *FreeTextAnnotation) SetBorderWidth(w float64)
- func (a *FreeTextAnnotation) SetCalloutPoints(pts []Point)
- func (d *FreeTextAnnotation) SetColor(c *Color)
- func (a *FreeTextAnnotation) SetContents(s string)
- func (d *FreeTextAnnotation) SetDashPattern(p []float64)
- func (a *FreeTextAnnotation) SetEndLineEnding(s LineEndingStyle)
- func (a *FreeTextAnnotation) SetInnerRect(inner Rectangle)
- func (a *FreeTextAnnotation) SetIntent(i FreeTextIntent)
- func (d *FreeTextAnnotation) SetRect(r Rectangle)
- func (a *FreeTextAnnotation) SetTextStyle(s TextStyle)
- func (a *FreeTextAnnotation) TextStyle() TextStyle
- type FreeTextIntent
- type GenericAnnotation
- func (a *GenericAnnotation) AnnotationType() AnnotationType
- func (b *GenericAnnotation) Color() *Color
- func (b *GenericAnnotation) Contents() string
- func (b *GenericAnnotation) Flatten() error
- func (b *GenericAnnotation) PageIndex() int
- func (b *GenericAnnotation) Rect() Rectangle
- func (b *GenericAnnotation) SetColor(c *Color)
- func (b *GenericAnnotation) SetContents(s string)
- func (b *GenericAnnotation) SetRect(r Rectangle)
- func (b *GenericAnnotation) SetTitle(s string)
- func (b *GenericAnnotation) Title() string
- type GifDevice
- type GoToAction
- type GoToURIAction
- type Gradient
- type GradientStop
- type GraphicalPdfComparer
- func (c *GraphicalPdfComparer) CompareDocumentsToPdf(doc1, doc2 *Document, outputPath string) error
- func (c *GraphicalPdfComparer) ComparePagesToImage(page1, page2 *Page, path string) error
- func (c *GraphicalPdfComparer) GetDifference(page1, page2 *Page) (*ImagesDifference, error)
- func (c *GraphicalPdfComparer) WriteDocumentsToPdf(doc1, doc2 *Document, w io.Writer) error
- func (c *GraphicalPdfComparer) WritePagesToImage(page1, page2 *Page, w io.Writer) error
- type HAlign
- type HTMLDiffOutputGenerator
- func (g *HTMLDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)
- func (g *HTMLDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)
- func (g *HTMLDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error
- func (g *HTMLDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error
- func (g *HTMLDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error
- func (g *HTMLDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
- type HTMLMode
- type HTMLSaveOptions
- type HiddenDataSanitizationOptions
- type HiddenDataSanitizationResult
- type HighlightAnnotation
- func (a *HighlightAnnotation) AnnotationType() AnnotationType
- func (m *HighlightAnnotation) QuadPoints() []QuadPoint
- func (a *HighlightAnnotation) RegenerateAppearance()
- func (m *HighlightAnnotation) SetColor(c *Color)
- func (m *HighlightAnnotation) SetQuadPoints(qp []QuadPoint)
- func (m *HighlightAnnotation) SetRect(r Rectangle)
- type Image
- type ImageColorSpace
- type ImageCompressionOptions
- type ImageFormat
- type ImageInfo
- type ImageStamp
- type ImageToDocumentOptions
- type ImagesDifference
- func (d *ImagesDifference) DestinationImage() image.Image
- func (d *ImagesDifference) DifferenceToImage(foreground, background Color) image.Image
- func (d *ImagesDifference) DifferentPixels() int
- func (d *ImagesDifference) HasDifferences() bool
- func (d *ImagesDifference) Ratio() float64
- func (d *ImagesDifference) SourceImage() image.Image
- func (d *ImagesDifference) TotalPixels() int
- type InkAnnotation
- func (a *InkAnnotation) AddStroke(stroke []Point)
- func (a *InkAnnotation) AnnotationType() AnnotationType
- func (d *InkAnnotation) BorderStyle() BorderStyle
- func (d *InkAnnotation) BorderWidth() float64
- func (d *InkAnnotation) DashPattern() []float64
- func (a *InkAnnotation) RegenerateAppearance()
- func (d *InkAnnotation) SetBorderStyle(s BorderStyle)
- func (a *InkAnnotation) SetBorderWidth(w float64)
- func (d *InkAnnotation) SetColor(c *Color)
- func (d *InkAnnotation) SetDashPattern(p []float64)
- func (d *InkAnnotation) SetRect(r Rectangle)
- func (a *InkAnnotation) SetStrokes(strokes [][]Point)
- func (a *InkAnnotation) Strokes() [][]Point
- type Invoice
- type InvoiceOptions
- type InvoiceProfile
- type JSONDiffOutputGenerator
- func (g *JSONDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)
- func (g *JSONDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)
- func (g *JSONDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error
- func (g *JSONDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error
- func (g *JSONDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error
- func (g *JSONDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
- type JSONExportOptions
- type JavaScriptAction
- type JavaScriptCollection
- func (c *JavaScriptCollection) Add(name, script string) error
- func (c *JavaScriptCollection) Clear()
- func (c *JavaScriptCollection) Count() int
- func (c *JavaScriptCollection) Get(name string) string
- func (c *JavaScriptCollection) Has(name string) bool
- func (c *JavaScriptCollection) Names() []string
- func (c *JavaScriptCollection) Remove(name string) bool
- type JpegDevice
- type Layer
- type LineAnnotation
- func (a *LineAnnotation) AnnotationType() AnnotationType
- func (d *LineAnnotation) BorderStyle() BorderStyle
- func (d *LineAnnotation) BorderWidth() float64
- func (d *LineAnnotation) DashPattern() []float64
- func (a *LineAnnotation) End() Point
- func (a *LineAnnotation) EndLineEnding() LineEndingStyle
- func (a *LineAnnotation) InteriorColor() *Color
- func (a *LineAnnotation) LeaderLineLength() float64
- func (a *LineAnnotation) RegenerateAppearance()
- func (d *LineAnnotation) SetBorderStyle(s BorderStyle)
- func (a *LineAnnotation) SetBorderWidth(w float64)
- func (d *LineAnnotation) SetColor(c *Color)
- func (d *LineAnnotation) SetDashPattern(p []float64)
- func (a *LineAnnotation) SetEnd(p Point)
- func (a *LineAnnotation) SetEndLineEnding(s LineEndingStyle)
- func (a *LineAnnotation) SetInteriorColor(c *Color)
- func (a *LineAnnotation) SetLeaderLineLength(l float64)
- func (d *LineAnnotation) SetRect(r Rectangle)
- func (a *LineAnnotation) SetStart(p Point)
- func (a *LineAnnotation) SetStartLineEnding(s LineEndingStyle)
- func (a *LineAnnotation) Start() Point
- func (a *LineAnnotation) StartLineEnding() LineEndingStyle
- type LineCap
- type LineEndingStyle
- type LineJoin
- type LineStyle
- type LinearGradient
- type LinkAnnotation
- func (a *LinkAnnotation) Action() Action
- func (a *LinkAnnotation) AnnotationType() AnnotationType
- func (a *LinkAnnotation) BorderWidth() float64
- func (b *LinkAnnotation) Color() *Color
- func (b *LinkAnnotation) Contents() string
- func (b *LinkAnnotation) Flatten() error
- func (a *LinkAnnotation) Highlight() LinkHighlightMode
- func (b *LinkAnnotation) PageIndex() int
- func (b *LinkAnnotation) Rect() Rectangle
- func (a *LinkAnnotation) SetAction(act Action)
- func (a *LinkAnnotation) SetBorderWidth(width float64)
- func (b *LinkAnnotation) SetColor(c *Color)
- func (b *LinkAnnotation) SetContents(s string)
- func (a *LinkAnnotation) SetHighlight(h LinkHighlightMode)
- func (b *LinkAnnotation) SetRect(r Rectangle)
- func (b *LinkAnnotation) SetTitle(s string)
- func (b *LinkAnnotation) Title() string
- type LinkHighlightMode
- type ListBoxField
- func (f *ListBoxField) AddOption(o ChoiceOption)
- func (b *ListBoxField) Flatten() error
- func (b *ListBoxField) FullName() string
- func (b *ListBoxField) IsReadOnly() bool
- func (b *ListBoxField) IsRequired() bool
- func (f *ListBoxField) MultiSelect() bool
- func (f *ListBoxField) Options() []ChoiceOption
- func (b *ListBoxField) PageIndex() int
- func (b *ListBoxField) PartialName() string
- func (b *ListBoxField) Rect() Rectangle
- func (f *ListBoxField) RemoveOption(index int) error
- func (f *ListBoxField) Selected() []int
- func (f *ListBoxField) SetMultiSelect(v bool)
- func (f *ListBoxField) SetReadOnly(v bool)
- func (f *ListBoxField) SetRequired(v bool)
- func (f *ListBoxField) SetSelected(indices ...int) error
- func (b *ListBoxField) SetStyle(s FieldStyle) error
- func (f *ListBoxField) SetValue(s string) error
- func (b *ListBoxField) Style() FieldStyle
- func (f *ListBoxField) Value() string
- type MarginInfo
- type MarkdownDiffOutputGenerator
- func (g *MarkdownDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)
- func (g *MarkdownDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)
- func (g *MarkdownDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error
- func (g *MarkdownDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error
- func (g *MarkdownDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error
- func (g *MarkdownDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
- type MarkdownOptions
- type MarkdownSaveOptions
- type MarkupParagraph
- type MarkupSection
- type MissingGlyphPolicy
- type NUpOptions
- type NUpOrder
- type NamedAction
- type NamedActionType
- type NamedDestination
- type NamedDestinations
- func (n *NamedDestinations) Add(name string, dest Destination) error
- func (n *NamedDestinations) All() map[string]Destination
- func (n *NamedDestinations) Clear()
- func (n *NamedDestinations) Count() int
- func (n *NamedDestinations) Document() *Document
- func (n *NamedDestinations) Get(name string) Destination
- func (n *NamedDestinations) Has(name string) bool
- func (n *NamedDestinations) Names() []string
- func (n *NamedDestinations) Remove(name string) bool
- type NumberField
- func (b *NumberField) Flatten() error
- func (b *NumberField) FullName() string
- func (b *NumberField) IsReadOnly() bool
- func (b *NumberField) IsRequired() bool
- func (b *NumberField) PageIndex() int
- func (b *NumberField) PartialName() string
- func (b *NumberField) Rect() Rectangle
- func (b *NumberField) SetStyle(s FieldStyle) error
- func (b *NumberField) Style() FieldStyle
- type NumberFormatOptions
- type Operation
- type OptimizationOptions
- type OptimizationResult
- type OptimizeImageOptions
- type OutlineItemCollection
- func (o *OutlineItemCollection) Action() Action
- func (o *OutlineItemCollection) Add(child *OutlineItemCollection) error
- func (o *OutlineItemCollection) All() []*OutlineItemCollection
- func (o *OutlineItemCollection) At(index int) *OutlineItemCollection
- func (o *OutlineItemCollection) Bold() bool
- func (o *OutlineItemCollection) Color() *Color
- func (o *OutlineItemCollection) Count() int
- func (o *OutlineItemCollection) Destination() Destination
- func (o *OutlineItemCollection) Document() *Document
- func (o *OutlineItemCollection) Insert(index int, child *OutlineItemCollection) error
- func (o *OutlineItemCollection) IsExpanded() bool
- func (o *OutlineItemCollection) Italic() bool
- func (o *OutlineItemCollection) Parent() *OutlineItemCollection
- func (o *OutlineItemCollection) Remove(child *OutlineItemCollection) bool
- func (o *OutlineItemCollection) RemoveAt(index int) error
- func (o *OutlineItemCollection) SetAction(a Action)
- func (o *OutlineItemCollection) SetBold(b bool)
- func (o *OutlineItemCollection) SetColor(c *Color)
- func (o *OutlineItemCollection) SetDestination(d Destination)
- func (o *OutlineItemCollection) SetIsExpanded(b bool)
- func (o *OutlineItemCollection) SetItalic(b bool)
- func (o *OutlineItemCollection) SetTitle(s string)
- func (o *OutlineItemCollection) Title() string
- type PDFAFormat
- type PDFAIssue
- type PDFAValidationReport
- type PDFDiffOutputGenerator
- func (g *PDFDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error
- func (g *PDFDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error
- func (g *PDFDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error
- func (g *PDFDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
- type PDFDiffReportOptions
- type PDFUAIssue
- type PDFUAValidationReport
- type Page
- func (p *Page) AddFloatingBox(box *FloatingBox, rect Rectangle) error
- func (p *Page) AddForm(form *XForm, rect Rectangle) error
- func (p *Page) AddImage(path string, rect Rectangle) error
- func (p *Page) AddImageFromStream(r io.Reader, rect Rectangle) error
- func (p *Page) AddInlineImage(path string, rect Rectangle) error
- func (p *Page) AddInlineImageFromStream(r io.Reader, rect Rectangle) error
- func (p *Page) AddMarkdown(md string, rect Rectangle, opts ...MarkdownOptions) error
- func (p *Page) AddSVG(path string, rect Rectangle) error
- func (p *Page) AddSVGFromStream(r io.Reader, rect Rectangle) error
- func (p *Page) AddSVGObject(svg *SVG, rect Rectangle) error
- func (p *Page) AddStamp(s Stamp) error
- func (p *Page) AddTOC(entries []TOCEntry, rect Rectangle, opts ...TOCOptions) (int, error)
- func (p *Page) AddTable(t *Table, rect Rectangle) (int, error)
- func (p *Page) AddTaggedList(tc *TaggedContent, parent *StructElement, items []string, style TextStyle, ...) (*StructElement, error)
- func (p *Page) AddTaggedTable(tc *TaggedContent, parent *StructElement, t *Table, rect Rectangle) (*StructElement, int, error)
- func (p *Page) AddText(text string, style TextStyle, rect Rectangle) error
- func (p *Page) AddTextAt(text string, style TextStyle, x, y float64) error
- func (p *Page) Annotations() *AnnotationCollection
- func (p *Page) ArtBox() (Rectangle, error)
- func (p *Page) BeginLayer(layer *Layer) error
- func (p *Page) BleedBox() (Rectangle, error)
- func (p *Page) CropBox() (Rectangle, error)
- func (p *Page) DrawCircle(center Point, radius float64, style ShapeStyle) error
- func (p *Page) DrawEllipse(center Point, rx, ry float64, style ShapeStyle) error
- func (p *Page) DrawLine(from, to Point, style LineStyle) error
- func (p *Page) DrawPath(path *Path, style ShapeStyle) error
- func (p *Page) DrawPolygon(points []Point, style ShapeStyle) error
- func (p *Page) DrawPolyline(points []Point, style LineStyle) error
- func (p *Page) DrawRectangle(rect Rectangle, style ShapeStyle) error
- func (p *Page) DrawRoundedRectangle(rect Rectangle, radius float64, style ShapeStyle) error
- func (p *Page) EndLayer() error
- func (p *Page) ExtractImages() ([]Image, error)
- func (p *Page) ExtractText(opts ...TextExtractOptions) (string, error)
- func (p *Page) ExtractTextWithLayout() ([]TextLine, error)
- func (p *Page) Forms() []*XForm
- func (p *Page) ImageInfos() ([]ImageInfo, error)
- func (p *Page) Label() string
- func (p *Page) MediaBox() (Rectangle, error)
- func (p *Page) Number() int
- func (p *Page) Paragraphs() (PageMarkup, error)
- func (p *Page) RenderBMP(w io.Writer, opts RenderOptions) error
- func (p *Page) RenderGIF(w io.Writer, opts RenderOptions) error
- func (p *Page) RenderImage(opts RenderOptions) (image.Image, error)
- func (p *Page) RenderJPEG(w io.Writer, opts RenderOptions, quality int) error
- func (p *Page) RenderPNG(w io.Writer, opts RenderOptions) error
- func (p *Page) RenderTIFF(w io.Writer, opts RenderOptions) error
- func (p *Page) ReplaceText(old, replacement string, opts ...ReplaceOptions) (int, error)
- func (p *Page) Rotation() RotationAngle
- func (p *Page) SaveSVG(path string, opts ...SVGSaveOptions) error
- func (p *Page) SearchText(query string, opts ...SearchOptions) ([]TextMatch, error)
- func (p *Page) SetArtBox(rect Rectangle) error
- func (p *Page) SetBleedBox(rect Rectangle) error
- func (p *Page) SetCropBox(rect Rectangle) error
- func (p *Page) SetMediaBox(rect Rectangle) error
- func (p *Page) SetPageSize(width, height float64) error
- func (p *Page) SetTrimBox(rect Rectangle) error
- func (p *Page) Size() (PageSize, error)
- func (p *Page) TagArtifact(draw func() error) error
- func (p *Page) TagContent(parent *StructElement, t StructType, draw func() error) (*StructElement, error)
- func (p *Page) TrimBox() (Rectangle, error)
- func (p *Page) WriteSVG(w io.Writer, opts ...SVGSaveOptions) error
- type PageFormat
- type PageLabelRange
- type PageLabelStyle
- type PageMarkup
- type PageNumberStamp
- type PageRange
- type PageSize
- type PasswordBoxField
- func (b *PasswordBoxField) Flatten() error
- func (b *PasswordBoxField) FullName() string
- func (b *PasswordBoxField) IsReadOnly() bool
- func (b *PasswordBoxField) IsRequired() bool
- func (b *PasswordBoxField) PageIndex() int
- func (b *PasswordBoxField) PartialName() string
- func (b *PasswordBoxField) Rect() Rectangle
- func (b *PasswordBoxField) SetStyle(s FieldStyle) error
- func (b *PasswordBoxField) Style() FieldStyle
- type Path
- type PdfPageStamp
- type Permissions
- type PngDevice
- type Point
- type PolygonAnnotation
- func (a *PolygonAnnotation) AnnotationType() AnnotationType
- func (a *PolygonAnnotation) InteriorColor() *Color
- func (a *PolygonAnnotation) RegenerateAppearance()
- func (a *PolygonAnnotation) SetBorderWidth(w float64)
- func (a *PolygonAnnotation) SetInteriorColor(c *Color)
- func (a *PolygonAnnotation) SetVertices(v []Point)
- func (a *PolygonAnnotation) Vertices() []Point
- type PolylineAnnotation
- func (a *PolylineAnnotation) AnnotationType() AnnotationType
- func (a *PolylineAnnotation) EndLineEnding() LineEndingStyle
- func (a *PolylineAnnotation) InteriorColor() *Color
- func (a *PolylineAnnotation) RegenerateAppearance()
- func (a *PolylineAnnotation) SetBorderWidth(w float64)
- func (a *PolylineAnnotation) SetEndLineEnding(s LineEndingStyle)
- func (a *PolylineAnnotation) SetInteriorColor(c *Color)
- func (a *PolylineAnnotation) SetStartLineEnding(s LineEndingStyle)
- func (a *PolylineAnnotation) SetVertices(v []Point)
- func (a *PolylineAnnotation) StartLineEnding() LineEndingStyle
- func (a *PolylineAnnotation) Vertices() []Point
- type QuadPoint
- type RadialGradient
- type RadioButtonField
- func (b *RadioButtonField) Flatten() error
- func (b *RadioButtonField) FullName() string
- func (b *RadioButtonField) IsReadOnly() bool
- func (b *RadioButtonField) IsRequired() bool
- func (f *RadioButtonField) Options() []*RadioButtonOptionField
- func (b *RadioButtonField) PageIndex() int
- func (b *RadioButtonField) PartialName() string
- func (b *RadioButtonField) Rect() Rectangle
- func (f *RadioButtonField) SetReadOnly(v bool)
- func (f *RadioButtonField) SetRequired(v bool)
- func (b *RadioButtonField) SetStyle(s FieldStyle) error
- func (f *RadioButtonField) SetValue(s string) error
- func (b *RadioButtonField) Style() FieldStyle
- func (f *RadioButtonField) Value() string
- type RadioButtonOptionField
- type RadioItem
- type Recipient
- type Rectangle
- type RedactAnnotation
- func (a *RedactAnnotation) AnnotationType() AnnotationType
- func (d *RedactAnnotation) BorderStyle() BorderStyle
- func (d *RedactAnnotation) BorderWidth() float64
- func (d *RedactAnnotation) DashPattern() []float64
- func (a *RedactAnnotation) InteriorColor() *Color
- func (a *RedactAnnotation) OverlayText() string
- func (a *RedactAnnotation) OverlayTextStyle() TextStyle
- func (a *RedactAnnotation) QuadPoints() []QuadPoint
- func (a *RedactAnnotation) RegenerateAppearance()
- func (a *RedactAnnotation) RepeatOverlayText() bool
- func (d *RedactAnnotation) SetBorderStyle(s BorderStyle)
- func (d *RedactAnnotation) SetBorderWidth(w float64)
- func (d *RedactAnnotation) SetColor(c *Color)
- func (d *RedactAnnotation) SetDashPattern(p []float64)
- func (a *RedactAnnotation) SetInteriorColor(c *Color)
- func (a *RedactAnnotation) SetOverlayText(s string)
- func (a *RedactAnnotation) SetOverlayTextStyle(s TextStyle)
- func (a *RedactAnnotation) SetQuadPoints(qp []QuadPoint)
- func (d *RedactAnnotation) SetRect(r Rectangle)
- func (a *RedactAnnotation) SetRepeatOverlayText(repeat bool)
- type RenderOptions
- type RepairReport
- type ReplaceOptions
- type ResetFormAction
- type Resolution
- type RevocationCheck
- type RevocationFetcher
- type RevocationSource
- type RevocationState
- type RevocationStatus
- type RichTextBoxField
- func (b *RichTextBoxField) Flatten() error
- func (b *RichTextBoxField) FullName() string
- func (b *RichTextBoxField) IsReadOnly() bool
- func (b *RichTextBoxField) IsRequired() bool
- func (b *RichTextBoxField) PageIndex() int
- func (b *RichTextBoxField) PartialName() string
- func (b *RichTextBoxField) Rect() Rectangle
- func (r *RichTextBoxField) RichValue() string
- func (r *RichTextBoxField) SetRichValue(rv, plain string) error
- func (b *RichTextBoxField) SetStyle(s FieldStyle) error
- func (b *RichTextBoxField) Style() FieldStyle
- type RotationAngle
- type Row
- func (r *Row) AddCell(text string) *Cell
- func (r *Row) AddCells(texts ...string) []*Cell
- func (r *Row) Background() *Color
- func (r *Row) Border() *BorderInfo
- func (r *Row) CellCount() int
- func (r *Row) Cells() []*Cell
- func (r *Row) Height() float64
- func (r *Row) Margin() *MarginInfo
- func (r *Row) SetBackground(col *Color) *Row
- func (r *Row) SetBorder(b BorderInfo) *Row
- func (r *Row) SetHeight(h float64) *Row
- func (r *Row) SetMargin(m MarginInfo) *Row
- func (r *Row) SetTextStyle(s TextStyle) *Row
- func (r *Row) Table() *Table
- func (r *Row) TextStyle() *TextStyle
- type SVG
- type SVGFontResolver
- type SVGSaveOptions
- type SearchOptions
- type ShapeStyle
- type SideBySideComparisonOptions
- type SideBySideDocsComparisonResult
- type SideBySidePagesComparisonResult
- type SignOptions
- type SignatureAppearance
- type SignatureVerification
- type SquareAnnotation
- func (a *SquareAnnotation) AnnotationType() AnnotationType
- func (d *SquareAnnotation) BorderStyle() BorderStyle
- func (d *SquareAnnotation) BorderWidth() float64
- func (d *SquareAnnotation) DashPattern() []float64
- func (a *SquareAnnotation) InteriorColor() *Color
- func (a *SquareAnnotation) RegenerateAppearance()
- func (d *SquareAnnotation) SetBorderStyle(s BorderStyle)
- func (d *SquareAnnotation) SetBorderWidth(w float64)
- func (d *SquareAnnotation) SetColor(c *Color)
- func (d *SquareAnnotation) SetDashPattern(p []float64)
- func (a *SquareAnnotation) SetInteriorColor(c *Color)
- func (d *SquareAnnotation) SetRect(r Rectangle)
- type SquigglyAnnotation
- func (a *SquigglyAnnotation) AnnotationType() AnnotationType
- func (m *SquigglyAnnotation) QuadPoints() []QuadPoint
- func (a *SquigglyAnnotation) RegenerateAppearance()
- func (m *SquigglyAnnotation) SetColor(c *Color)
- func (m *SquigglyAnnotation) SetQuadPoints(qp []QuadPoint)
- func (m *SquigglyAnnotation) SetRect(r Rectangle)
- type Stamp
- type StampAnnotation
- func (a *StampAnnotation) AnnotationType() AnnotationType
- func (d *StampAnnotation) BorderStyle() BorderStyle
- func (d *StampAnnotation) BorderWidth() float64
- func (a *StampAnnotation) ClearCustomImage()
- func (d *StampAnnotation) DashPattern() []float64
- func (a *StampAnnotation) HasCustomImage() bool
- func (a *StampAnnotation) Name() StampName
- func (a *StampAnnotation) RawName() string
- func (a *StampAnnotation) RegenerateAppearance()
- func (d *StampAnnotation) SetBorderStyle(s BorderStyle)
- func (d *StampAnnotation) SetBorderWidth(w float64)
- func (d *StampAnnotation) SetColor(c *Color)
- func (a *StampAnnotation) SetCustomImage(path string) error
- func (a *StampAnnotation) SetCustomImageFromStream(r io.Reader) error
- func (d *StampAnnotation) SetDashPattern(p []float64)
- func (a *StampAnnotation) SetName(n StampName)
- func (a *StampAnnotation) SetRawName(s string)
- func (d *StampAnnotation) SetRect(r Rectangle)
- type StampName
- type StrikeOutAnnotation
- func (a *StrikeOutAnnotation) AnnotationType() AnnotationType
- func (m *StrikeOutAnnotation) QuadPoints() []QuadPoint
- func (a *StrikeOutAnnotation) RegenerateAppearance()
- func (m *StrikeOutAnnotation) SetColor(c *Color)
- func (m *StrikeOutAnnotation) SetQuadPoints(qp []QuadPoint)
- func (m *StrikeOutAnnotation) SetRect(r Rectangle)
- type StringDiffOutputGenerator
- type StructElement
- type StructType
- type SubmitFormAction
- func (a *SubmitFormAction) ActionType() ActionType
- func (a *SubmitFormAction) FieldNames() []string
- func (a *SubmitFormAction) Flags() SubmitFormFlags
- func (a *SubmitFormAction) SetFieldNames(f []string)
- func (a *SubmitFormAction) SetFlags(f SubmitFormFlags)
- func (a *SubmitFormAction) SetURL(u string)
- func (a *SubmitFormAction) URL() string
- type SubmitFormFlags
- type TOCEntry
- type TOCOptions
- type Table
- func (t *Table) AddRow() *Row
- func (t *Table) AddRows(rows [][]string) []*Row
- func (t *Table) Border() BorderInfo
- func (t *Table) ColumnWidths() []float64
- func (t *Table) DefaultCellBorder() BorderInfo
- func (t *Table) DefaultCellMargin() MarginInfo
- func (t *Table) DefaultCellStyle() TextStyle
- func (t *Table) OverflowMargins() (top, bottom float64)
- func (t *Table) RepeatingRowsCount() int
- func (t *Table) RowCount() int
- func (t *Table) Rows() []*Row
- func (t *Table) SetBorder(b BorderInfo) *Table
- func (t *Table) SetColumnWidths(widths []float64) *Table
- func (t *Table) SetDefaultCellBorder(b BorderInfo) *Table
- func (t *Table) SetDefaultCellMargin(m MarginInfo) *Table
- func (t *Table) SetDefaultCellStyle(s TextStyle) *Table
- func (t *Table) SetOverflowMargins(top, bottom float64) *Table
- func (t *Table) SetRepeatingRowsCount(n int) *Table
- type TableAbsorber
- type TaggedContent
- type TextAnnotation
- func (a *TextAnnotation) AnnotationType() AnnotationType
- func (b *TextAnnotation) Color() *Color
- func (b *TextAnnotation) Contents() string
- func (b *TextAnnotation) Flatten() error
- func (a *TextAnnotation) Icon() TextIcon
- func (a *TextAnnotation) Open() bool
- func (b *TextAnnotation) PageIndex() int
- func (b *TextAnnotation) Rect() Rectangle
- func (a *TextAnnotation) RegenerateAppearance()
- func (b *TextAnnotation) SetColor(c *Color)
- func (b *TextAnnotation) SetContents(s string)
- func (a *TextAnnotation) SetIcon(t TextIcon)
- func (a *TextAnnotation) SetOpen(open bool)
- func (b *TextAnnotation) SetRect(r Rectangle)
- func (b *TextAnnotation) SetTitle(s string)
- func (b *TextAnnotation) Title() string
- type TextBoxField
- func (b *TextBoxField) Flatten() error
- func (b *TextBoxField) FullName() string
- func (f *TextBoxField) IsMultiline() bool
- func (f *TextBoxField) IsPassword() bool
- func (b *TextBoxField) IsReadOnly() bool
- func (b *TextBoxField) IsRequired() bool
- func (f *TextBoxField) MaxLen() int
- func (b *TextBoxField) PageIndex() int
- func (b *TextBoxField) PartialName() string
- func (b *TextBoxField) Rect() Rectangle
- func (f *TextBoxField) SetMaxLen(n int)
- func (f *TextBoxField) SetMultiline(v bool)
- func (f *TextBoxField) SetPassword(v bool)
- func (f *TextBoxField) SetReadOnly(v bool)
- func (f *TextBoxField) SetRequired(v bool)
- func (b *TextBoxField) SetStyle(s FieldStyle) error
- func (f *TextBoxField) SetValue(s string) error
- func (b *TextBoxField) Style() FieldStyle
- func (f *TextBoxField) Value() string
- type TextExtractOptions
- type TextExtractionMode
- type TextFragment
- type TextIcon
- type TextLine
- type TextMatch
- type TextStamp
- type TextStyle
- type TiffDevice
- type TilingPattern
- type Type3Font
- type UnderlineAnnotation
- func (a *UnderlineAnnotation) AnnotationType() AnnotationType
- func (m *UnderlineAnnotation) QuadPoints() []QuadPoint
- func (a *UnderlineAnnotation) RegenerateAppearance()
- func (m *UnderlineAnnotation) SetColor(c *Color)
- func (m *UnderlineAnnotation) SetQuadPoints(qp []QuadPoint)
- func (m *UnderlineAnnotation) SetRect(r Rectangle)
- type VAlign
- type ValidationIssue
- type ValidationOptions
- type ValidationReport
- type WidgetAnnotation
- func (a *WidgetAnnotation) AnnotationType() AnnotationType
- func (b *WidgetAnnotation) Color() *Color
- func (b *WidgetAnnotation) Contents() string
- func (b *WidgetAnnotation) Flatten() error
- func (b *WidgetAnnotation) PageIndex() int
- func (b *WidgetAnnotation) Rect() Rectangle
- func (b *WidgetAnnotation) SetColor(c *Color)
- func (b *WidgetAnnotation) SetContents(s string)
- func (b *WidgetAnnotation) SetRect(r Rectangle)
- func (b *WidgetAnnotation) SetTitle(s string)
- func (b *WidgetAnnotation) Title() string
- type XForm
- type XMPMetadata
- type XMPProperty
- type XlsxRecognitionMode
- type XlsxSaveOptions
Examples ¶
- Document.AddSVGWatermark
- Document.AddTextWatermark
- Document.Append
- Document.Extract
- Document.ExtractText
- Document.FlattenTransparency
- Document.GenerateTOC
- Document.NewFlow
- Document.Optimize
- Document.Outlines
- Document.RenderImage
- Document.ReplaceText
- Document.Rotate
- Document.SetEncryption
- Document.SetPageLabels
- Document.Sign
- Document.Split
- Document.WriteHTML
- Document.WriteMarkdown
- Form.AddBarcodeField
- Form.AddTextField
- ImageToDocument
- MarkdownToDocumentFromStream
- NewDocumentFromFormat
- NewLinkAnnotation
- NewTable
- Open
- OpenWithPassword
- Page.AddImage
- Page.AddText
- Page.DrawRectangle
- Page.SearchText
- Page.WriteSVG
- Validate
Constants ¶
const DefaultDPI = 150
DefaultDPI is the rendering resolution used when RenderOptions.DPI is unset. 150 matches Aspose.PDF for .NET's default Resolution.
Variables ¶
var ( PageFormatA3 = PageFormat{Width: 842, Height: 1191} PageFormatA4 = PageFormat{Width: 595, Height: 842} PageFormatLetter = PageFormat{Width: 612, Height: 792} PageFormatLegal = PageFormat{Width: 612, Height: 1008} )
Predefined page formats (portrait orientation).
var ErrEncrypted = errors.New("PDF is encrypted; use OpenWithPassword")
ErrEncrypted is returned by Open / OpenStream when the input PDF carries an /Encrypt dictionary. Callers should retry with OpenWithPassword or OpenStreamWithPassword to supply a user or owner password.
var ErrInvalidPassword = errors.New("invalid password")
ErrInvalidPassword is returned by OpenWithPassword / OpenStreamWithPassword when the supplied password matches neither the user nor the owner password of the file. Mirrors Aspose.PDF for .NET's InvalidPasswordException.
Functions ¶
func AddFontFile ¶ added in v0.3.0
func AddFontFile(path string)
AddFontFile registers a single font file. Mirrors a FileFontSource.
func AddFontFolder ¶ added in v0.3.0
func AddFontFolder(path string)
AddFontFolder registers a directory searched (recursively) for fonts when rendering. Mirrors adding a FolderFontSource in Aspose.PDF for .NET.
func AddSystemFonts ¶ added in v0.3.0
func AddSystemFonts()
AddSystemFonts registers the operating system's standard font directories. Mirrors adding a SystemFontSource. Not enabled by default — call it to let the renderer use installed fonts (e.g. real Arial / Times New Roman).
func AssembleDestinationText ¶ added in v0.9.0
func AssembleDestinationText(ops []DiffOperation) string
AssembleDestinationText rebuilds the second document's text — everything equal plus everything inserted. Mirrors Aspose.PDF for .NET's TextPdfComparer.AssemblyDestinationPageText. With ComparisonOptions.IgnoreCase set, equal runs carry the first document's spelling, so the result can differ from the second document in letter case.
func AssembleSourceText ¶ added in v0.9.0
func AssembleSourceText(ops []DiffOperation) string
AssembleSourceText rebuilds the first document's text from the operations — everything equal plus everything deleted. Mirrors Aspose.PDF for .NET's TextPdfComparer.AssemblySourcePageText.
func ClearFontSources ¶ added in v0.3.0
func ClearFontSources()
ClearFontSources removes all registered folders and files.
func Encrypt ¶
Encrypt writes a password-protected copy of inputPath to outputPath. The document is encrypted using RC4-128 (PDF 1.4 Standard Security Handler, revision 3). userPassword is required to open the document; ownerPassword controls permission settings. If ownerPassword is empty, it defaults to userPassword.
Example:
err := asposepdf.Encrypt("input.pdf", "output.pdf", "secret", "")
func MeasureText ¶ added in v0.13.0
MeasureText returns the width in points of text drawn as a single line with style, using the same font resolution, Arabic/bidi reordering and OpenType shaping AddTextAt applies — so a caller doing its own line-breaking can measure a candidate line exactly the way it would be drawn. Unlike AddText's own internal wrapping measurement, whitespace in text is never collapsed. style.Font nil defaults to FontHelvetica, style.Size 0 to 12, matching AddText/AddTextAt.
Types ¶
type AFRelationship ¶ added in v0.10.0
type AFRelationship int
AFRelationship says how an embedded file relates to the document. Mirrors Aspose.PDF for .NET's AFRelationship.
const ( // AFUnspecified states no particular relationship. The zero value, and // what a file with no /AFRelationship reports. AFUnspecified AFRelationship = iota // AFSource is the original the document was produced from. AFSource // AFData is data the document's content is built on, such as the table // behind a chart. AFData // AFAlternative is an alternative representation of the content, such as // the XML of a hybrid e-invoice. AFAlternative // AFSupplement is a supplemental representation of the content. AFSupplement )
func (AFRelationship) String ¶ added in v0.10.0
func (r AFRelationship) String() string
String names the relationship as PDF writes it, without the slash.
type AbsorbedCell ¶ added in v0.7.0
type AbsorbedCell struct {
// Rect is the cell's rectangle (the full span for spanning cells;
// covered positions carry the covering cell's rectangle).
Rect Rectangle
// RowSpan/ColSpan are >= 1 on a cell's anchor position.
RowSpan, ColSpan int
// Covered marks a position occupied by another cell's span.
Covered bool
// Shading is the cell's background fill colour, when the page paints one.
Shading *Color
// contains filtered or unexported fields
}
AbsorbedCell is one logical grid position.
func (*AbsorbedCell) Text ¶ added in v0.7.0
func (c *AbsorbedCell) Text() string
Text returns the cell's text: fragments grouped into visual lines, lines joined with newlines, gap-separated fragments with spaces.
func (*AbsorbedCell) TextFragments ¶ added in v0.7.0
func (c *AbsorbedCell) TextFragments() []TextFragment
TextFragments returns the text fragments inside the cell.
type AbsorbedRow ¶ added in v0.7.0
type AbsorbedRow struct {
Rect Rectangle
// contains filtered or unexported fields
}
AbsorbedRow is one logical table row.
func (*AbsorbedRow) CellList ¶ added in v0.7.0
func (r *AbsorbedRow) CellList() []*AbsorbedCell
CellList returns the row's cells, left-to-right (one per logical column; positions covered by a span carry Covered=true).
type AbsorbedTable ¶ added in v0.7.0
type AbsorbedTable struct {
// Rect is the table's bounding rectangle in PDF user space.
Rect Rectangle
// PageNumber is the 1-based source page.
PageNumber int
// contains filtered or unexported fields
}
AbsorbedTable is one recognized table.
func (*AbsorbedTable) RowList ¶ added in v0.7.0
func (t *AbsorbedTable) RowList() []*AbsorbedRow
RowList returns the table's rows, top-to-bottom.
type Action ¶
type Action interface {
ActionType() ActionType
// contains filtered or unexported methods
}
Action is the common interface implemented by every concrete action type. Action values are inline within the parent annotation's /A dict — they are not separately addressable PDF objects.
type ActionType ¶
type ActionType int
ActionType identifies the kind of action attached to an annotation (typically a LinkAnnotation's /A entry).
const ( ActionTypeUnknown ActionType = iota ActionTypeGoToURI ActionTypeGoTo ActionTypeNamed ActionTypeSubmitForm ActionTypeResetForm ActionTypeJavaScript )
type Annotation ¶
type Annotation interface {
AnnotationType() AnnotationType
Rect() Rectangle
SetRect(r Rectangle)
Color() *Color
SetColor(c *Color)
Title() string
SetTitle(s string)
Contents() string
SetContents(s string)
PageIndex() int
// Flatten bakes this annotation's normal appearance into the page
// content and removes the annotation, making it non-interactive. See
// (*annotationBase).Flatten in flatten.go.
Flatten() error
// contains filtered or unexported methods
}
Annotation is the common interface implemented by every concrete annotation type. Page-scoped — annotations belong to a specific page and are managed through that page's AnnotationCollection.
type AnnotationCollection ¶
type AnnotationCollection struct {
// contains filtered or unexported fields
}
AnnotationCollection is the live, ordered set of annotations attached to a single page. Mutations through Add / Delete propagate to the page dict's /Annots array and to the document's object table; the next Save writes them out.
func (*AnnotationCollection) Add ¶
func (c *AnnotationCollection) Add(a Annotation) error
Add attaches an annotation to this page. Errors if the annotation is already attached to a different page; idempotent same-page Add returns nil. Panics on nil annotation (programmer error).
func (*AnnotationCollection) All ¶
func (c *AnnotationCollection) All() []Annotation
All returns the page's annotations as a slice. Each Annotation in the slice is a live handle: mutations write through to the underlying pdfDict and are visible to callers holding the same handle.
func (*AnnotationCollection) At ¶
func (c *AnnotationCollection) At(index int) Annotation
At returns the annotation at the given index. Panics if out of range.
func (*AnnotationCollection) Count ¶
func (c *AnnotationCollection) Count() int
Count reports how many annotations live on this page.
func (*AnnotationCollection) Delete ¶
func (c *AnnotationCollection) Delete(a Annotation) bool
Delete removes the annotation from this page. Returns true if found, false otherwise. The annotation handle becomes dangling after Delete: mutations through it write to an unlinked dict that is no longer reachable from the document and are silently dropped on next Save.
func (*AnnotationCollection) DeleteAt ¶
func (c *AnnotationCollection) DeleteAt(index int) error
DeleteAt removes the annotation at the given index. Errors on out-of-range index. The annotation handle becomes dangling after DeleteAt — see Delete for the dangling-handle semantics.
func (*AnnotationCollection) Flatten ¶ added in v0.3.0
func (c *AnnotationCollection) Flatten() error
Flatten bakes every annotation on the page into the page content and removes it. Widget annotations (form-field widgets) are skipped — flatten those via (*Document).Flatten or (*Form).Flatten so the /AcroForm is cleaned up too.
type AnnotationType ¶
type AnnotationType int
AnnotationType identifies the kind of annotation. Returned by Annotation.AnnotationType() so callers can switch on type without a type-assertion ladder.
const ( AnnotationTypeUnknown AnnotationType = iota AnnotationTypeLink AnnotationTypeHighlight AnnotationTypeUnderline AnnotationTypeStrikeOut AnnotationTypeSquiggly AnnotationTypeWidget AnnotationTypeSquare AnnotationTypeCircle AnnotationTypeLine AnnotationTypeInk AnnotationTypeText AnnotationTypeFreeText AnnotationTypeStamp AnnotationTypeFileAttachment AnnotationTypeRedact AnnotationTypePolygon AnnotationTypePolyLine AnnotationTypeCaret )
type BarcodeField ¶ added in v0.10.0
type BarcodeField struct{ TextBoxField }
BarcodeField draws its value as a barcode symbol. Value()/SetValue() (inherited from TextBoxField) get/set the encoded text; every value change re-renders the widget's /AP. Bar colour and background reuse FieldStyle.TextColor / BackgroundColor via SetStyle — there is no separate "ForegroundColor" on this type. Unlike other field types, BarcodeField draws no default border or background fill (a barcode's quiet zone must stay open), so both stay transparent unless SetStyle sets them explicitly.
func (*BarcodeField) Flatten ¶ added in v0.10.0
func (b *BarcodeField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*BarcodeField) IsReadOnly ¶ added in v0.10.0
func (b *BarcodeField) IsReadOnly() bool
func (*BarcodeField) IsRequired ¶ added in v0.10.0
func (b *BarcodeField) IsRequired() bool
func (*BarcodeField) PartialName ¶ added in v0.10.0
func (b *BarcodeField) PartialName() string
func (*BarcodeField) SetStyle ¶ added in v0.10.0
func (b *BarcodeField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*BarcodeField) SetSymbology ¶ added in v0.10.0
func (bc *BarcodeField) SetSymbology(s BarcodeSymbology) error
SetSymbology changes the barcode encoding and re-renders the appearance. Errors (leaving the field unchanged) if the field's current value cannot be encoded under the new symbology.
func (*BarcodeField) SetValue ¶ added in v0.10.0
func (bc *BarcodeField) SetValue(value string) error
SetValue validates that value encodes under the field's current symbology before writing it (leaving the field unchanged on error), then re-renders the barcode appearance.
func (*BarcodeField) Style ¶ added in v0.10.0
func (b *BarcodeField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
func (*BarcodeField) Symbology ¶ added in v0.10.0
func (bc *BarcodeField) Symbology() BarcodeSymbology
Symbology returns the field's barcode encoding.
type BarcodeSymbology ¶ added in v0.10.0
type BarcodeSymbology int
BarcodeSymbology identifies which barcode encoding a BarcodeField draws.
const ( BarcodeSymbologyUnknown BarcodeSymbology = iota // BarcodeCode128 encodes printable ASCII (0x20-0x7E) via Code Set B // (ISO/IEC 15417). Non-ASCII text is rejected — use BarcodeQR instead. BarcodeCode128 // BarcodeQR encodes arbitrary text as its UTF-8 bytes in QR byte mode // (ISO/IEC 18004), error-correction level M, version chosen // automatically (1-40). BarcodeQR // BarcodePDF417 encodes arbitrary text as its UTF-8 bytes in PDF417 // byte compaction (ISO/IEC 15438), with an ECI 000026 designator when // the text is not pure ASCII. The error-correction level follows ISO's // recommendation for the data size and the column count is chosen to // approach the widget rectangle's proportions. Up to 929 codewords // (roughly 1,100 bytes) fit in one symbol. BarcodePDF417 )
type BmpDevice ¶ added in v0.3.0
type BmpDevice struct {
// contains filtered or unexported fields
}
BmpDevice renders a page to BMP. Mirrors Aspose.PDF for .NET's BmpDevice.
func NewBmpDevice ¶ added in v0.3.0
func NewBmpDevice(res Resolution) *BmpDevice
NewBmpDevice returns a BmpDevice for the given resolution.
type BookletBinding ¶ added in v0.4.0
type BookletBinding int
BookletBinding selects the binding edge of a booklet.
const ( // BindingLeft places the lower page number on the right (LTR reading). BindingLeft BookletBinding = iota // BindingRight mirrors the spreads for right-to-left binding. BindingRight )
type BookletOptions ¶ added in v0.4.0
type BookletOptions struct {
// PageSize is the output sheet (a two-page spread). The zero value uses
// twice the width by the height of the document's first page, so the
// source pages are placed at 100% with no scaling.
PageSize PageFormat
// Binding selects the binding edge (left by default).
Binding BookletBinding
}
BookletOptions configures Booklet imposition.
type BorderEffect ¶
type BorderEffect int
BorderEffect controls the /BE/S entry per ISO 32000-1 §12.5.4 Table 167.
const ( BorderEffectNone BorderEffect = iota // /S = /S (default) BorderEffectCloudy // /S = /C — wavy "cloud" border )
type BorderInfo ¶
type BorderInfo struct {
Sides BorderSide
Width float64 // in points; 0 means no border regardless of Sides
Color *Color // nil → black (R:0 G:0 B:0 A:1)
}
BorderInfo describes a border drawn around a table or cell. Mirrors Aspose.PDF for .NET's BorderInfo. Zero value means "no border".
type BorderSide ¶
type BorderSide int
BorderSide is a bitmask selecting which sides of a rectangular border are drawn.
const ( BorderSideNone BorderSide = 0 BorderSideTop BorderSide = 1 BorderSideRight BorderSide = 2 BorderSideBottom BorderSide = 4 BorderSideLeft BorderSide = 8 BorderSideAll = BorderSideTop | BorderSideRight | BorderSideBottom | BorderSideLeft )
type BorderStyle ¶
type BorderStyle int
BorderStyle controls the /BS dict for drawing annotations per ISO 32000-1 §12.5.4 Table 168.
const ( BorderSolid BorderStyle = iota // /S = /S BorderDashed // /S = /D + /D dash array BorderBeveled // /S = /B (3D raised effect) BorderInset // /S = /I (3D recessed effect) BorderUnderline // /S = /U (only the bottom edge) )
type ButtonAppearance ¶ added in v0.3.0
type ButtonAppearance struct {
Caption string // /MK/CA — normal-state caption
RolloverText string // /MK/RC — caption while hovered (falls back to Caption)
DownText string // /MK/AC — caption while pressed (falls back to Caption)
IconPath string // optional icon image (PNG/JPEG), baked into the /AP streams
IconPosition ButtonIconPosition // /MK/TP — icon vs caption layout
TextColor *Color // caption colour (default dark grey)
FaceColor *Color // button face fill (default light grey)
BorderColor *Color // button border (default grey)
}
ButtonAppearance configures a push button's rich appearance: separate captions for the normal / rollover / down states, an optional icon image, and face/border/text colours. Applied via (*ButtonField).SetAppearance, which writes the /MK appearance- characteristics dict and bakes /AP/N, /AP/R, and /AP/D appearance streams so the button reacts to hover and press in every viewer.
Out of scope (follow-up): caption rotation (/MK/R) and exposing the icon as a /MK/I Form XObject for viewer-side regeneration — the icon is rendered directly into the /AP streams here, which renders in any viewer without relying on regeneration.
type ButtonField ¶
type ButtonField struct {
// contains filtered or unexported fields
}
ButtonField is a push button — action only, no value semantics.
func (*ButtonField) Action ¶ added in v0.5.0
func (f *ButtonField) Action() Action
Action returns the button's activation action (/A on its widget), or nil if none is set or the action type is unsupported. Mirrors the LinkAnnotation action surface.
func (*ButtonField) Flatten ¶ added in v0.3.0
func (b *ButtonField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*ButtonField) IsReadOnly ¶
func (b *ButtonField) IsReadOnly() bool
func (*ButtonField) IsRequired ¶
func (b *ButtonField) IsRequired() bool
func (*ButtonField) PartialName ¶
func (b *ButtonField) PartialName() string
func (*ButtonField) SetAction ¶ added in v0.5.0
func (f *ButtonField) SetAction(act Action)
SetAction writes the button's activation action (/A) onto its widget(s) — typically a SubmitFormAction, ResetFormAction, GoTo/URI or JavaScript action. nil clears the action. Mirrors Aspose.PDF for .NET's ButtonField.OnActivated.
func (*ButtonField) SetAppearance ¶ added in v0.3.0
func (f *ButtonField) SetAppearance(a ButtonAppearance) error
SetAppearance applies a ButtonAppearance to the push button: it writes the /MK characteristics (/CA, /RC, /AC, /TP) and regenerates the widget's /AP with distinct /N (normal), /R (rollover), and /D (down) appearance streams. Returns an error if the field has no widget or the icon image cannot be read.
func (*ButtonField) SetReadOnly ¶
func (f *ButtonField) SetReadOnly(v bool)
func (*ButtonField) SetStyle ¶ added in v0.3.0
func (b *ButtonField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*ButtonField) SetValue ¶
func (f *ButtonField) SetValue(s string) error
func (*ButtonField) Style ¶ added in v0.3.0
func (b *ButtonField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
func (*ButtonField) Value ¶
func (f *ButtonField) Value() string
type ButtonIconPosition ¶ added in v0.3.0
type ButtonIconPosition int
ButtonIconPosition controls how a push button lays out its icon and caption — the /MK /TP entry per ISO 32000-1 §12.5.6.19 Table 189.
const ( ButtonCaptionOnly ButtonIconPosition = 0 // /TP 0 — caption only, no icon ButtonIconOnly ButtonIconPosition = 1 // /TP 1 — icon only, no caption ButtonIconAboveCaption ButtonIconPosition = 2 // /TP 2 — caption below the icon ButtonCaptionOverIcon ButtonIconPosition = 6 // /TP 6 — caption overlaid on the icon )
type CaretAnnotation ¶ added in v0.4.0
type CaretAnnotation struct {
// contains filtered or unexported fields
}
CaretAnnotation marks a point of text insertion or deletion, drawn as an upward caret ("^") filled with the annotation colour. Mirrors Aspose.PDF for .NET's CaretAnnotation.
func NewCaretAnnotation ¶ added in v0.4.0
func NewCaretAnnotation(page *Page, rect Rectangle) *CaretAnnotation
NewCaretAnnotation builds an unbound caret annotation occupying rect. Page must be non-nil. The caret is drawn to fill the rectangle; set a colour with SetColor (default black).
func (*CaretAnnotation) AnnotationType ¶ added in v0.4.0
func (a *CaretAnnotation) AnnotationType() AnnotationType
func (*CaretAnnotation) BorderStyle ¶ added in v0.4.0
func (d *CaretAnnotation) BorderStyle() BorderStyle
BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.
func (*CaretAnnotation) BorderWidth ¶ added in v0.4.0
func (d *CaretAnnotation) BorderWidth() float64
BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.
func (*CaretAnnotation) DashPattern ¶ added in v0.4.0
func (d *CaretAnnotation) DashPattern() []float64
DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.
func (*CaretAnnotation) RegenerateAppearance ¶ added in v0.4.0
func (a *CaretAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*CaretAnnotation) SetBorderStyle ¶ added in v0.4.0
func (d *CaretAnnotation) SetBorderStyle(s BorderStyle)
SetBorderStyle writes /BS/S using the PDF spec name codes.
func (*CaretAnnotation) SetBorderWidth ¶ added in v0.4.0
func (d *CaretAnnotation) SetBorderWidth(w float64)
SetBorderWidth writes /BS/W and clears any legacy /Border array.
func (*CaretAnnotation) SetColor ¶ added in v0.4.0
func (d *CaretAnnotation) SetColor(c *Color)
SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.
func (*CaretAnnotation) SetDashPattern ¶ added in v0.4.0
func (d *CaretAnnotation) SetDashPattern(p []float64)
SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.
func (*CaretAnnotation) SetRect ¶ added in v0.4.0
func (d *CaretAnnotation) SetRect(r Rectangle)
SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).
func (*CaretAnnotation) SetSymbol ¶ added in v0.4.0
func (a *CaretAnnotation) SetSymbol(s CaretSymbol)
SetSymbol writes /Sy. CaretSymbolNone removes the entry.
func (*CaretAnnotation) Symbol ¶ added in v0.4.0
func (a *CaretAnnotation) Symbol() CaretSymbol
Symbol returns the /Sy symbol drawn with the caret.
type CaretSymbol ¶ added in v0.4.0
type CaretSymbol int
CaretSymbol is the /Sy entry of a Caret annotation per ISO 32000-1 §12.5.6.11 Table 180 — an optional symbol drawn together with the caret to associate it with an editing action.
const ( // CaretSymbolNone draws the caret alone (/Sy /None or absent). CaretSymbolNone CaretSymbol = iota // CaretSymbolParagraph draws a paragraph symbol with the caret (/Sy /P). CaretSymbolParagraph )
type Cell ¶
type Cell struct {
// contains filtered or unexported fields
}
Cell is a single cell within a Row.
func (*Cell) Background ¶
func (*Cell) Border ¶
func (c *Cell) Border() *BorderInfo
func (*Cell) Image ¶
Image returns the configured image source. path is empty when the image was set from a stream. hasImage is true when any image source is set.
func (*Cell) Margin ¶
func (c *Cell) Margin() *MarginInfo
func (*Cell) SetBackground ¶
func (*Cell) SetBorder ¶
func (c *Cell) SetBorder(b BorderInfo) *Cell
func (*Cell) SetColSpan ¶
SetColSpan sets the column span (cells the cell occupies horizontally). Default 1. Mirrors Aspose.PDF for .NET's Cell.ColSpan.
When colSpan > 1, the caller does NOT add cells for the positions covered by the span — the row simply has fewer cells.
func (*Cell) SetImage ¶
SetImage configures the cell to render the named image instead of text. PNG and JPEG supported (format auto-detected by magic bytes).
If both SetText and SetImage are configured, the image wins.
The image is auto-sized to fit the cell's interior width (sum of spanned column widths minus padding), preserving aspect ratio. Row height auto-fit computes the resulting image height plus margins. Use Row.SetHeight to override row height; the image then scales down to fit if needed.
Mirrors Aspose.PDF for .NET's Cell.Image property.
func (*Cell) SetImageFromStream ¶
SetImageFromStream is the io.Reader-based counterpart. The full stream is buffered immediately so that the table renderer can measure and draw later.
func (*Cell) SetMargin ¶
func (c *Cell) SetMargin(m MarginInfo) *Cell
func (*Cell) SetRowSpan ¶
SetRowSpan sets the row span (rows the cell occupies vertically). Default 1. Mirrors Aspose.PDF for .NET's Cell.RowSpan.
When rowSpan > 1, the caller does NOT add cells in subsequent rows for the positions covered by the span — those rows simply have fewer cells.
func (*Cell) SetTextStyle ¶
SetTextStyle overrides the table's DefaultCellStyle for this cell.
type CertifyPermission ¶ added in v0.4.0
type CertifyPermission int
CertifyPermission is the DocMDP permission level of a certification signature (ISO 32000-1 §12.8.2.2 Table 254). Its integer value is the /P entry written to /TransformParams.
const ( NotCertified CertifyPermission = iota // ordinary approval signature (default) CertifyNoChanges // P=1: no changes permitted CertifyFillForms // P=2: form filling and signing CertifyAnnotations // P=3: form filling, signing, and annotations )
type CheckboxField ¶
type CheckboxField struct {
// contains filtered or unexported fields
}
CheckboxField is a checkbox with on/off state.
func (*CheckboxField) Checked ¶
func (f *CheckboxField) Checked() bool
func (*CheckboxField) Flatten ¶ added in v0.3.0
func (b *CheckboxField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*CheckboxField) IsReadOnly ¶
func (b *CheckboxField) IsReadOnly() bool
func (*CheckboxField) IsRequired ¶
func (b *CheckboxField) IsRequired() bool
func (*CheckboxField) PartialName ¶
func (b *CheckboxField) PartialName() string
func (*CheckboxField) SetChecked ¶
func (f *CheckboxField) SetChecked(v bool)
SetChecked sets the checkbox state. The "checked" /V is the kid widget's /AS export value (typically /Yes); the "unchecked" /V is /Off.
func (*CheckboxField) SetReadOnly ¶
func (f *CheckboxField) SetReadOnly(v bool)
func (*CheckboxField) SetRequired ¶
func (f *CheckboxField) SetRequired(v bool)
func (*CheckboxField) SetStyle ¶ added in v0.3.0
func (b *CheckboxField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*CheckboxField) SetValue ¶
func (f *CheckboxField) SetValue(s string) error
func (*CheckboxField) Style ¶ added in v0.3.0
func (b *CheckboxField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
func (*CheckboxField) Value ¶
func (f *CheckboxField) Value() string
type ChoiceOption ¶
type ChoiceOption struct {
Value string // displayed text
Export string // export value when distinct from Value
}
ChoiceOption is one option of a ComboBoxField or ListBoxField.
type CircleAnnotation ¶
type CircleAnnotation struct {
// contains filtered or unexported fields
}
CircleAnnotation draws an elliptical annotation. Mirrors SquareAnnotation API; only the rendered shape and /Subtype differ. Border styles (Solid/Dashed/Beveled/Inset/Underline) and BorderWidth/Color/DashPattern are inherited from drawingAnnotationBase.
func NewCircleAnnotation ¶
func NewCircleAnnotation(page *Page, rect Rectangle) *CircleAnnotation
NewCircleAnnotation builds an unbound circle annotation. Page must be non-nil. The ellipse is inscribed in the given rectangle.
func (*CircleAnnotation) AnnotationType ¶
func (a *CircleAnnotation) AnnotationType() AnnotationType
func (*CircleAnnotation) BorderStyle ¶
func (d *CircleAnnotation) BorderStyle() BorderStyle
BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.
func (*CircleAnnotation) BorderWidth ¶
func (d *CircleAnnotation) BorderWidth() float64
BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.
func (*CircleAnnotation) DashPattern ¶
func (d *CircleAnnotation) DashPattern() []float64
DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.
func (*CircleAnnotation) InteriorColor ¶
func (a *CircleAnnotation) InteriorColor() *Color
InteriorColor returns the /IC fill color, or nil if absent.
func (*CircleAnnotation) RegenerateAppearance ¶
func (a *CircleAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*CircleAnnotation) SetBorderStyle ¶
func (d *CircleAnnotation) SetBorderStyle(s BorderStyle)
SetBorderStyle writes /BS/S using the PDF spec name codes.
func (*CircleAnnotation) SetBorderWidth ¶
func (d *CircleAnnotation) SetBorderWidth(w float64)
SetBorderWidth writes /BS/W and clears any legacy /Border array.
func (*CircleAnnotation) SetColor ¶
func (d *CircleAnnotation) SetColor(c *Color)
SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.
func (*CircleAnnotation) SetDashPattern ¶
func (d *CircleAnnotation) SetDashPattern(p []float64)
SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.
func (*CircleAnnotation) SetInteriorColor ¶
func (a *CircleAnnotation) SetInteriorColor(c *Color)
SetInteriorColor writes /IC as an RGB array; nil removes the entry.
type Collection ¶ added in v0.8.0
type Collection struct {
// contains filtered or unexported fields
}
Collection is the document's portfolio view over its embedded files. Always non-nil; IsPortfolio reports whether the document actually carries a /Collection dictionary. Mutating calls create it.
func (*Collection) Files ¶ added in v0.8.0
func (c *Collection) Files() []*EmbeddedFile
Files returns the portfolio's attachments — the document's embedded files, which a portfolio is a presentation layer over.
func (*Collection) InitialFile ¶ added in v0.8.0
func (c *Collection) InitialFile() string
InitialFile returns the name of the attachment a viewer opens first, or "" when unset.
func (*Collection) IsPortfolio ¶ added in v0.8.0
func (c *Collection) IsPortfolio() bool
IsPortfolio reports whether the document presents its attachments as a portfolio.
func (*Collection) Remove ¶ added in v0.8.0
func (c *Collection) Remove()
Remove drops the /Collection dictionary: the attachments stay, presented as an ordinary attachment list again.
func (*Collection) Schema ¶ added in v0.8.0
func (c *Collection) Schema() *CollectionSchema
Schema returns the portfolio's column schema.
func (*Collection) SetInitialFile ¶ added in v0.8.0
func (c *Collection) SetInitialFile(name string)
SetInitialFile names the attachment a viewer should present first; "" clears the entry. The name must match an embedded file's name-tree key.
func (*Collection) SetSort ¶ added in v0.8.0
func (c *Collection) SetSort(field string, ascending bool)
SetSort makes the viewer sort the file list by the named schema field; an empty field clears the sort.
func (*Collection) SetView ¶ added in v0.8.0
func (c *Collection) SetView(v CollectionView)
SetView sets the presentation mode, turning the document into a portfolio if it is not one already.
func (*Collection) Sort ¶ added in v0.8.0
func (c *Collection) Sort() (field string, ascending bool, ok bool)
Sort returns the field the viewer sorts by and its direction; ok is false when no sort is configured.
func (*Collection) View ¶ added in v0.8.0
func (c *Collection) View() CollectionView
View returns the presentation mode; CollectionViewDetails when unset.
type CollectionField ¶ added in v0.8.0
type CollectionField struct {
// contains filtered or unexported fields
}
CollectionField is one portfolio column.
func (*CollectionField) DisplayName ¶ added in v0.8.0
func (f *CollectionField) DisplayName() string
DisplayName returns the column header text.
func (*CollectionField) IsDerived ¶ added in v0.8.0
func (f *CollectionField) IsDerived() bool
IsDerived reports whether the column's values come from the attachment's file specification (file name, description, dates, size) rather than from its collection item — such a column needs no per-file value.
func (*CollectionField) IsEditable ¶ added in v0.8.0
func (f *CollectionField) IsEditable() bool
IsEditable reports whether a viewer may edit the values (/E, default false).
func (*CollectionField) IsVisible ¶ added in v0.8.0
func (f *CollectionField) IsVisible() bool
IsVisible reports whether the viewer shows the column (/V, default true).
func (*CollectionField) Key ¶ added in v0.8.0
func (f *CollectionField) Key() string
Key returns the field key used by collection items.
func (*CollectionField) Order ¶ added in v0.8.0
func (f *CollectionField) Order() int
Order returns the column's position (/O); 0 when unset.
func (*CollectionField) SetDisplayName ¶ added in v0.8.0
func (f *CollectionField) SetDisplayName(s string)
SetDisplayName sets the column header text.
func (*CollectionField) SetEditable ¶ added in v0.8.0
func (f *CollectionField) SetEditable(v bool)
SetEditable allows or forbids viewer-side editing of the column's values.
func (*CollectionField) SetOrder ¶ added in v0.8.0
func (f *CollectionField) SetOrder(n int)
SetOrder sets the column's position among the others.
func (*CollectionField) SetVisible ¶ added in v0.8.0
func (f *CollectionField) SetVisible(v bool)
SetVisible shows or hides the column.
func (*CollectionField) Type ¶ added in v0.8.0
func (f *CollectionField) Type() CollectionFieldType
Type returns the column's value type.
type CollectionFieldType ¶ added in v0.8.0
type CollectionFieldType int
CollectionFieldType is a schema column's data type (the collection field's /Subtype). The last five are derived fields: their values come from the file specification itself, so they need no per-file collection-item entry.
const ( // CollectionFieldText holds a text value (/S). CollectionFieldText CollectionFieldType = iota // CollectionFieldDate holds a date value (/D). CollectionFieldDate // CollectionFieldNumber holds a numeric value (/N). CollectionFieldNumber // CollectionFieldFilename shows the attachment's file name (/F). CollectionFieldFilename // CollectionFieldDescription shows the attachment's description (/Desc). CollectionFieldDescription // CollectionFieldModDate shows the embedded file's modification date // (/ModDate). CollectionFieldModDate // CollectionFieldCreationDate shows the embedded file's creation date // (/CreationDate). CollectionFieldCreationDate // CollectionFieldSize shows the embedded file's size in bytes (/Size). CollectionFieldSize )
type CollectionItem ¶ added in v0.8.0
type CollectionItem struct {
// contains filtered or unexported fields
}
CollectionItem holds one attachment's values for the portfolio's schema fields (the file specification's /CI dictionary).
func (*CollectionItem) Date ¶ added in v0.8.0
func (i *CollectionItem) Date(field string) (value time.Time, ok bool)
Date returns the field's date value; ok is false when the field is unset or does not parse as a PDF date.
func (*CollectionItem) Fields ¶ added in v0.8.0
func (i *CollectionItem) Fields() []string
Fields returns the keys this item carries values for, sorted.
func (*CollectionItem) Number ¶ added in v0.8.0
func (i *CollectionItem) Number(field string) (value float64, ok bool)
Number returns the field's numeric value; ok is false when the field is unset or holds another type.
func (*CollectionItem) Remove ¶ added in v0.8.0
func (i *CollectionItem) Remove(field string) bool
Remove deletes the item's value for a field; it reports whether one was removed.
func (*CollectionItem) SetDate ¶ added in v0.8.0
func (i *CollectionItem) SetDate(field string, t time.Time)
SetDate stores a date value for the field (written as a PDF date string).
func (*CollectionItem) SetNumber ¶ added in v0.8.0
func (i *CollectionItem) SetNumber(field string, value float64)
SetNumber stores a numeric value for the field.
func (*CollectionItem) SetText ¶ added in v0.8.0
func (i *CollectionItem) SetText(field, value string)
SetText stores a text value for the field.
func (*CollectionItem) Text ¶ added in v0.8.0
func (i *CollectionItem) Text(field string) string
Text returns the field's value as text, or "" when unset.
type CollectionSchema ¶ added in v0.8.0
type CollectionSchema struct {
// contains filtered or unexported fields
}
CollectionSchema is the portfolio's set of columns.
func (*CollectionSchema) Add ¶ added in v0.8.0
func (s *CollectionSchema) Add(key, displayName string, typ CollectionFieldType) *CollectionField
Add defines a column: key identifies the field in collection items, displayName is the header a viewer shows, and typ is the value type. Re-adding an existing key replaces it. The new field is visible, not editable, and ordered after the existing ones.
func (*CollectionSchema) Count ¶ added in v0.8.0
func (s *CollectionSchema) Count() int
Count returns the number of columns.
func (*CollectionSchema) Field ¶ added in v0.8.0
func (s *CollectionSchema) Field(key string) *CollectionField
Field returns the column with the given key, or nil.
func (*CollectionSchema) Fields ¶ added in v0.8.0
func (s *CollectionSchema) Fields() []*CollectionField
Fields returns the columns in display order (by /O, then by key).
func (*CollectionSchema) Keys ¶ added in v0.8.0
func (s *CollectionSchema) Keys() []string
Keys returns the column keys in display order.
func (*CollectionSchema) Remove ¶ added in v0.8.0
func (s *CollectionSchema) Remove(key string) bool
Remove deletes a column; it reports whether one was removed. Values already stored in collection items are left alone (harmless, and they reappear if the column is added back).
type CollectionView ¶ added in v0.8.0
type CollectionView int
CollectionView selects how a viewer presents the portfolio's files (the /Collection /View entry).
const ( // CollectionViewDetails lists the files in a table of schema columns (/D). CollectionViewDetails CollectionView = iota // CollectionViewTiles shows one tile per file (/T). CollectionViewTiles // CollectionViewHidden hides the portfolio pane, showing the cover // page only (/H). CollectionViewHidden )
type ComboBoxField ¶
type ComboBoxField struct {
// contains filtered or unexported fields
}
ComboBoxField is a single-select dropdown choice field.
func (*ComboBoxField) AddOption ¶
func (f *ComboBoxField) AddOption(o ChoiceOption)
AddOption appends a ChoiceOption to /Opt.
func (*ComboBoxField) Flatten ¶ added in v0.3.0
func (b *ComboBoxField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*ComboBoxField) IsReadOnly ¶
func (b *ComboBoxField) IsReadOnly() bool
func (*ComboBoxField) IsRequired ¶
func (b *ComboBoxField) IsRequired() bool
func (*ComboBoxField) Options ¶
func (f *ComboBoxField) Options() []ChoiceOption
func (*ComboBoxField) PartialName ¶
func (b *ComboBoxField) PartialName() string
func (*ComboBoxField) RemoveOption ¶
func (f *ComboBoxField) RemoveOption(index int) error
RemoveOption removes the option at index. Errors on out-of-range.
func (*ComboBoxField) Selected ¶
func (f *ComboBoxField) Selected() int
func (*ComboBoxField) SetEditable ¶
func (f *ComboBoxField) SetEditable(v bool)
SetEditable toggles bit 19 (/Ff Edit). When true, the combo accepts arbitrary user-typed text instead of restricting to /Opt entries.
func (*ComboBoxField) SetReadOnly ¶
func (f *ComboBoxField) SetReadOnly(v bool)
SetReadOnly sets the read-only flag; the choice types share the same setFlag-based mutators as the text field.
func (*ComboBoxField) SetRequired ¶
func (f *ComboBoxField) SetRequired(v bool)
func (*ComboBoxField) SetSelected ¶
func (f *ComboBoxField) SetSelected(index int) error
func (*ComboBoxField) SetStyle ¶ added in v0.3.0
func (b *ComboBoxField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*ComboBoxField) SetValue ¶
func (f *ComboBoxField) SetValue(s string) error
func (*ComboBoxField) Style ¶ added in v0.3.0
func (b *ComboBoxField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
func (*ComboBoxField) Value ¶
func (f *ComboBoxField) Value() string
type ComparisonOptions ¶ added in v0.9.0
type ComparisonOptions struct {
// ExtractionArea limits the comparison to the words whose centre lies in
// this rectangle. Cannot be combined with ExcludeTables or ExcludeAreas.
ExtractionArea *Rectangle
// ExcludeAreas1 lists regions of the first document to ignore.
ExcludeAreas1 []Rectangle
// ExcludeAreas2 lists regions of the second document to ignore.
ExcludeAreas2 []Rectangle
// ExcludeTables drops the words inside tables found by the TableAbsorber.
ExcludeTables bool
// EditOperationsOrder decides which half of a replacement is reported first.
EditOperationsOrder EditOperationsOrder
// IgnoreCase compares words without regard to letter case. This library's
// addition; Aspose has no equivalent.
IgnoreCase bool
}
ComparisonOptions narrows what is compared. The zero value compares the whole page, case-sensitively, reporting deletions before insertions. Mirrors Aspose.PDF for .NET's ComparisonOptions, plus IgnoreCase.
type ComparisonResult ¶ added in v0.9.0
type ComparisonResult struct {
// contains filtered or unexported fields
}
ComparisonResult holds the differences between two documents and can write a marked-up copy of either side.
func CompareDocumentsPageByPage ¶ added in v0.9.0
func CompareDocumentsPageByPage(d1, d2 *Document, opts ...ComparisonOptions) (*ComparisonResult, error)
CompareDocumentsPageByPage compares page 1 with page 1, page 2 with page 2 and so on; the pages of the longer document beyond the shorter one are reported wholly inserted or wholly deleted. Mirrors Aspose.PDF for .NET's TextPdfComparer.CompareDocumentsPageByPage.
func CompareFlatDocuments ¶ added in v0.9.0
func CompareFlatDocuments(d1, d2 *Document, opts ...ComparisonOptions) (*ComparisonResult, error)
CompareFlatDocuments compares the documents as one continuous text, so content that moved across a page boundary reads as unchanged. Mirrors Aspose.PDF for .NET's TextPdfComparer.CompareFlatDocuments.
func (*ComparisonResult) HasChanges ¶ added in v0.9.0
func (r *ComparisonResult) HasChanges() bool
HasChanges reports whether anything differs. Mirrors Aspose.PDF for .NET's SideBySideDocsComparisonResult.HasChanges.
func (*ComparisonResult) Operations ¶ added in v0.9.0
func (r *ComparisonResult) Operations() []DiffOperation
Operations returns every operation, differences and unchanged runs alike, in document order. The returned slice is the result's internal storage; the caller must not sort or truncate it in place.
func (*ComparisonResult) PageOperations ¶ added in v0.9.0
func (r *ComparisonResult) PageOperations(pageNum int) []DiffOperation
PageOperations returns the operations of one 1-based page. An operation is listed under the page it physically occupies: the second document's page for equal and inserted text, the first document's page for deleted text. In page-by-page mode the returned slice is the result's internal storage; the caller must not sort or truncate it in place.
func (*ComparisonResult) Pages ¶ added in v0.10.0
func (r *ComparisonResult) Pages() [][]DiffOperation
Pages returns the operations grouped one slice per page, the shape every diff output generator's *Pages method expects — the same shape CompareDocumentsPageByPage/CompareFlatDocuments return directly in Aspose.PDF for .NET. In page-by-page mode this is the result's own per-page storage; in flat mode it is built from PageOperations, since flat mode keeps only the flat op list.
func (*ComparisonResult) SaveMarkup ¶ added in v0.9.0
func (r *ComparisonResult) SaveMarkup(path string, opts ...DiffMarkupOptions) error
SaveMarkup writes a copy of one of the compared documents with every difference marked as an annotation. The documents handed to the comparer are left untouched; the output is a new document, so signatures on the input do not survive the copy. Marking up an encrypted document is not supported — save it without encryption first.
func (*ComparisonResult) Statistics ¶ added in v0.9.0
func (r *ComparisonResult) Statistics() ComparisonStatistics
Statistics counts the words on each side of the comparison. Mirrors Aspose.PDF for .NET's TextPdfComparer.CreateComparisonStatistics.
func (*ComparisonResult) WriteMarkup ¶ added in v0.9.0
func (r *ComparisonResult) WriteMarkup(w io.Writer, opts ...DiffMarkupOptions) error
WriteMarkup writes the marked-up copy to w. The output is a new document, so signatures on the input do not survive the copy. Marking up an encrypted document is not supported — save it without encryption first.
type ComparisonStatistics ¶ added in v0.9.0
type ComparisonStatistics struct {
EqualWords int
InsertedWords int
DeletedWords int
// ChangedPages lists, ascending, the pages carrying a change. Each page
// number is chosen by the same rule PageOperations uses to place an
// operation — the destination page for equal and inserted text, the
// source page for deleted text — but since only non-equal operations
// contribute, in practice this means the destination page for an
// insertion and the source page for a deletion. In flat mode source and
// destination page numbers are independent counters, so this list can
// mix the two numbering spaces.
ChangedPages []int
}
ComparisonStatistics summarises a comparison. Mirrors the shape of Aspose.PDF for .NET's DocumentComparisonStatistics.
type DateField ¶ added in v0.4.0
type DateField struct{ TextBoxField }
DateField is a text field with a JavaScript date-format action and a format mask (e.g. "mm/dd/yyyy").
func (*DateField) Flatten ¶ added in v0.4.0
func (b *DateField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*DateField) Format ¶ added in v0.4.0
Format returns the date field's format mask (parsed back from its format JS).
func (*DateField) IsReadOnly ¶ added in v0.4.0
func (b *DateField) IsReadOnly() bool
func (*DateField) IsRequired ¶ added in v0.4.0
func (b *DateField) IsRequired() bool
func (*DateField) PartialName ¶ added in v0.4.0
func (b *DateField) PartialName() string
func (*DateField) SetStyle ¶ added in v0.4.0
func (b *DateField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*DateField) Style ¶ added in v0.4.0
func (b *DateField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
type Destination ¶
type Destination interface {
DestinationType() DestinationType
Page() *Page
}
Destination is the common interface for all explicit destinations. Per ISO 32000-1 §12.3.2.2.
type DestinationFit ¶
type DestinationFit struct {
// contains filtered or unexported fields
}
DestinationFit — [page /Fit]
func NewDestinationFit ¶
func NewDestinationFit(page *Page) *DestinationFit
func (*DestinationFit) DestinationType ¶
func (d *DestinationFit) DestinationType() DestinationType
func (*DestinationFit) Page ¶
func (d *DestinationFit) Page() *Page
type DestinationFitB ¶
type DestinationFitB struct {
// contains filtered or unexported fields
}
DestinationFitB — [page /FitB]
func NewDestinationFitB ¶
func NewDestinationFitB(page *Page) *DestinationFitB
func (*DestinationFitB) DestinationType ¶
func (d *DestinationFitB) DestinationType() DestinationType
func (*DestinationFitB) Page ¶
func (d *DestinationFitB) Page() *Page
type DestinationFitBH ¶
type DestinationFitBH struct {
// contains filtered or unexported fields
}
DestinationFitBH — [page /FitBH top]
func NewDestinationFitBH ¶
func NewDestinationFitBH(page *Page, top float64) *DestinationFitBH
func NewDestinationFitBHUnchanged ¶
func NewDestinationFitBHUnchanged(page *Page) *DestinationFitBH
func (*DestinationFitBH) DestinationType ¶
func (d *DestinationFitBH) DestinationType() DestinationType
func (*DestinationFitBH) HasTop ¶
func (d *DestinationFitBH) HasTop() bool
func (*DestinationFitBH) Page ¶
func (d *DestinationFitBH) Page() *Page
func (*DestinationFitBH) Top ¶
func (d *DestinationFitBH) Top() float64
type DestinationFitBV ¶
type DestinationFitBV struct {
// contains filtered or unexported fields
}
DestinationFitBV — [page /FitBV left]
func NewDestinationFitBV ¶
func NewDestinationFitBV(page *Page, left float64) *DestinationFitBV
func NewDestinationFitBVUnchanged ¶
func NewDestinationFitBVUnchanged(page *Page) *DestinationFitBV
func (*DestinationFitBV) DestinationType ¶
func (d *DestinationFitBV) DestinationType() DestinationType
func (*DestinationFitBV) HasLeft ¶
func (d *DestinationFitBV) HasLeft() bool
func (*DestinationFitBV) Left ¶
func (d *DestinationFitBV) Left() float64
func (*DestinationFitBV) Page ¶
func (d *DestinationFitBV) Page() *Page
type DestinationFitH ¶
type DestinationFitH struct {
// contains filtered or unexported fields
}
DestinationFitH — [page /FitH top]
func NewDestinationFitH ¶
func NewDestinationFitH(page *Page, top float64) *DestinationFitH
func NewDestinationFitHUnchanged ¶
func NewDestinationFitHUnchanged(page *Page) *DestinationFitH
func (*DestinationFitH) DestinationType ¶
func (d *DestinationFitH) DestinationType() DestinationType
func (*DestinationFitH) HasTop ¶
func (d *DestinationFitH) HasTop() bool
func (*DestinationFitH) Page ¶
func (d *DestinationFitH) Page() *Page
func (*DestinationFitH) Top ¶
func (d *DestinationFitH) Top() float64
type DestinationFitR ¶
type DestinationFitR struct {
// contains filtered or unexported fields
}
DestinationFitR — [page /FitR left bottom right top]
func NewDestinationFitR ¶
func NewDestinationFitR(page *Page, left, bottom, right, top float64) *DestinationFitR
func (*DestinationFitR) Bottom ¶
func (d *DestinationFitR) Bottom() float64
func (*DestinationFitR) DestinationType ¶
func (d *DestinationFitR) DestinationType() DestinationType
func (*DestinationFitR) Left ¶
func (d *DestinationFitR) Left() float64
func (*DestinationFitR) Page ¶
func (d *DestinationFitR) Page() *Page
func (*DestinationFitR) Right ¶
func (d *DestinationFitR) Right() float64
func (*DestinationFitR) Top ¶
func (d *DestinationFitR) Top() float64
type DestinationFitV ¶
type DestinationFitV struct {
// contains filtered or unexported fields
}
DestinationFitV — [page /FitV left]
func NewDestinationFitV ¶
func NewDestinationFitV(page *Page, left float64) *DestinationFitV
func NewDestinationFitVUnchanged ¶
func NewDestinationFitVUnchanged(page *Page) *DestinationFitV
func (*DestinationFitV) DestinationType ¶
func (d *DestinationFitV) DestinationType() DestinationType
func (*DestinationFitV) HasLeft ¶
func (d *DestinationFitV) HasLeft() bool
func (*DestinationFitV) Left ¶
func (d *DestinationFitV) Left() float64
func (*DestinationFitV) Page ¶
func (d *DestinationFitV) Page() *Page
type DestinationType ¶
type DestinationType int
DestinationType identifies the destination flavor.
const ( DestinationTypeXYZ DestinationType = iota DestinationTypeFit DestinationTypeFitH DestinationTypeFitV DestinationTypeFitR DestinationTypeFitB DestinationTypeFitBH DestinationTypeFitBV DestinationTypeNamed // named destination reference via collection lookup )
type DestinationXYZ ¶
type DestinationXYZ struct {
// contains filtered or unexported fields
}
DestinationXYZ — [page /XYZ left top zoom]. Any of left/top/zoom may be left "unchanged" (encoded as /null in PDF) via the Has* flags.
func NewDestinationXYZ ¶
func NewDestinationXYZ(page *Page, left, top, zoom float64) *DestinationXYZ
func (*DestinationXYZ) DestinationType ¶
func (d *DestinationXYZ) DestinationType() DestinationType
func (*DestinationXYZ) HasLeft ¶
func (d *DestinationXYZ) HasLeft() bool
func (*DestinationXYZ) HasTop ¶
func (d *DestinationXYZ) HasTop() bool
func (*DestinationXYZ) HasZoom ¶
func (d *DestinationXYZ) HasZoom() bool
func (*DestinationXYZ) Left ¶
func (d *DestinationXYZ) Left() float64
func (*DestinationXYZ) Page ¶
func (d *DestinationXYZ) Page() *Page
func (*DestinationXYZ) Top ¶
func (d *DestinationXYZ) Top() float64
func (*DestinationXYZ) Zoom ¶
func (d *DestinationXYZ) Zoom() float64
type DiffMarkupOptions ¶ added in v0.9.0
type DiffMarkupOptions struct {
Side DiffMarkupSide
InsertColor *Color
DeleteColor *Color
Title string
// Flatten bakes the comparison markup into the page content and removes
// it, via (*AnnotationCollection).Flatten. That call flattens every
// non-widget annotation already on the page, not only the ones this
// writer added — an existing highlight or free-text annotation in the
// source document is flattened too.
Flatten bool
}
DiffMarkupOptions styles the marked-up copy. The zero value marks the second document in green and red, titles every annotation "Comparison" and keeps the annotations live.
type DiffMarkupSide ¶ added in v0.9.0
type DiffMarkupSide int
DiffMarkupSide selects which document the markup is drawn on.
const ( // DiffMarkupDestination marks the second document: insertions // highlighted, deletions shown as carets carrying the removed text. The // zero value. DiffMarkupDestination DiffMarkupSide = iota // DiffMarkupSource marks the first document: deletions struck out, // insertions shown as carets carrying the added text. DiffMarkupSource )
type DiffOperation ¶ added in v0.9.0
type DiffOperation struct {
Operation Operation
// Text is the run's words joined with single spaces. For OperationEqual
// it is the first document's spelling, which can differ from the second's
// when ComparisonOptions.IgnoreCase is set.
Text string
// SourcePage is the 1-based page in the first document, 0 for an insertion.
SourcePage int
// DestPage is the 1-based page in the second document, 0 for a deletion.
DestPage int
// SourceRects holds one rectangle per line the run touches in the first
// document; empty for an insertion.
SourceRects []Rectangle
// DestRects holds one rectangle per line the run touches in the second
// document; empty for a deletion.
DestRects []Rectangle
}
DiffOperation is one run of adjacent words sharing an operation. Runs break at line and page boundaries, so every rectangle is a real box on a real page: a run spanning three lines carries three rectangles.
Operation and Text mirror Aspose.PDF for .NET's DiffOperation; the page and rectangle fields are this library's addition.
func ComparePages ¶ added in v0.9.0
func ComparePages(p1, p2 *Page, opts ...ComparisonOptions) ([]DiffOperation, error)
ComparePages compares the text of two pages and returns the differences in reading order. Mirrors Aspose.PDF for .NET's TextPdfComparer.ComparePages.
type DiffOutputStyle ¶ added in v0.10.0
type DiffOutputStyle struct {
InsertColor, InsertBackground *Color
DeleteColor, DeleteBackground *Color
EqualColor, EqualBackground *Color
// StrikethroughDelete draws deleted text with a line through it. Mirrors
// OutputTextStyle.StrikethroughDeleted; default false. Markdown has no
// equivalent knob — a deletion is always struck through there, since GFM
// strikethrough is the only way to represent one at all.
StrikethroughDelete bool
}
DiffOutputStyle colors the three kinds of text a diff output generator marks. The zero value resolves to the same green/red pair DiffMarkupOptions defaults to, keeping every comparison output visually consistent. Mirrors the intent of Aspose.PDF for .NET's OutputTextStyle (its per-kind TextStyle{Color, BackgroundColor} pairs are flattened here, since TextStyle already names an unrelated type in this library).
type DigestAlgorithm ¶ added in v0.10.0
type DigestAlgorithm int
DigestAlgorithm is the hash a signature is computed with. Mirrors Aspose.PDF for .NET's DigestHashAlgorithm; the zero value is SHA-256, which is what every earlier release wrote.
const ( DigestSHA256 DigestAlgorithm = iota // SHA-256 (default) DigestSHA384 // SHA-384 DigestSHA512 // SHA-512 DigestSHA3_256 // SHA3-256 DigestSHA3_384 // SHA3-384 DigestSHA3_512 // SHA3-512 )
func (DigestAlgorithm) String ¶ added in v0.10.0
func (a DigestAlgorithm) String() string
String names the algorithm the way the standards do.
type DocRecognitionMode ¶ added in v0.7.0
type DocRecognitionMode int
DocRecognitionMode selects the reconstruction algorithm — mirrors Aspose.PDF for .NET's DocSaveOptions.RecognitionMode.
const ( // DocEnhancedFlow (default) is DocFlow plus table recognition: ruled // tables detected by the TableAbsorber become real, editable Word // tables (w:tbl with gridSpan/vMerge); tables the detector cannot // claim still carry over as pictures. Mirrors Aspose's EnhancedFlow. DocEnhancedFlow DocRecognitionMode = iota // DocFlow performs full structure recognition (headings, lists, runs) // without table reconstruction — ruled tables carry over as pictures // (Aspose Flow-mode behaviour). DocFlow // DocTextbox is the fixed-layout mode: every paragraph becomes an // absolutely positioned floating text box at its PDF coordinates and // every image an anchored picture — maximal visual fidelity, limited // editability, no reconstruction heuristics. Mirrors Aspose's Textbox. DocTextbox )
type DocSaveOptions ¶ added in v0.7.0
type DocSaveOptions struct {
// Pages is a 1-based subset (in the given order); nil = all pages.
Pages []int
// Mode is the reconstruction algorithm; the zero value DocEnhancedFlow
// recognizes ruled tables as real Word tables.
Mode DocRecognitionMode
// NoImages skips images.
NoImages bool
// NoPageBreaks lets content flow continuously instead of starting a new
// Word page where each source PDF page started (the default inserts a
// page break, so the output pagination mirrors the original; exact
// fit still depends on Word's own line layout).
NoPageBreaks bool
}
DocSaveOptions configures SaveDocx / WriteDocx. The zero value exports all pages in Flow mode with images, preserving the source pagination.
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is a PDF document. Operations directly mutate the receiver.
func ImageToDocument ¶
func ImageToDocument(path string, opts ...ImageToDocumentOptions) (*Document, error)
ImageToDocument creates a new Document with a single page containing the image. Page size is determined by image dimensions and DPI metadata (default 72 DPI).
Example ¶
Convert a standalone image into a single-page PDF.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.ImageToDocument("testdata/Koala.jpg")
if err != nil {
log.Fatal(err)
}
fmt.Println("pages:", doc.PageCount())
}
Output: pages: 1
func ImageToDocumentFromStream ¶
func ImageToDocumentFromStream(r io.Reader, opts ...ImageToDocumentOptions) (*Document, error)
ImageToDocumentFromStream creates a new Document from an image reader. Format is detected by magic bytes.
func MarkdownToDocument ¶ added in v0.6.0
func MarkdownToDocument(path string, opts ...MarkdownOptions) (*Document, error)
MarkdownToDocument renders a Markdown file as a new PDF document.
func MarkdownToDocumentFromStream ¶ added in v0.6.0
func MarkdownToDocumentFromStream(r io.Reader, opts ...MarkdownOptions) (*Document, error)
MarkdownToDocumentFromStream renders Markdown read from r as a new PDF document.
Example ¶
Convert Markdown (CommonMark + GFM) into a paginated PDF.
package main
import (
"fmt"
"log"
"strings"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
md := "# Hello\n\nA paragraph with **bold** text.\n"
doc, err := pdf.MarkdownToDocumentFromStream(strings.NewReader(md))
if err != nil {
log.Fatal(err)
}
pages, _ := doc.ExtractText()
fmt.Println(strings.Split(pages[0], "\n")[0])
}
Output: Hello
func NewDocument ¶
NewDocument creates a single-page blank document with the given dimensions in points.
func NewDocumentFromFormat ¶
func NewDocumentFromFormat(format PageFormat) *Document
NewDocumentFromFormat creates a single-page blank document using a predefined page format.
Example ¶
Create a blank A4 document in memory.
package main
import (
"fmt"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
size, _ := page.Size()
fmt.Printf("%.0fx%.0f pt\n", size.Width, size.Height)
}
Output: 595x842 pt
func Open ¶
Open opens a PDF file and returns a Document.
Example:
doc, err := asposepdf.Open("input.pdf")
Example ¶
Open a PDF file and inspect its page count.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.Open("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
fmt.Println(doc.PageCount(), "pages")
}
Output: 4 pages
func OpenStream ¶
OpenStream reads a PDF from r and returns a Document. Returns ErrEncrypted if the input is password-protected; in that case retry with OpenStreamWithPassword.
Example:
doc, err := asposepdf.OpenStream(file)
func OpenStreamWithCertificate ¶ added in v0.8.0
func OpenStreamWithCertificate(r io.Reader, cert *x509.Certificate, key crypto.Decrypter) (*Document, error)
OpenStreamWithCertificate reads a certificate-encrypted PDF from r. See OpenWithCertificate.
func OpenStreamWithPassword ¶
OpenStreamWithPassword reads a password-protected PDF from r. Plain (unencrypted) PDFs are also accepted — the password is silently ignored — so this method is a safe drop-in for code that doesn't know up front whether the input is encrypted.
See OpenWithPassword for the edit-in-place preservation semantics.
func OpenWithCertificate ¶ added in v0.8.0
func OpenWithCertificate(path string, cert *x509.Certificate, key crypto.Decrypter) (*Document, error)
OpenWithCertificate opens a PDF encrypted for certificate recipients (the public-key security handler, /Filter /Adobe.PubSec) using the recipient's certificate and its private key. The key is any crypto.Decrypter — an *rsa.PrivateKey satisfies it — so no .p12 file is required. Plain and password-protected files are rejected with a message pointing at the right entry point.
Example:
doc, err := asposepdf.OpenWithCertificate("secret.pdf", cert, key)
func OpenWithPassword ¶
OpenWithPassword opens a password-protected PDF file. Use Open for unencrypted files. The password is tried as both user and owner password; either unlocks the document for editing. Returns ErrInvalidPassword if it matches neither.
Edit-in-place: the original /O, /U, /P, and /ID bytes from the file are preserved on the returned Document so a subsequent Save reuses them verbatim — BOTH the original user and owner passwords continue to work after re-save, and permissions are preserved bit-for-bit. If you call SetPassword, SetPermissions, SetEncryption, or RemoveEncryption after open, the preserved state is discarded and the document is re-encrypted from the new configuration.
Example:
doc, err := asposepdf.OpenWithPassword("locked.pdf", "secret")
Example ¶
Open an encrypted PDF by trying the password as both user and owner password.
package main
import (
"bytes"
"errors"
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
// Build an encrypted document in memory so the example is self-contained.
src := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
src.SetEncryption(pdf.EncryptionOptions{UserPassword: "secret"})
var buf bytes.Buffer
if _, err := src.WriteTo(&buf); err != nil {
log.Fatal(err)
}
if _, err := pdf.OpenStreamWithPassword(bytes.NewReader(buf.Bytes()), "guess"); errors.Is(err, pdf.ErrInvalidPassword) {
fmt.Println("wrong password rejected")
}
doc, err := pdf.OpenStreamWithPassword(bytes.NewReader(buf.Bytes()), "secret")
if err != nil {
log.Fatal(err)
}
fmt.Println("opened:", doc.PageCount(), "pages")
}
Output: wrong password rejected opened: 1 pages
func (*Document) AddBlankPage ¶
AddBlankPage appends a blank page to the end of the document.
func (*Document) AddBlankPageFromFormat ¶
func (d *Document) AddBlankPageFromFormat(format PageFormat) error
AddBlankPageFromFormat appends a blank page using a predefined page format.
func (*Document) AddLayer ¶ added in v0.4.0
AddLayer creates a new layer (OCG) named name and registers it in the document's optional-content properties. The layer is visible by default; call SetVisible(false) to hide it. Returns the layer for assigning content (Page.BeginLayer) and tuning visibility.
func (*Document) AddSVGObjectWatermark ¶ added in v0.2.0
AddSVGObjectWatermark uses a pre-parsed *SVG for the watermark content. Renders into each target page's full MediaBox.
func (*Document) AddSVGWatermark ¶ added in v0.2.0
AddSVGWatermark applies an SVG watermark to all pages (when pageNums is empty) or to the specified 1-based page numbers. The SVG is positioned to fill each page's MediaBox honoring its own preserveAspectRatio attribute.
Example ¶
Stamp an SVG logo as a watermark on every page.
package main
import (
"bytes"
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.Open("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
if err := doc.AddSVGWatermark("testdata/aspose-logo.svg"); err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
if _, err := doc.WriteTo(&buf); err != nil {
log.Fatal(err)
}
fmt.Println("watermarked:", buf.Len() > 0)
}
Output: watermarked: true
func (*Document) AddSVGWatermarkFromStream ¶ added in v0.2.0
AddSVGWatermarkFromStream is the io.Reader variant of AddSVGWatermark.
func (*Document) AddStamp ¶ added in v0.4.0
AddStamp draws a stamp onto the given 1-based pages (all pages when none are given) — convenient for watermarks, headers, footers, and page numbers. A PageNumberStamp renders the correct number on each page.
func (*Document) AddTextWatermark ¶
AddTextWatermark adds a text watermark to selected pages of the document. If no page numbers are given, the watermark is applied to all pages. Page numbers are 1-based. The watermark covers the full page area (MediaBox). The caller controls all styling via TextStyle (rotation, behind, color, etc.).
Example ¶
Apply a diagonal "DRAFT" text watermark behind the content of every page.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.Open("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
style := pdf.TextStyle{
Font: pdf.FontHelveticaBold,
Size: 72,
Color: &pdf.Color{R: 0.85, G: 0.85, B: 0.85, A: 0.5},
Rotation: 45,
HAlign: pdf.HAlignCenter,
VAlign: pdf.VAlignMiddle,
Behind: true,
}
if err := doc.AddTextWatermark("DRAFT", style); err != nil {
log.Fatal(err)
}
fmt.Println("ok")
}
Output: ok
func (*Document) AddValidationInfo ¶ added in v0.10.0
func (d *Document) AddValidationInfo(opts ...ValidationOptions) error
AddValidationInfo collects the certificates and revocation material for every signature in the document and writes them into the catalog as /DSS, appended as a new revision so signatures already in the file stay valid. This is long-term validation: the evidence travels with the document, so it still verifies once the certificate expires or the responder is gone.
The document must have been opened from a file or stream. Network access is opt-in through ValidationOptions — with the zero value nothing is fetched and only the certificates the signature carries are recorded. Mirrors the intent of Aspose.PDF for .NET's LTV support.
func (*Document) Append ¶
Append adds all pages from others to this document, merging their objects. Nil arguments are silently skipped.
Example:
doc1, _ := asposepdf.Open("part1.pdf")
doc2, _ := asposepdf.Open("part2.pdf")
doc1.Append(doc2)
doc1.Save("combined.pdf")
Example ¶
Merge two documents by appending all pages of one into another.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
a, err := pdf.Open("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
b, err := pdf.Open("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
a.Append(b)
fmt.Println("merged:", a.PageCount(), "pages")
}
Output: merged: 8 pages
func (*Document) ApplyRedactions ¶
ApplyRedactions destructively removes content (text glyphs, image XObjects, paths) inside every /Redact annotation's /QuadPoints (or /Rect if /QuadPoints is empty). Renders /OverlayText if set, then removes the redact annotations from the page. A glyph's page-space position correctly accounts for the graphics-state CTM a "cm" sets, not just the text matrix — see rewriteTextOperatorsInStream's own doc comment (pdf-go-njbg, closed): text drawn after a non-identity "cm" (the common top-left-origin Y-flip many producers emit once per page) used to be compared against regions at the wrong position and so never matched, even when the region came straight from SearchText's own (correct) answer.
Calls RemoveUnusedObjects once at the end when at least one page was redacted, so the content stream(s) a page's /Contents pointed to before redaction — and any earlier dead copy left by prior drawing calls (image_add.go's appendToContentStream, see pdf-go-qgrn) — are actually gone from the saved file rather than merely unreferenced. Both still carry the redacted content in full, recoverable with any PDF tool, until this runs: replacePageContents (used here and by FlattenTransparency) only repoints /Contents, it was never the writer's job to drop what it replaces. Reported privately by shadowhunter1470-svg via GitHub's private vulnerability reporting (pdf-go-2qkq) — thank you for the careful, considerate report.
This sweep shares RemoveUnusedObjects' usual trade-off: a page/catalog -unreachable object that is not yet "dangerous" — e.g. a Type3 glyph canvas or an XForm the caller built but has not placed on any page yet — is reclaimed too. Call ApplyRedactions only after placing everything you mean to keep, same as any other Optimize-family call.
A Form XObject intersecting a redaction region — fully or partially — is now redacted into, not refused (pdf-go-w5hl, closed; a v0.11.0 safety stopgap until then): the region is mapped from page space into the form's own local content-stream space by inverting the composed placement matrix (the form's /Matrix, then the CTM the Do invocation was under — formPlacementBbox's own convention, run in reverse), and the SAME three rewriters this method uses at the page level then run on the form's content with those local-space regions, recursing into a nested Form XObject the same way (up to maxFormRedactDepth levels, and a total maxFormRedactWork placements per PAGE, not across the whole call — see maxFormRedactWork's own doc comment for why that scope is intentional — a fan-out of region-intersecting placements can exhaust this long before the depth cap, bounding a pathologically fan-out-heavy or self-referential file). Neither cap is a silent blind spot: exceeding either one while a region genuinely intersects an unexamined Do is refused (an error), not left incomplete — an earlier draft of the depth cap skipped silently instead, caught by an independent review. The ORIGINAL form object, and its own /Resources dict, are never mutated: since the same Form XObject (and the same /Resources, shared by every placement of it) can be placed more than once — the same logo stamped on every page, say — only placements that actually need a change are redirected (their one Do operand only) to a freshly cloned, redacted copy with its own private /Resources, PRUNED to exactly the /XObject entries the clone's own (rewritten) content still needs (see neededXObjectNames) — every other placement of the original keeps rendering exactly as before. The same sharing hazard applies one level up too: a PAGE's own /Resources can itself be shared across pages via an indirect reference (another common producer size optimization), so this method gives each redacted page a private copy of its own before redacting into it, pruned the same way — minus whatever an annotation appearance stream with no own /Resources on that page still needs through it (see pagePreservedXObjectNames), since the page-level prune has no visibility into annotations on its own. Three sharing/pruning hazards here — a cloned form's own private resources still forwarding a reference to the very original object it replaces (through an inherited entry its own content never uses), a page-level prune removing a name a SIBLING Form XObject sharing that same dict still calls, and the two levels of resources-dict sharing this paragraph opened with — were all confirmed reachable (an unrelated, non-redacted page or placement silently losing content, or the original secret-bearing object staying reachable and un-collectable) across two rounds of independent review of this fix. Still refused outright, not guessed at: a Form XObject with no resolvable /BBox (formPlacementBbox's own ok=false — ISO 32000-1 §8.10.2 requires one on every conformant form) or a placement matrix that doesn't invert (so a region can't be mapped into the form's space at all) — see redactFormDo/redactFormXObject.
Known gaps (not closed by this sweep, tracked separately). Two MORE SEVERE ones — where the secret used to survive not just forensically (pdf-go-2qkq's class) but through this library's own ORDINARY read APIs on the "redacted" file — are now closed: a Tj/TJ run under a font this pipeline cannot classify now REFUSES (an error) rather than passing through unredacted (pdf-go-oq9i; several such "unknown" cases were still visible when rendered and extractable via ExtractText/SearchText, which substitute Helvetica or read the embedded program's own encoding where this redaction-specific flag gives up); and a BDC marked-content span's /ActualText property (common in accessibility-tagged output from Word, InDesign, etc.) is now scrubbed whenever anything inside its span was redacted, so ExtractText/SearchText on a redacted page can no longer return the original secret text verbatim via that replacement mechanism (pdf-go-1ha8). Both fixed in rewriteTextOperatorsInStream (redact_apply_text.go) — see its own doc comment. A further independent review of those two fixes found and closed two more real gaps in the SAME /ActualText mechanism (both documented in rewriteTextOperatorsInStream's own comment, not repeated here) and one gap in ApplyRedactions' own error handling: returning on the first page that errors used to skip RemoveUnusedObjects entirely, so any EARLIER page that had already redacted successfully still had its pre-redaction stream sitting dead but unswept in d.objects — reachable in practice now that pdf-go-oq9i gives this method a real way to fail partway through a multi-page document, where before every rewriter just silently passed through instead. Fixed by sweeping whatever succeeded so far before returning the error, not only on the all-succeeded path.
An Image XObject fully inside a redaction region has its Do invocation dropped from the content stream, and — closed, pdf-go-ye1z — its /Resources/XObject entry is pruned from the page's own (already privatized, see privateXObjectResources) resources too, so RemoveUnusedObjects' trailing sweep above actually reclaims the image object rather than leaving it graph-reachable with its pixel data still in the file. This closed as a side effect of the general-purpose resource-pruning pass neededXObjectNames already does for the unrelated pdf-go-w5hl Form-XObject fix: it computes which /XObject names the FINAL rewritten content still invokes via ANY Do operator — Image or Form alike, it draws no distinction — and prunes every other name, so a dropped Image Do is pruned exactly the same way a redirected Form XObject's now-stale original name is. The ticket had proposed a separate, image-specific fix; by the time it was picked up, the more general mechanism built for pdf-go-w5hl already covered it, confirmed by a direct forensic test (TestApplyRedactionsRemovesFullyCoveredImageBytes, redact_apply_image_leak_internal_test.go — an image whose raw JPEG bytes carry a marker, redacted, then checked byte-for-byte across every object in the saved file, same method pdf-go-2qkq's own regression test uses) and mutation-tested (temporarily disabling the pruning's delete call reproduces exactly the leak the ticket described).
Two more content paths this method's rewriters never reached are now closed too (pdf-go-xp2u). First, every OTHER annotation's own /AP appearance stream(s) overlapping a redaction region are now redacted into (redactAnnotationAppearances, redact_apply_annot.go) — a FreeText note's drawn text, a Stamp's drawn content, and critically a form Widget's /AP rendering of its OWN FIELD VALUE (a text field showing an SSN, say) all draw through their own appearance stream, completely outside this method's page-content rewriters, and used to survive a covering redaction untouched both visually and forensically. Reuses the Form-XObject redaction machinery from pdf-go-w5hl almost verbatim: an annotation's /AP/N (or /D, /R) stream IS a Form XObject, placed by a fixed ISO 32000-1 §12.5.5 algorithm instead of a content-stream `cm`+`Do`, and that algorithm's own matrix composes with the stream's /Matrix exactly the way a Do's CTM does — so redactFormXObject and formPlacementBbox apply unchanged, this just supplies a different "ctm". Same clone-not-mutate discipline as redactFormDo: nothing here ever mutates an annotation's /AP dict or an appearance stream object in place, since either can in principle be shared across annotations or states. Second, an inline image (BI...ID...EI) fully or partially inside a region is now dropped/clipped the same way a non-Form Do is (emitClassifiedImageOp, redact_apply_image.go) — it used to fall through to the rewriter's default case and pass through completely unexamined, the same class of leak as pdf-go-ye1z's XObject-image case but for pixel data that was never a separate XObject to begin with. A tiling pattern whose every fill was redacted away is now dropped from the page's /Resources/Pattern (pdf-go-ifik, closed; prunePagePatterns, redact_apply_pattern.go), so its cell content — which can hold text — no longer stays reachable in the saved file. A pattern still painted somewhere on the page is kept: its cell repeats the same content everywhere, so what a region clips away is also visible outside it. A pattern used only inside a Form XObject with its own /Resources is not pruned (that dict still names it). Type3 /CharProcs are deliberately left alone: a glyph procedure is shared by every occurrence of that glyph, the text rewriter already drops the Tj/TJ that would run it inside a region, and redacting "into" it would blank every other, legitimately-unredacted occurrence of the same character.
A Form XObject whose own content relies on a font inherited from the page (no Tf of its own, legal per ISO 32000-1 §8.10.1) can now actually be redacted (pdf-go-w7ye, closed): rewriteXObjectDoOperatorsInStream tracks the SAME text-state operators (Tf/Tc/Tw/Tz/TL, saved/restored by q/Q) the page-level text rewriter does, purely to capture the state in effect at each Do, and hands it to redactFormXObject as the form's own rewriter's starting point instead of zero/unknown — closing both the earlier silent-leak failure mode (before pdf-go-oq9i existed) and the later outright-refusal one (after it): a document using this unusual but legal construct is now redacted correctly instead of either leaking or failing outright. The inheritance chain is threaded through nested Form XObjects too, so a form two levels of Do deep continues to resolve correctly. Confirmed by direct reproduction, not just by reading the code — a prior draft of the regression test for this accidentally passed under more than one wrong fix, once because a MERELY PARTIAL redaction broke a secret string's contiguity just as effectively as a complete one for a plain substring-absence check, and once because two hand-picked test secrets happened to share a substring with each other; see redact_apply_inherited_font_internal_test.go's own comments for both.
A page's /Thumb thumbnail, if a producer embedded one, is now dropped (pdf-go-ekp4, closed) rather than left to go on possibly showing a miniature of the pre-redaction page — see this method's step 5a for why dropping rather than regenerating it.
A composite (Type0) font using a non-Identity, variable-width CJK CMap (predefined or embedded) now decodes glyph boundaries through the font's own CMap instead of assuming fixed 2-byte codes, closing a misdecode/mispositioning risk — and a width-lookup-by-raw-code bug that predated it — the same way the text extractor and renderer already did (`pdf-go-eys1`, closed; see `decodeCIDGlyphs`'s own doc comment, `redact_apply_text.go`). This also closes `pdf-go-ifpy`'s word-spacing point as a side effect: Tw now applies only to a single-byte code 32, never a multi-byte one resolving to CID 32, mirroring the extractor exactly. Its other two points are closed too: the renderer now takes `0 Tz` literally (zero-width glyphs) like the extractor and this rewriter, and the q/Q snapshots hold a shared *fontInfo instead of copying the whole font on every q.
The rest: redacting a document that is later saved incrementally (already signed, or AddValidationInfo) keeps the original text in the earlier, byte-preserved revision by design.
Best-effort semantics: partial state on failure. Call ValidateRedactions first to surface problems before mutating.
func (*Document) AttachInvoice ¶ added in v0.10.0
func (d *Document) AttachInvoice(xmlData []byte, opts ...InvoiceOptions) (*PDFAValidationReport, error)
AttachInvoice turns the document into a hybrid e-invoice (Factur-X 1.0 / ZUGFeRD 2.1+): it embeds the caller's CII XML as an associated file, writes the Factur-X XMP properties with the extension schema that declares them, and converts the document to PDF/A-3. Calling it again replaces the invoice. The returned report is the PDF/A result; conversion removes any encryption, as PDF/A requires. Mirrors the intent of Aspose.PDF for .NET's PdfFormat.ZUGFeRD conversion.
func (*Document) Booklet ¶ added in v0.4.0
func (d *Document) 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. The page count is padded up to a multiple of four with blank halves. The receiver is not modified.
Like NUp, this is a production helper (not an ISO 32000 feature) producing an ordinary PDF; it mirrors the intent of Aspose.PDF for .NET's PdfFileEditor.MakeBooklet, adapted to this library's Document API.
func (*Document) ChangePassword ¶ added in v0.4.0
ChangePassword re-encrypts the document with new passwords on the next Save, keeping the current encryption algorithm and permissions. The document must already be open and decrypted (via OpenWithPassword / OpenStreamWithPassword) — the password that unlocked it is the "old" password. If newOwnerPassword is empty it defaults to newUserPassword. Returns an error if the document is not encrypted; to encrypt a plaintext document use SetPassword / SetEncryption. Mirrors Aspose.PDF for .NET's Document.ChangePasswords.
Example:
doc, _ := asposepdf.OpenWithPassword("locked.pdf", "old")
doc.ChangePassword("new", "")
doc.Save("locked.pdf")
func (*Document) ClearInfo ¶ added in v0.3.0
func (d *Document) ClearInfo()
ClearInfo removes the Info dictionary entirely.
func (*Document) ClearPageLabels ¶ added in v0.3.0
func (d *Document) ClearPageLabels()
ClearPageLabels removes the document's /PageLabels entry. (*Page).Label() then falls back to the decimal page number.
func (*Document) ClearXMP ¶ added in v0.3.0
func (d *Document) ClearXMP()
ClearXMP removes the /Catalog/Metadata entry. The underlying stream object becomes unreferenced; call RemoveUnusedObjects to reclaim it.
func (*Document) Collection ¶ added in v0.8.0
func (d *Document) Collection() *Collection
Collection returns the document's portfolio facade.
func (*Document) ConvertToGrayscale ¶ added in v0.4.0
ConvertToGrayscale 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. The geometry, text and layout are untouched. Mirrors the intent of Aspose.PDF for .NET's grayscale conversion.
Coverage: DeviceRGB/DeviceGray/DeviceCMYK and ICCBased colours in content streams and via cs/sc/scn; RGB/CMYK/Indexed/ICCBased raster images (re-encoded as DeviceGray); axial/radial (type 2/3) shadings; and annotation /C, /IC and appearance streams — recursing through Form XObjects. Best-effort / left as-is (documented): Separation/DeviceN tints, Pattern fills, and type 0/4 shading functions, whose colours pass through unconverted.
func (*Document) ConvertToPDFA ¶ added in v0.4.0
func (d *Document) 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. It applies the structural and metadata fixes the library can make safely in place:
- removes encryption;
- removes JavaScript and Launch actions (document-level and per-annotation);
- removes file attachments for PDF/A-1 (including a page-pinned FileAttachmentAnnotation, not just the document-level EmbeddedFiles tree);
- rasterizes any page using transparency for PDF/A-1 (FlattenTransparency, which PDF/A-1 forbids outright; PDF/A-2 and -3 permit it and are left alone);
- sets annotation flags (Print on, Hidden/NoView off);
- embeds non-embedded simple fonts (Standard-14 and other single-byte Type1/TrueType) using the bundled metric-compatible substitutes;
- adds an sRGB ICC OutputIntent (so device colours are colour-managed);
- writes an XMP packet carrying the pdfaid identifier (synced from /Info).
Symbol and ZapfDingbats have no Latin substitute and remain a reported violation; composite (Type0/CJK) and Type3 fonts are not auto-fixed. The returned report lists any remaining issues; when Conformant is true the document satisfies the checks in ValidatePDFA. Mirrors the intent of Aspose.PDF for .NET's Document.Convert(PdfFormat).
The changes are applied to the in-memory document; call Save/WriteTo to write the converted file. An error return (from the transparency-flattening step, the only one that can fail) can leave the document partway converted — pages already rasterized before the failing one keep their new raster content, like ApplyRedactions' documented best-effort/partial-state-on-error behavior; re-running FlattenTransparency or ConvertToPDFA is safe (already vector-content pages that raise no error stay untouched, and an already rasterized page is a no-op the second time, per FlattenTransparency's own idempotence guarantee).
func (*Document) CreateForm ¶ added in v0.4.0
CreateForm creates an empty Form XObject of the given size (points). Draw its content through Canvas(), then place it on pages with Page.AddForm.
func (*Document) CreateTilingPattern ¶ added in v0.4.0
func (d *Document) CreateTilingPattern(width, height float64) *TilingPattern
CreateTilingPattern creates an empty tiling pattern whose cell is width×height points. Draw the cell through Canvas(), then fill shapes with it via ShapeStyle.FillTiling.
func (*Document) CreateType3Font ¶ added in v0.8.0
CreateType3Font returns an empty Type3 font bound to the document.
func (*Document) DeletePage ¶ added in v0.3.0
DeletePage removes the page at the given 1-based number. Mirrors Aspose.PDF for .NET's Document.Pages.Delete(int).
Example:
err = doc.DeletePage(2) // drop the second page
func (*Document) DeletePages ¶ added in v0.3.0
DeletePages removes the pages at the given 1-based page numbers. Repeated numbers are de-duplicated and argument order does not matter; the surviving pages keep their relative order. Every number is validated before any page is removed, so on error the document is left unchanged. Mirrors Aspose.PDF for .NET's Document.Pages.Delete(int[]).
A document must keep at least one page: a call that would remove every page returns an error and changes nothing. Passing no page numbers is an error (unlike .NET's parameterless Pages.Delete(), which clears all pages — that would leave an unusable zero-page document).
Removed pages no longer appear in the document or in saved output. The underlying objects are not eagerly reclaimed (matching Reorder); they fall out of the written page tree and can be garbage-collected by the writer's reachability pass.
Example:
err = doc.DeletePages(1, 3) // drop the first and third pages
func (*Document) EmbeddedFiles ¶ added in v0.4.0
func (d *Document) EmbeddedFiles() *EmbeddedFiles
EmbeddedFiles returns the document-level embedded-file collection.
func (*Document) Extract ¶
Extract returns a new Document containing only the pages in the specified ranges. Ranges are 1-based and inclusive. Pages appear in the order the ranges are listed.
Example:
extracted, err := doc.Extract(asposepdf.PageRange{1, 3}, asposepdf.PageRange{5, 5})
extracted.Save("output.pdf")
Example ¶
Extract selected page ranges into a new document.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.Open("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
out, err := doc.Extract(
pdf.PageRange{From: 1, To: 2},
pdf.PageRange{From: 4, To: 4},
)
if err != nil {
log.Fatal(err)
}
fmt.Println("extracted:", out.PageCount(), "pages")
}
Output: extracted: 3 pages
func (*Document) ExtractImages ¶
ExtractImages returns images from all pages (one slice per page).
func (*Document) ExtractText ¶
func (d *Document) ExtractText(opts ...TextExtractOptions) ([]string, error)
ExtractText returns the text content of each page (one entry per page, 0-indexed). An optional TextExtractOptions selects the extraction mode.
Example ¶
Extract text from every page in visual reading order.
package main
import (
"fmt"
"log"
"strings"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.Open("testdata/Hello world.pdf")
if err != nil {
log.Fatal(err)
}
pages, err := doc.ExtractText()
if err != nil {
log.Fatal(err)
}
fmt.Println(strings.TrimSpace(pages[0]))
}
Output: Hello, world!
func (*Document) ExtractTextWithLayout ¶
ExtractTextWithLayout returns structured text lines for each page. The returned slice has one entry per page (0-indexed).
func (*Document) FiguresNeedingAltText ¶ added in v0.6.0
FiguresNeedingAltText walks the document's logical structure tree and returns every /Figure element that lacks alternate text (/Alt or /ActualText), each paired with the image it brackets when that image can be located. Returns nil for an untagged document. Mirrors the discovery half of Aspose.PDF for .NET's accessibility tooling; the description side lives in the ai subpackage (ImageDescriptionCopilot.FillAltTexts).
func (*Document) Flatten ¶ added in v0.3.0
Flatten 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. Equivalent to (*Document).Form().Flatten().
Mirrors Aspose.PDF for .NET's Document.Flatten (which flattens form fields). Annotations are not affected here — flatten those via a page's AnnotationCollection.Flatten or an individual Annotation.Flatten.
func (*Document) FlattenTransparency ¶ added in v0.10.0
func (d *Document) FlattenTransparency(opts ...FlattenTransparencyOptions) (int, error)
FlattenTransparency rasterizes every page that uses transparency into a single opaque full-page image, leaving pages without transparency untouched. Returns the number of pages rasterized. A flattened page's old content-stream and resource objects (the very transparency constructs this method exists to remove) become unreachable; when at least one page was flattened, FlattenTransparency also calls RemoveUnusedObjects so those orphans are actually gone from the file — otherwise ValidatePDFA's TRANSPARENCY check, which scans every object rather than only reachable ones, would still trip on them.
Example ¶
Rasterize only the pages that actually use transparency (here, a semi-transparent fill), leaving every other page fully vector.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
fill := pdf.Color{R: 1, G: 0, B: 0, A: 0.5}
if err := page.DrawRectangle(pdf.Rectangle{LLX: 50, LLY: 700, URX: 300, URY: 780},
pdf.ShapeStyle{FillColor: &fill}); err != nil {
log.Fatal(err)
}
n, err := doc.FlattenTransparency()
if err != nil {
log.Fatal(err)
}
fmt.Println("pages flattened:", n)
}
Output: pages flattened: 1
func (*Document) Form ¶
Form returns the document's AcroForm. Always non-nil; for a document without /AcroForm, an empty Form is returned (Fields() is empty, Field(name) returns nil, HasField returns false).
func (*Document) GenerateTOC ¶ added in v0.4.0
func (d *Document) 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. Outline nesting becomes the indent level. Returns the number of pages added (0 when the document has no outline entries).
Page numbers and GoTo links reflect the final page order after the TOC pages are inserted. Mirrors Aspose.PDF for .NET's TocInfo-driven TOC generation, sourced from the document outline.
Example ¶
Generate a table of contents from the document outline. The TOC is inserted as new page(s) at the front; entries link to their targets.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
doc.AddBlankPageFromFormat(pdf.PageFormatA4)
body, _ := doc.Page(1)
chapter := pdf.NewOutlineItemCollection(doc)
chapter.SetTitle("Chapter 1")
chapter.SetDestination(pdf.NewDestinationFit(body))
if err := doc.Outlines().Add(chapter); err != nil {
log.Fatal(err)
}
added, err := doc.GenerateTOC(pdf.TOCOptions{Title: "Table of Contents"})
if err != nil {
log.Fatal(err)
}
fmt.Println("TOC pages added:", added, "| total pages:", doc.PageCount())
}
Output: TOC pages added: 1 | total pages: 3
func (*Document) ImageInfos ¶
ImageInfos returns image metadata for all pages (one slice per page) without decoding pixel data.
func (*Document) ImportForm ¶ added in v0.4.0
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. A form already belonging to this document is returned unchanged.
func (*Document) Info ¶ added in v0.3.0
func (d *Document) Info() (DocumentInfo, error)
Info returns the Info-dictionary metadata from this document. Mirrors Aspose.PDF for .NET's Document.Info; the XMP store is XMP().
func (*Document) InsertBlankPage ¶
InsertBlankPage inserts a blank page at the given 1-based position. Existing pages at and after that position shift by one.
func (*Document) InsertBlankPageFromFormat ¶
func (d *Document) InsertBlankPageFromFormat(position int, format PageFormat) error
InsertBlankPageFromFormat inserts a blank page at the given position using a predefined page format.
func (*Document) Invoice ¶ added in v0.10.0
Invoice returns the e-invoice embedded in the document, or (nil, nil) when the document is not one. It reads Factur-X 1.0 / ZUGFeRD 2.1+, ZUGFeRD 2.0 and ZUGFeRD 1.0 files: the attachment is found by the name the XMP gives, else by the names the standards use.
func (*Document) JavaScript ¶ added in v0.4.0
func (d *Document) JavaScript() *JavaScriptCollection
JavaScript returns the document-level JavaScript collection. Always non-nil. Mirrors Aspose.PDF for .NET's Document.JavaScript.
func (*Document) Layers ¶ added in v0.4.0
Layers returns the document's layers (OCGs), in /OCProperties/OCGs order. Empty for a document with no optional content.
func (*Document) LoadFont ¶
LoadFont reads a TTF file, parses it, embeds it into the document, and returns a Font that can be used in TextStyle.Font. The full TTF is embedded without subsetting, so large fonts increase output size. The returned Font is bound to this document and must not be used with pages from other documents.
func (*Document) LoadFontByName ¶ added in v0.4.0
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. It is the by-name counterpart to LoadFont(path): callers that know a family ("Calibri", "Verdana", "Arial" bold) need not locate the file themselves. A sub-font of a .ttc collection is re-wrapped as a standalone sfnt before embedding. Standard-14 family names resolve to their installed metric-equivalents (Helvetica → Arial, Times → Times New Roman, …); for a non-embedded Standard-14 font use the package-level vars (FontHelvetica, …) instead. Returns an error if no matching font is registered or installed. Mirrors the intent of Aspose.PDF for .NET's FontRepository.FindFont.
func (*Document) LoadFontFromStream ¶
LoadFontFromStream is like LoadFont but reads from an io.Reader.
func (*Document) LoadSVG ¶ added in v0.2.0
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.
func (*Document) LoadSVGFromStream ¶ added in v0.2.0
LoadSVGFromStream is the io.Reader variant of LoadSVG.
func (*Document) NUp ¶ added in v0.4.0
func (d *Document) 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. 2×2 for 4-up). Each source page is wrapped in a Form XObject and scaled to fit its cell, preserving aspect ratio and centered. Sheets are filled until every page is placed; the last sheet may have empty cells. The receiver is not modified.
This is a page-production helper (not an ISO 32000 feature); the output is an ordinary, spec-compliant PDF. It mirrors the intent of Aspose.PDF for .NET's PdfFileEditor.MakeNUp, adapted to this library's Document API.
func (*Document) NamedDestinations ¶
func (d *Document) NamedDestinations() *NamedDestinations
NamedDestinations returns the document's named-destination collection. Always non-nil. Lazy-initialized on first call from /Catalog/Names/Dests (modern PDF 1.2+ name tree) merged with legacy /Catalog/Dests; on collision the /Names/Dests entry wins.
Mirrors Aspose.PDF for .NET's Document.NamedDestinations property.
func (*Document) NeedsRepair ¶ added in v0.10.0
NeedsRepair reports whether the document was recovered rather than read as written. Saving it writes a clean file, so this is the moment to warn a user that the input was damaged.
func (*Document) NewFlow ¶ added in v0.4.0
func (d *Document) NewFlow(opts FlowOptions) *Flow
NewFlow creates a flow that renders into the document d.
Example ¶
Generate a paginated document with the flow layout: headings, paragraphs and tables are laid out top-to-bottom with automatic page breaks.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
flow := doc.NewFlow(pdf.FlowOptions{})
flow.AddHeading(1, "Quarterly Report", pdf.TextStyle{})
flow.AddParagraph("Revenue grew in every region this quarter.", pdf.TextStyle{Size: 11})
flow.AddList([]string{"North: +12%", "South: +8%"}, false, pdf.TextStyle{Size: 11})
pages, err := flow.Render()
if err != nil {
log.Fatal(err)
}
fmt.Println("pages:", pages)
}
Output: pages: 1
func (*Document) OpenAction ¶ added in v0.4.0
OpenAction 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. A GoTo open-action has its destination page resolved to a 1-based PageNum. When /OpenAction is a bare destination array (a "go to page on open" without an explicit action dict) this returns nil — read the destination via NamedDestinations / the page tree instead.
Mirrors Aspose.PDF for .NET's Document.OpenAction.
func (*Document) Optimize ¶ added in v0.6.0
func (d *Document) Optimize(opts OptimizationOptions) (OptimizationResult, error)
Optimize reduces the document's size in place per opts and returns a report of what changed. Call before Save/WriteTo. Mirrors Aspose.PDF for .NET's Document.OptimizeResources(OptimizationOptions).
Order: remove unused objects (a pre-pass, see below) → images → fonts (unembed, then subset what's left embedded) → compress streams → dedupe streams → remove unused objects again (so anything a transform orphans is reclaimed last). RemovedObjects reports the sum of both passes.
The pre-pass was added because every (*Page).AddText call (and every table cell) used to replace a page's /Contents with a brand-new stream object holding the whole concatenated content, leaving the old one dead in d.objects with nothing referencing it any more — on a page built from many small AddText calls this meant many dead copies piling up, which RemoveDuplicateStreams and CompressStreams would otherwise both walk and hash/compress for nothing before the final pass cleared them away; on a 20-page, 200-calls-per-page document this made Optimize ~25x slower for no change in the end result. Reported with a clear reproduction and a correct diagnosis by Kare-ino (GitHub issue #9) — thank you. That root cause is now closed at the source (appendToContentStream/prependToContentStream, content_append.go, pdf-go-jbiu/GitHub issue #16: an append now adds one array entry to /Contents instead of rewriting a combined stream, so nothing is ever abandoned), so a document built with the current code produces no such copies in the first place — TestOptimizeManyAddTextCallsStaysFast still pins the speed guarantee itself, now trivially satisfied rather than needing the pre-pass's help. The pre-pass is kept anyway as cheap, harmless insurance against OTHER sources of dead objects this method doesn't know about: a third-party file opened with its own pre-existing orphaned content, or this library's own full-content-replace call sites (ApplyRedactions, ConvertToGrayscale, ImageInfo.Remove, FlattenTransparency — all via replacePageContents or an equivalent, which still swap in one new stream and abandon whatever /Contents pointed at before). Running the same removal once at the very start changes nothing about which objects survive Optimize overall, only when the already-dead ones are noticed, since nothing later in this method can make a genuinely unreachable object reachable again.
Example ¶
Shrink a document with the unified lossless optimizer (unused objects, font subsetting, stream compression, duplicate-stream dedup).
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
font, err := doc.LoadFont("testdata/DejaVuSans.ttf")
if err != nil {
log.Fatal(err)
}
page, _ := doc.Page(1)
_ = page.AddText("Привет, мир!", pdf.TextStyle{Font: font, Size: 18},
pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})
res, err := doc.Optimize(pdf.DefaultOptimizationOptions())
if err != nil {
log.Fatal(err)
}
fmt.Println("fonts subset:", res.SubsettedFonts)
}
Output: fonts subset: 1
func (*Document) OptimizeImages ¶
func (d *Document) OptimizeImages(opts OptimizeImageOptions) (int, error)
OptimizeImages optimizes all images in the document to reduce file size. Returns the number of images optimized.
func (*Document) Outlines ¶
func (d *Document) Outlines() *OutlineItemCollection
Outlines returns the document's root outline collection. Always non-nil — an empty collection is returned for documents without outline content. Mirrors Aspose.PDF for .NET's Document.Outlines.
Example ¶
Build a bookmark (outline) tree with clickable destinations.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
item := pdf.NewOutlineItemCollection(doc)
item.SetTitle("Chapter 1")
item.SetDestination(pdf.NewDestinationFit(page))
if err := doc.Outlines().Add(item); err != nil {
log.Fatal(err)
}
fmt.Println(doc.Outlines().Count(), doc.Outlines().At(0).Title())
}
Output: 1 Chapter 1
func (*Document) Paragraphs ¶ added in v0.4.0
func (d *Document) Paragraphs() ([]PageMarkup, error)
Paragraphs returns the structured text of every page.
func (*Document) Permissions ¶
func (d *Document) 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. For a document opened via OpenWithPassword, the permissions reflect the /P value read from the original file. Returns the zero Permissions and false for unencrypted documents.
func (*Document) RemoveEncryption ¶
func (d *Document) RemoveEncryption()
RemoveEncryption clears any previously configured encryption (passwords and permissions) so the next Save produces a plaintext PDF. This is the way to "decrypt" an encrypted file via the public API: open with a password, call RemoveEncryption, save.
Example:
doc, _ := asposepdf.OpenWithPassword("locked.pdf", "secret")
doc.RemoveEncryption()
doc.Save("plain.pdf")
func (*Document) RemoveOpenAction ¶ added in v0.4.0
func (d *Document) RemoveOpenAction()
RemoveOpenAction clears any /Catalog/OpenAction. Equivalent to SetOpenAction(nil).
func (*Document) RemoveUnusedObjects ¶
RemoveUnusedObjects removes objects from the document that are not reachable from any page or from the document catalog (/Root). The catalog is a GC root in its own right — /Metadata, /OutputIntents, /AcroForm, /StructTreeRoot, /Names and similar catalog-only-referenced content is never dropped just because no page happens to reference it too. Returns the number of objects removed.
func (*Document) RenderImage ¶ added in v0.3.0
RenderImage renders the 1-based page number to an image.
Example ¶
Render a page to a raster image with the built-in dependency-free renderer.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
_ = page.AddText("Preview me", pdf.TextStyle{Size: 24},
pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})
img, err := doc.RenderImage(1, pdf.RenderOptions{DPI: 96})
if err != nil {
log.Fatal(err)
}
fmt.Println("rendered:", img.Bounds().Dx() > 0 && img.Bounds().Dy() > 0)
}
Output: rendered: true
func (*Document) RenderTIFF ¶ added in v0.3.0
RenderTIFF renders the document to a single multi-page TIFF written to w. With no pageNums every page is rendered in order; otherwise just the listed 1-based pages, in the given order. Pages are rendered one at a time, so peak memory is a single page image. Mirrors Aspose.PDF for .NET's TiffDevice whole-document output.
func (*Document) Reorder ¶
Reorder rearranges pages according to order, a slice of 1-based page numbers. Pages may be repeated or omitted.
Example — reverse a 4-page document:
err = doc.Reorder([]int{4, 3, 2, 1})
func (*Document) RepairReport ¶ added in v0.10.0
func (d *Document) RepairReport() RepairReport
RepairReport returns what had to be reconstructed to open the document. Mirrors the intent of Aspose.PDF for .NET's Document.IsRepairNeeded, which reports the same condition through an out parameter.
func (*Document) ReplaceText ¶ added in v0.4.0
func (d *Document) ReplaceText(old, replacement string, opts ...ReplaceOptions) (int, error)
ReplaceText replaces every occurrence of old with replacement across all pages, returning the total number of replacements. See (*Page).ReplaceText for the replacement strategy and limitations.
Example ¶
Find and replace every occurrence of a string across the document.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
_ = page.AddText("Draft version. Draft only.",
pdf.TextStyle{Size: 14}, pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})
n, err := doc.ReplaceText("Draft", "Final")
if err != nil {
log.Fatal(err)
}
fmt.Println("replaced:", n)
}
Output: replaced: 2
func (*Document) Rotate ¶
func (d *Document) Rotate(angle RotationAngle, pageNums ...int) error
Rotate rotates selected pages clockwise by angle (Rotate90, Rotate180, or Rotate270). The rotation is added to any existing rotation. If no page numbers are given, all pages are rotated. Page numbers are 1-based.
Example:
err = doc.Rotate(asposepdf.Rotate90) // rotate all pages err = doc.Rotate(asposepdf.Rotate180, 1, 3) // rotate pages 1 and 3
Example ¶
Rotate selected pages by 90 degrees clockwise. Subsequent calls accumulate.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.Open("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
if err := doc.Rotate(pdf.Rotate90, 1, 3); err != nil {
log.Fatal(err)
}
p1, _ := doc.Page(1)
p2, _ := doc.Page(2)
fmt.Println("page1:", p1.Rotation(), "page2:", p2.Rotation())
}
Output: page1: 90 page2: 0
func (*Document) Sanitize ¶ added in v0.11.0
func (d *Document) Sanitize(opts HiddenDataSanitizationOptions) (HiddenDataSanitizationResult, error)
Sanitize removes hidden data per opts and returns a report of what changed. Mirrors the intent of Aspose.PDF for .NET's Aspose.Pdf.Security.HiddenDataSanitization.HiddenDataSanitizer + HiddenDataSanitizationOptions, composed here over this library's existing primitives (ClearInfo/ClearXMP, EmbeddedFiles, JavaScript/action stripping, ApplyRedactions, annotation deletion, Document.Flatten, optional-content removal, page rasterization, OptimizeImages) rather than new mechanics.
Order: metadata -> attachments -> scripts/actions -> search index and private data -> flatten forms -> flatten layers -> apply redactions and remove annotations -> rasterize pages (or recompress existing images). Rasterization runs last, after every other step has already narrowed what there is to rasterize, matching Aspose's own ordering note. RemoveUnusedObjects runs once at the end when anything was removed, reclaiming whatever the steps above orphaned (OCG dictionaries, filespecs, action objects, …).
On error, res still reports whatever an earlier step already completed in this call, including a step that failed partway through (e.g. ConvertPagesToImages: res.PagesRasterized counts the pages already rasterized in place before the failing one) — mirroring FlattenTransparency's own partial-progress-on-error convention.
func (*Document) SaveDocx ¶ added in v0.7.0
func (d *Document) SaveDocx(path string, opts ...DocSaveOptions) error
SaveDocx writes the document as a Word (.docx) file.
func (*Document) SaveEpub ¶ added in v0.7.0
func (d *Document) SaveEpub(path string, opts ...EpubSaveOptions) error
SaveEpub writes the document as an EPUB file.
func (*Document) SaveHTML ¶ added in v0.5.0
func (d *Document) SaveHTML(outputPath string, opts ...HTMLSaveOptions) error
SaveHTML 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 <stem>_p<N>.html.
func (*Document) SaveLinearized ¶ added in v0.4.0
SaveLinearized 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. The result is an ordinary PDF that any reader opens normally. Encryption and signing are not supported together with linearization. Mirrors the intent of Aspose.PDF for .NET's linearized save.
func (*Document) SaveMarkdown ¶ added in v0.7.0
func (d *Document) SaveMarkdown(path string, opts ...MarkdownSaveOptions) error
SaveMarkdown writes the document as a Markdown file. Images go to opts.ImageDir (default "<stem>_files") unless EmbedImages/NoImages or an ImageWriter says otherwise. Mirrors the shape of SaveHTML.
func (*Document) SaveSVG ¶ added in v0.7.0
func (d *Document) SaveSVG(path string, opts ...SVGSaveOptions) error
SaveSVG exports the document's pages as SVG files. A single selected page is written to path itself; several pages become sibling files "<stem>_pN.svg" (N = the source page number), like the HTML exporter's SplitPages. Mirrors Aspose.PDF for .NET's Document.Save(SaveFormat.Svg).
func (*Document) SaveXlsx ¶ added in v0.8.0
func (d *Document) SaveXlsx(path string, opts ...XlsxSaveOptions) error
SaveXlsx writes the document as an Excel (.xlsx) workbook file.
func (*Document) SearchText ¶ added in v0.3.0
func (d *Document) 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. Each TextMatch carries the page it was found on. See (*Page).SearchText for matching semantics.
func (*Document) SetEncryption ¶
func (d *Document) SetEncryption(opts EncryptionOptions)
SetEncryption configures every encryption-related setting at once from an EncryptionOptions struct. It replaces any prior configuration set by SetPassword or SetPermissions. See EncryptionOptions for field-level semantics; nil Permissions means "grant all".
SetPassword and SetPermissions remain convenient for one-liner updates and compose cleanly either before or after SetEncryption.
Example:
doc.SetEncryption(asposepdf.EncryptionOptions{
UserPassword: "user",
OwnerPassword: "owner",
Permissions: &asposepdf.Permissions{AllowPrint: true, AllowCopy: true},
})
doc.Save("restricted.pdf")
Example ¶
Encrypt a document with AES-128 and a user password.
package main
import (
"bytes"
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
doc.SetEncryption(pdf.EncryptionOptions{
UserPassword: "secret",
OwnerPassword: "owner-secret",
Permissions: &pdf.Permissions{AllowPrint: true, AllowCopy: true},
Algorithm: pdf.EncryptionAlgAES128,
})
var buf bytes.Buffer
if _, err := doc.WriteTo(&buf); err != nil {
log.Fatal(err)
}
// The file is now encrypted; Open returns ErrEncrypted.
if _, err := pdf.OpenStream(&buf); err != nil {
fmt.Println("encrypted")
}
}
Output: encrypted
func (*Document) SetInfo ¶ added in v0.3.0
func (d *Document) SetInfo(info DocumentInfo)
SetInfo replaces the document's Info dictionary with the given metadata. Empty string fields are omitted. This is a full replacement. Mirrors assigning Aspose.PDF for .NET's Document.Info.
func (*Document) SetOpenAction ¶ added in v0.4.0
SetOpenAction sets the action run when the document opens. A nil action clears /OpenAction. A GoTo action is bound to this document so its destination is written as a proper page reference.
Mirrors Aspose.PDF for .NET's Document.OpenAction setter.
func (*Document) SetPageLabels ¶ added in v0.3.0
func (d *Document) SetPageLabels(ranges []PageLabelRange) error
SetPageLabels installs the document's /PageLabels number tree so PDF viewers display labels like "i, ii, 1, 2, …" in the navigation pane and page indicators. (*Page).Label() also reads from this tree.
Ranges must be sorted by StartPage in strictly ascending order and the first range must begin at page 1; otherwise an error is returned. Passing a nil/empty slice clears any existing labels.
Per PDF spec §12.4.2, /PageLabels is a number tree keyed by 0-based page index. This implementation emits a single-leaf number tree with one /Nums array, which is valid for any number of ranges.
Example ¶
Author logical page labels (front matter i, ii, then body 1, 2, …).
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
_ = doc.AddBlankPageFromFormat(pdf.PageFormatA4)
_ = doc.AddBlankPageFromFormat(pdf.PageFormatA4)
err := doc.SetPageLabels([]pdf.PageLabelRange{
{StartPage: 1, Style: pdf.PageLabelRomanLower},
{StartPage: 3, Style: pdf.PageLabelDecimal},
})
if err != nil {
log.Fatal(err)
}
p2, _ := doc.Page(2)
p3, _ := doc.Page(3)
fmt.Println(p2.Label(), p3.Label())
}
Output: ii 1
func (*Document) SetPassword ¶
SetPassword configures the document to be encrypted when saved. userPassword is required to open; ownerPassword controls permissions. If ownerPassword is empty, it defaults to userPassword.
Password encoding: The password bytes are passed unchanged to the PDF Standard Security Handler (RC4-128, V=2 R=3). For ASCII passwords this matches both the PDF specification and every major PDF viewer. For non-ASCII passwords the raw UTF-8 bytes are used, which is compatible with pypdf 6.x and Adobe Acrobat DC but may not be accepted by strictly legacy PDFDocEncoding-only viewers (e.g. Adobe Reader 9 and older). For international passwords with guaranteed interop, AES-256 (R=6) is the only complete solution — not yet supported by this library.
Example:
doc.SetPassword("secret", "")
doc.Save("encrypted.pdf")
func (*Document) SetPermissions ¶
func (d *Document) SetPermissions(p Permissions)
SetPermissions configures what operations a viewer allows on the encrypted document (printing, copying, modifying, etc.). Permissions only take effect if the document is also encrypted — call SetPassword to set the user and owner passwords. If SetPermissions is never called, all operations are allowed by default, matching the historical behavior.
Example:
doc.SetPassword("secret", "owner-secret")
doc.SetPermissions(asposepdf.Permissions{AllowPrint: true, AllowCopy: true})
doc.Save("restricted.pdf")
func (*Document) SetRotation ¶
func (d *Document) SetRotation(angle RotationAngle, pageNums ...int) error
SetRotation sets selected pages to exactly angle (Rotate0, Rotate90, Rotate180, or Rotate270), replacing any existing rotation. If no page numbers are given, all pages are affected. Page numbers are 1-based.
Example:
err = doc.SetRotation(asposepdf.Rotate90) // set all pages to 90° err = doc.SetRotation(asposepdf.Rotate0, 1, 3) // reset pages 1 and 3 to 0°
func (*Document) SetSVGFontResolver ¶ added in v0.2.0
func (d *Document) SetSVGFontResolver(fn SVGFontResolver)
SetSVGFontResolver installs a custom resolver. The renderer queries it first for each SVG font-family encountered; on nil return, falls back to the heuristic. Use this to plug in embedded TTF fonts (Cyrillic, etc.) loaded via Document.LoadFont.
Pass nil to clear a previously-set resolver (revert to heuristic-only).
func (*Document) SetXMP ¶ added in v0.3.0
func (d *Document) SetXMP(meta XMPMetadata) error
SetXMP 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). Replaces any existing packet. Passing an empty XMPMetadata writes an empty (but valid) packet; use ClearXMP to remove metadata entirely.
func (*Document) SetXMPRaw ¶ added in v0.3.0
SetXMPRaw stores data verbatim as the /Catalog/Metadata stream — an escape hatch for callers that produce their own XMP packet. The bytes are written uncompressed so external tools can locate the xpacket markers. Reuses the existing Metadata object if present.
func (*Document) Sign ¶ added in v0.4.0
func (d *Document) Sign(opts SignOptions) error
Sign configures a digital signature applied on the next Save/WriteTo. Mirrors the intent of Aspose.PDF for .NET's PdfFileSignature.Sign, adapted to this library's options paradigm. Returns an error for a missing certificate or key.
Example ¶
Sign a document with an ECDSA key and verify the signature. Certificates are ordinarily loaded from a key store; here one is generated in memory.
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
cryptorand "crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"fmt"
"log"
"math/big"
"time"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
key, _ := ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "Jane Signer"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature,
}
der, _ := x509.CreateCertificate(cryptorand.Reader, tmpl, tmpl, &key.PublicKey, key)
cert, _ := x509.ParseCertificate(der)
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
if err := doc.Sign(pdf.SignOptions{Certificate: cert, PrivateKey: key, Reason: "Approval"}); err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
if _, err := doc.WriteTo(&buf); err != nil {
log.Fatal(err)
}
signed, _ := pdf.OpenStream(&buf)
sigs, err := signed.VerifySignatures()
if err != nil {
log.Fatal(err)
}
fmt.Printf("signatures: %d, valid: %v, reason: %s\n", len(sigs), sigs[0].Valid, sigs[0].Reason)
}
Output: signatures: 1, valid: true, reason: Approval
func (*Document) SignatureNames ¶ added in v0.10.0
SignatureNames returns the field name of every signature in the document, in document order. Mirrors Aspose.PDF for .NET's PdfFileSignature.GetSignatureNames.
func (*Document) Split ¶
Split returns each page of the document as a separate *Document.
Example:
parts, err := doc.Split()
for i, p := range parts {
p.Save(fmt.Sprintf("page%03d.pdf", i+1))
}
Example ¶
Split a multi-page document into single-page documents.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.Open("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
parts, err := doc.Split()
if err != nil {
log.Fatal(err)
}
fmt.Println("parts:", len(parts))
}
Output: parts: 4
func (*Document) SubsetFonts ¶ added in v0.3.0
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. /W and /ToUnicode are also trimmed to the used glyphs.
Call this once, AFTER all text has been added and just before Save / WriteTo: adding more text that introduces new glyphs after subsetting would reference glyphs the subset no longer contains. Fonts with no drawn glyphs are skipped. Returns the number of fonts subsetted.
Typical reduction is from ~300-700 KB per embedded font down to a few KB, since only the used outlines survive. Mirrors the post-processing shape of (*Document).OptimizeImages.
func (*Document) SyncInfoToXMP ¶ added in v0.3.0
SyncInfoToXMP 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). Info Title/Author/Subject/Keywords/Creator/Producer/dates map to the corresponding XMP properties. No-op-safe when /Info is absent.
func (*Document) TaggedContent ¶ added in v0.4.0
func (d *Document) TaggedContent() *TaggedContent
TaggedContent returns the document's tagged-content facade, creating the structure tree and the /MarkInfo, /ViewerPreferences and /StructTreeRoot catalog entries on first call. Idempotent.
func (*Document) UnembedFonts ¶ added in v0.10.0
UnembedFonts drops the embedded font program from every simple font whose name and metrics are those of a Helvetica/Times/Courier Standard-14 face (see unembedFonts for the full eligibility rule), then reclaims the now-orphaned font-program stream objects. Call before Save/WriteTo. Returns the number of fonts unembedded. Mirrors Aspose.PDF for .NET's OptimizationOptions.UnembedFonts (phase 2 of the Optimize epic, pdf-go-o0wy/pdf-go-vb4b) — opt-in (not part of DefaultOptimizationOptions) since, unlike SubsetFonts, it can change how the document actually looks in a viewer that substitutes a different Arial/Times/Courier clone.
func (*Document) ValidatePDFA ¶ added in v0.4.0
func (d *Document) ValidatePDFA(format PDFAFormat) *PDFAValidationReport
ValidatePDFA checks the document against a PDF/A "b"-level conformance profile and returns a report of violations. It is a read-only diagnostic — it never mutates the document; use ConvertToPDFA to produce a conformant file.
Checks performed (ISO 19005-1/2/3, basic level): an XMP metadata packet with a matching pdfaid:part/conformance; every font embedded (no Standard-14 reliance); no encryption; no JavaScript or Launch actions; an ICC OutputIntent when device colours are used; no transparency for PDF/A-1; annotation flags (Print set, Hidden/NoView clear) and appearance streams; an uncompressed /Metadata stream; no LZWDecode (PDF/A-1); and no embedded files for PDF/A-1.
Scope: the "a" (tagged/accessible) levels are not validated. This mirrors the intent of Aspose.PDF for .NET's Document.Validate(PdfFormat) but returns a structured report instead of writing an XML log.
func (*Document) ValidatePDFUA ¶ added in v0.4.0
func (d *Document) ValidatePDFUA() *PDFUAValidationReport
ValidatePDFUA checks the document against a subset of PDF/UA-1 (ISO 14289-1, universal accessibility) and returns a report of violations. It is a read-only diagnostic — it never mutates the document.
Checks performed: the document is marked as Tagged PDF (/MarkInfo /Marked) and carries a logical structure tree (/StructTreeRoot with kids and a /ParentTree); a natural-language default (/Lang); a document title (in /Info or XMP) that is shown rather than the file name (/ViewerPreferences /DisplayDocTitle); every /Figure (and /Formula) structure element has alternate text (/Alt or /ActualText); and accessibility is not blocked by encryption permissions.
Scope: this validates the structural prerequisites of PDF/UA. It does not verify full reading-order correctness, heading nesting, table-cell scoping or that every content item is tagged — those need deeper semantic analysis (and a real validator such as PAC or veraPDF for final sign-off). Mirrors the intent of Aspose.PDF for .NET's Document.Validate(PdfFormat.PDF_UA_1).
func (*Document) ValidateRedactions ¶
ValidateRedactions performs a pre-flight dry-run check on every page that has at least one RedactAnnotation: its content stream must parse, and every Form XObject a redaction region intersects must be one ApplyRedactions can safely redact into — a resolvable /BBox, an invertible placement matrix, and nesting/work within maxFormRedactDepth/maxFormRedactWork (see unsafeFormXObjectName; most intersecting Form XObjects ARE safely redactable since pdf-go-w5hl — this only flags the genuinely unsafe cases). Also checks every non-/Redact annotation's own /AP appearance stream(s) overlapping a region the same way (unsafeAnnotationAppearance; pdf-go-xp2u) — an annotation's placement matrix is always invertible by construction (it comes from ISO 32000-1 §12.5.5's scale+translate algorithm, not an arbitrary `cm`), so only a missing/malformed /BBox can make one unsafe here. Returns the first problem found, or nil if every redact-bearing page is safe to process. Pages without redact annotations are not inspected.
Callers should invoke this before ApplyRedactions to surface problems up-front; ApplyRedactions has best-effort semantics and may leave partial state on failure.
func (*Document) VerifySignature ¶ added in v0.10.0
func (d *Document) VerifySignature(fieldName string, opts ...ValidationOptions) (SignatureVerification, error)
VerifySignature verifies the one signature held by the named field. The error reports a missing field or missing source bytes; a signature that is present but invalid comes back in the result, with the reason in Err — there is nothing exceptional about a document failing to verify. Mirrors Aspose.PDF for .NET's PdfFileSignature.VerifySignature(sigName).
func (*Document) VerifySignatures ¶ added in v0.4.0
func (d *Document) VerifySignatures(opts ...ValidationOptions) ([]SignatureVerification, error)
VerifySignatures verifies every digital signature in the document and returns one result per signature field, in document order. The document must have been opened from a file or stream (the raw bytes are needed to resolve each /ByteRange). Trust-chain validation is left to the caller — Certificate is returned so it can be checked against a trust store.
Mirrors the intent of Aspose.PDF for .NET's PdfFileSignature.VerifySignature.
func (*Document) WriteDocx ¶ added in v0.7.0
func (d *Document) WriteDocx(w io.Writer, opts ...DocSaveOptions) error
WriteDocx writes the document as a Word (.docx) package to w.
func (*Document) WriteEpub ¶ added in v0.7.0
func (d *Document) WriteEpub(w io.Writer, opts ...EpubSaveOptions) error
WriteEpub writes the document as an EPUB 3 package to w.
func (*Document) WriteHTML ¶ added in v0.5.0
func (d *Document) WriteHTML(w io.Writer, opts ...HTMLSaveOptions) error
WriteHTML 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.
Example ¶
Export the document as self-contained HTML with a selectable text layer.
package main
import (
"bytes"
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
_ = page.AddText("Hello HTML", pdf.TextStyle{Size: 18},
pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})
var html bytes.Buffer
if err := doc.WriteHTML(&html, pdf.HTMLSaveOptions{Mode: pdf.HTMLModeText}); err != nil {
log.Fatal(err)
}
fmt.Println("has text spans:", bytes.Contains(html.Bytes(), []byte("<span")))
}
Output: has text spans: true
func (*Document) WriteMarkdown ¶ added in v0.7.0
func (d *Document) WriteMarkdown(w io.Writer, opts ...MarkdownSaveOptions) error
WriteMarkdown writes the document as Markdown to w. Without an ImageWriter and with EmbedImages unset, images are skipped (a stream has no natural place for files).
Example ¶
Export a document as GFM Markdown (the reverse of the Markdown renderer).
package main
import (
"fmt"
"log"
"strings"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc, err := pdf.MarkdownToDocumentFromStream(strings.NewReader("# Title\n\nBody text.\n"))
if err != nil {
log.Fatal(err)
}
var out strings.Builder
if err := doc.WriteMarkdown(&out); err != nil {
log.Fatal(err)
}
fmt.Println(strings.Split(out.String(), "\n")[0])
}
Output: # Title
func (*Document) WriteToLinearized ¶ added in v0.4.0
WriteToLinearized writes the document as a linearized PDF to w (implements an io.WriterTo-style contract). See SaveLinearized.
func (*Document) WriteXlsx ¶ added in v0.8.0
func (d *Document) WriteXlsx(w io.Writer, opts ...XlsxSaveOptions) error
WriteXlsx writes the document as an Excel (.xlsx) workbook to w.
func (*Document) XMP ¶ added in v0.3.0
func (d *Document) XMP() (XMPMetadata, error)
XMP returns the document's XMP metadata parsed from the /Catalog/Metadata stream. Returns a zero XMPMetadata (IsEmpty) when the document has no XMP packet. Parse errors in a malformed packet are returned; recognised properties parsed before the error are discarded.
type DocumentInfo ¶ added in v0.3.0
type DocumentInfo struct {
Title string
Author string
Subject string
Keywords string
Creator string
Producer string
CreationDate string
ModDate string
Custom map[string]string // arbitrary Info dict entries
}
DocumentInfo contains document information from the PDF Info dictionary. Fields not present in the source PDF are empty strings.
Mirrors Aspose.PDF for .NET's DocumentInfo (Document.Info). Note the cross-API naming: in Aspose.PDF for .NET, Document.Info is this Info dictionary while Document.Metadata is the XMP store — which here is (*Document).XMP, not this type.
type EditOperationsOrder ¶ added in v0.9.0
type EditOperationsOrder int
EditOperationsOrder decides how the two halves of a replacement are ordered. Mirrors Aspose.PDF for .NET's EditOperationsOrder.
const ( // EditOperationsDeleteFirst reports the removed text before the added // text. This is the zero value. EditOperationsDeleteFirst EditOperationsOrder = iota // EditOperationsInsertFirst reports the added text first. This only // reorders the delete/insert pair at their adjacent junction: a // replacement split across a page boundary (the deletion on one page, // the insertion on the next) is not reordered and comes out interleaved. EditOperationsInsertFirst )
type EmbeddedFile ¶ added in v0.4.0
type EmbeddedFile struct {
// contains filtered or unexported fields
}
EmbeddedFile is one attachment: a /Filespec dictionary with an embedded stream. Read its metadata and content, or set its description.
func (*EmbeddedFile) AFRelationship ¶ added in v0.10.0
func (f *EmbeddedFile) AFRelationship() AFRelationship
AFRelationship reports how the file relates to the document; a file with no /AFRelationship reports AFUnspecified.
func (*EmbeddedFile) CollectionItem ¶ added in v0.8.0
func (f *EmbeddedFile) CollectionItem() *CollectionItem
CollectionItem returns the attachment's portfolio field values.
func (*EmbeddedFile) Data ¶ added in v0.4.0
func (f *EmbeddedFile) Data() ([]byte, error)
Data returns the attachment's decoded content bytes.
func (*EmbeddedFile) Description ¶ added in v0.4.0
func (f *EmbeddedFile) Description() string
Description returns the /Filespec /Desc text, or "" if none.
func (*EmbeddedFile) MIMEType ¶ added in v0.4.0
func (f *EmbeddedFile) MIMEType() string
MIMEType returns the embedded stream's /Subtype as a MIME type (e.g. "application/pdf"), or "" if absent.
func (*EmbeddedFile) Name ¶ added in v0.4.0
func (f *EmbeddedFile) Name() string
Name returns the attachment's name (its name-tree key).
func (*EmbeddedFile) Save ¶ added in v0.4.0
func (f *EmbeddedFile) Save(path string) error
Save writes the attachment's content to a file.
func (*EmbeddedFile) SetAFRelationship ¶ added in v0.10.0
func (f *EmbeddedFile) SetAFRelationship(r AFRelationship)
SetAFRelationship records how the file relates to the document and lists it in the catalog's /AF array — both of which PDF/A-3 requires of every embedded file.
func (*EmbeddedFile) SetDescription ¶ added in v0.4.0
func (f *EmbeddedFile) SetDescription(s string)
SetDescription sets (or, for "", removes) the /Filespec /Desc text.
func (*EmbeddedFile) Size ¶ added in v0.4.0
func (f *EmbeddedFile) Size() int
Size returns the attachment's size in bytes (0 if no content).
type EmbeddedFiles ¶ added in v0.4.0
type EmbeddedFiles struct {
// contains filtered or unexported fields
}
EmbeddedFiles is the document's collection of attached (embedded) files — the /Catalog/Names/EmbeddedFiles name tree (ISO 32000-1 §7.11.4). Each entry is a /Filespec whose /EF points at an /EmbeddedFile stream, letting a PDF carry arbitrary companion files (source code, datasets, the original of a scan). Always non-nil; a document with no attachments yields an empty collection. Mirrors Aspose.PDF for .NET's Document.EmbeddedFiles.
This is the document-level counterpart to FileAttachmentAnnotation (a file pinned to a page); both share the same /EmbeddedFile + /Filespec machinery.
func (*EmbeddedFiles) Add ¶ added in v0.4.0
func (e *EmbeddedFiles) Add(path string) (*EmbeddedFile, error)
Add embeds the file at path under its base name, detecting the MIME type from its extension, and returns the new attachment. An existing attachment with the same name is replaced.
func (*EmbeddedFiles) AddFromStream ¶ added in v0.4.0
func (e *EmbeddedFiles) AddFromStream(name string, r io.Reader) (*EmbeddedFile, error)
AddFromStream embeds the bytes read from r under the given name (the MIME type is detected from the name's extension), and returns the new attachment.
func (*EmbeddedFiles) All ¶ added in v0.4.0
func (e *EmbeddedFiles) All() []*EmbeddedFile
All returns every attachment, in sorted-name order.
func (*EmbeddedFiles) Clear ¶ added in v0.4.0
func (e *EmbeddedFiles) Clear()
Clear removes every attachment.
func (*EmbeddedFiles) Count ¶ added in v0.4.0
func (e *EmbeddedFiles) Count() int
Count returns the number of embedded files.
func (*EmbeddedFiles) Get ¶ added in v0.4.0
func (e *EmbeddedFiles) Get(name string) *EmbeddedFile
Get returns the named attachment, or nil if absent.
func (*EmbeddedFiles) Has ¶ added in v0.4.0
func (e *EmbeddedFiles) Has(name string) bool
Has reports whether an attachment with the given name exists.
func (*EmbeddedFiles) Names ¶ added in v0.4.0
func (e *EmbeddedFiles) Names() []string
Names returns the attachment names (name-tree keys), lexicographically sorted.
func (*EmbeddedFiles) Remove ¶ added in v0.4.0
func (e *EmbeddedFiles) Remove(name string) bool
Remove deletes the named attachment, returning whether it existed. The orphaned objects are reclaimed by RemoveUnusedObjects.
type EncryptionAlgorithm ¶
type EncryptionAlgorithm int
EncryptionAlgorithm selects the cipher and security-handler revision used by (*Document).SetEncryption. The zero value is AES-128.
const ( // EncryptionAlgAES128 — AES-128, Standard Security Handler V=4 R=4, // /CFM /AESV2. ISO 32000-1 §7.6.3.2. The default (zero value). EncryptionAlgAES128 EncryptionAlgorithm = iota // EncryptionAlgRC4_128 — RC4-128, Standard Security Handler V=2 R=3. // Legacy compatibility only — AES-128 is preferred for new documents. EncryptionAlgRC4_128 // EncryptionAlgAES256 — AES-256, Standard Security Handler V=5 R=6, // /CFM /AESV3. ISO 32000-2 §7.6.4. Output PDF header is bumped to // %PDF-2.0; viewers older than Adobe Acrobat DC (~2015) may not // support PDF 2.0 documents. EncryptionAlgAES256 // EncryptionAlgRC4_40 — RC4-40, the original Standard Security Handler // V=1 R=2. Present for interoperability with old readers and archives // that only understand it; a 40-bit key is breakable by brute force in // minutes, so never choose it to protect anything. EncryptionAlgRC4_40 )
type EncryptionOptions ¶
type EncryptionOptions struct {
UserPassword string
OwnerPassword string
Permissions *Permissions
Algorithm EncryptionAlgorithm
// Recipients switches to the public-key security handler
// (/Filter /Adobe.PubSec): the document is encrypted for these
// certificates and opens with OpenWithCertificate instead of a
// password. The password fields are ignored when it is non-empty, and
// a recipient's own Permissions override the document-wide ones.
Recipients []Recipient
}
EncryptionOptions bundles every knob that controls how a document is encrypted when saved. It is the unified structured input for (*Document).SetEncryption; the shorter SetPassword / SetPermissions methods remain available for the common case of one-line updates.
Zero values:
UserPassword — no password (empty string is a valid "open without
password" user-password under R<=4; the PDF still
carries permissions).
OwnerPassword — defaults to UserPassword, matching Adobe behavior.
Permissions — nil means "grant all" (the historical default);
pass a non-nil pointer to restrict. Permissions{}
(value, not pointer) deliberately denies everything,
so the pointer distinguishes "omitted" from "deny".
Algorithm — EncryptionAlgAES128 (zero value).
Example:
doc.SetEncryption(asposepdf.EncryptionOptions{
UserPassword: "user",
OwnerPassword: "owner",
Permissions: &asposepdf.Permissions{AllowPrint: true, AllowCopy: true},
})
doc.Save("restricted.pdf")
type EpubSaveOptions ¶ added in v0.7.0
type EpubSaveOptions struct {
// Pages is a 1-based subset (in the given order); nil = all pages.
Pages []int
// Title sets dc:title; empty falls back to the Info title, then "Document".
Title string
// NoImages skips images (raster, vector patches and inline icons alike).
NoImages bool
}
EpubSaveOptions configures SaveEpub / WriteEpub. The zero value exports all pages with images, titled from the document's /Info.
type Field ¶
type Field interface {
PartialName() string
FullName() string
Value() string
SetValue(s string) error
IsReadOnly() bool
IsRequired() bool
PageIndex() int
Rect() Rectangle
// SetStyle applies visual styling (colours, border, font, alignment)
// and regenerates the widget appearance. Style reads it back.
SetStyle(s FieldStyle) error
Style() FieldStyle
// Flatten bakes this single field's appearance into its page content
// and removes the field, leaving other fields and the /AcroForm intact.
// See (*fieldBase).Flatten in flatten.go.
Flatten() error
}
Field is the common interface implemented by every concrete form field type (TextBoxField, CheckboxField, RadioButtonField, etc.).
type FieldStyle ¶ added in v0.3.0
type FieldStyle struct {
BorderColor *Color // /MK /BC — nil = no border colour set
BackgroundColor *Color // /MK /BG — nil = transparent/white default
TextColor *Color // /DA fill colour — nil = black
BorderWidth float64 // /BS /W in points — 0 = hairline default
BorderStyle BorderStyle // /BS /S — BorderSolid (default), Dashed, Beveled, Inset, Underline
DashPattern []float64 // /BS /D — used only when BorderStyle == BorderDashed
TextFont Font // /DA font — nil = Helvetica
TextSize float64 // /DA size in points — 0 = 12pt
TextAlign HAlign // /Q — HAlignLeft (default), HAlignCenter, HAlignRight
}
FieldStyle is the visual styling applied to a form field's widget(s). A zero value means "leave at the library default" for every property: nil colour pointers, zero BorderWidth, BorderSolid, nil DashPattern, nil TextFont (→ Helvetica), zero TextSize (→ 12pt), HAlignLeft.
Styling is persisted into the PDF the way ISO 32000-1 specifies, so it round-trips and is also honoured by viewers that regenerate appearances:
- BorderColor / BackgroundColor → /MK /BC, /MK /BG (§12.5.6.19)
- BorderWidth / BorderStyle / DashPattern → /BS /W, /S, /D (§12.5.4)
- TextFont / TextSize / TextColor → /DA default-appearance string (§12.7.3.3)
- TextAlign → /Q quadding (0 left, 1 centre, 2 right)
Because the library also pre-generates the widget /AP appearance stream from these same values, a styled field renders identically across Acrobat, Foxit, browser PDF viewers, MuPDF, and Poppler.
type FigureAlt ¶ added in v0.6.0
type FigureAlt struct {
// contains filtered or unexported fields
}
FigureAlt is a /Figure structure element that has no alternate text, paired with the image it brackets (when resolvable). Set the text with SetAltText.
func (*FigureAlt) Image ¶ added in v0.6.0
Image returns the figure's image and whether one was resolved. The image is decoded (Data holds PNG/JPEG bytes).
func (*FigureAlt) SetAltText ¶ added in v0.6.0
SetAltText sets the figure's /Alt (alternate text). Empty input is ignored.
type FileAttachmentAnnotation ¶
type FileAttachmentAnnotation struct {
// contains filtered or unexported fields
}
FileAttachmentAnnotation embeds a file in the document and shows an icon at the annotation's /Rect. Per ISO 32000-1 §12.5.6.15. No /AP is generated — viewers render the icon themselves based on /Name.
func NewFileAttachmentAnnotation ¶
func NewFileAttachmentAnnotation(page *Page, position Point) *FileAttachmentAnnotation
NewFileAttachmentAnnotation builds an unbound file-attachment annotation. Page must be non-nil. The /Rect is auto-computed as a 24×24 pt square anchored at position (Acrobat icon convention).
Call SetFile or SetFileFromStream to embed file data; without that, the annotation has no /FS entry and viewers render an empty icon.
func (*FileAttachmentAnnotation) AFRelationship ¶ added in v0.10.0
func (a *FileAttachmentAnnotation) AFRelationship() AFRelationship
AFRelationship reports how the attached file relates to the document; a file with no /AFRelationship (including an annotation with no attachment yet) reports AFUnspecified. Mirrors EmbeddedFile.AFRelationship.
func (*FileAttachmentAnnotation) AnnotationType ¶
func (a *FileAttachmentAnnotation) AnnotationType() AnnotationType
func (*FileAttachmentAnnotation) Color ¶
func (b *FileAttachmentAnnotation) Color() *Color
Color returns the /C array as an RGB Color. Returns nil if /C is absent.
func (*FileAttachmentAnnotation) Contents ¶
func (b *FileAttachmentAnnotation) Contents() string
Contents returns /Contents (the annotation body text).
func (*FileAttachmentAnnotation) FileBytes ¶
func (a *FileAttachmentAnnotation) FileBytes() []byte
FileBytes returns a defensive copy of the embedded file's raw bytes. Nil if no file.
func (*FileAttachmentAnnotation) FileDescription ¶
func (a *FileAttachmentAnnotation) FileDescription() string
FileDescription returns /Filespec/Desc. Empty if no description set.
func (*FileAttachmentAnnotation) FileMIMEType ¶
func (a *FileAttachmentAnnotation) FileMIMEType() string
FileMIMEType returns the /Subtype on /EmbeddedFile (e.g. "application/pdf"). Empty if no file or /Subtype missing.
func (*FileAttachmentAnnotation) FileName ¶
func (a *FileAttachmentAnnotation) FileName() string
FileName returns the displayed filename from /Filespec/F. Empty if no file.
func (*FileAttachmentAnnotation) FileSize ¶
func (a *FileAttachmentAnnotation) FileSize() int
FileSize returns the size of the embedded file in bytes. Zero if no file.
func (*FileAttachmentAnnotation) Flatten ¶ added in v0.3.0
func (b *FileAttachmentAnnotation) Flatten() error
Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.
An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.
Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.
func (*FileAttachmentAnnotation) HasFile ¶
func (a *FileAttachmentAnnotation) HasFile() bool
HasFile returns true if SetFile or SetFileFromStream has been called successfully and not subsequently cleared. Stub for now — full implementation in Task 3.
func (*FileAttachmentAnnotation) Icon ¶
func (a *FileAttachmentAnnotation) Icon() FileAttachmentIcon
Icon returns the /Name entry mapped to a FileAttachmentIcon. Returns FileAttachmentIconPaperclip (the spec default) if absent.
func (*FileAttachmentAnnotation) PageIndex ¶
func (b *FileAttachmentAnnotation) PageIndex() int
PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.
func (*FileAttachmentAnnotation) Rect ¶
func (b *FileAttachmentAnnotation) Rect() Rectangle
Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.
func (*FileAttachmentAnnotation) RegenerateAppearance ¶
func (a *FileAttachmentAnnotation) RegenerateAppearance()
RegenerateAppearance is a no-op for FileAttachmentAnnotation (no /AP — viewers render the icon themselves).
func (*FileAttachmentAnnotation) SetAFRelationship ¶ added in v0.10.0
func (a *FileAttachmentAnnotation) SetAFRelationship(r AFRelationship)
SetAFRelationship records how the attached file relates to the document and lists its file specification in the catalog's /AF array — both of which PDF/A-3 requires of every embedded file (ISO 19005-3 §6.8), and a page-pinned FileAttachmentAnnotation's filespec is otherwise invisible to that rule (pdfaCheckAssociatedFiles only walked the document-level EmbeddedFiles name tree before pdf-go-tdx5). A no-op if the annotation has no attached file yet — call it after SetFile/SetFileFromStream.
func (*FileAttachmentAnnotation) SetColor ¶
func (b *FileAttachmentAnnotation) SetColor(c *Color)
SetColor writes /C as an RGB array; nil removes the entry.
func (*FileAttachmentAnnotation) SetContents ¶
func (b *FileAttachmentAnnotation) SetContents(s string)
SetContents writes /Contents (the annotation body text); empty string removes the entry.
func (*FileAttachmentAnnotation) SetFile ¶
func (a *FileAttachmentAnnotation) SetFile(path string) error
SetFile embeds the file at path as the annotation's attachment. The file's MIME type is auto-detected from the extension via mime.TypeByExtension; falls back to "application/octet-stream" for unknown extensions. Returns error on file-open or read failures.
func (*FileAttachmentAnnotation) SetFileDescription ¶
func (a *FileAttachmentAnnotation) SetFileDescription(s string)
SetFileDescription writes /Filespec/Desc.
func (*FileAttachmentAnnotation) SetFileFromStream ¶
func (a *FileAttachmentAnnotation) SetFileFromStream(r io.Reader, name string) error
SetFileFromStream is the io.Reader variant of SetFile. The caller supplies the displayed filename (used for /F entry and for MIME detection from extension).
func (*FileAttachmentAnnotation) SetIcon ¶
func (a *FileAttachmentAnnotation) SetIcon(i FileAttachmentIcon)
SetIcon writes the /Name entry. Unknown is encoded as /Paperclip.
func (*FileAttachmentAnnotation) SetRect ¶
func (b *FileAttachmentAnnotation) SetRect(r Rectangle)
SetRect writes the annotation rectangle.
type FileAttachmentIcon ¶
type FileAttachmentIcon int
FileAttachmentIcon names per ISO 32000-1 §12.5.6.15 Table 178.
const ( FileAttachmentIconUnknown FileAttachmentIcon = iota FileAttachmentIconGraph FileAttachmentIconPaperclip // PDF default FileAttachmentIconPushPin FileAttachmentIconTag )
type FileDiffOutputGenerator ¶ added in v0.10.0
type FileDiffOutputGenerator interface {
SaveOutput(path string, ops []DiffOperation) error
SaveOutputPages(path string, pages [][]DiffOperation) error
WriteOutput(w io.Writer, ops []DiffOperation) error
WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
}
FileDiffOutputGenerator writes comparison output to a file or writer. Mirrors Aspose.PDF for .NET's IFileOutputGenerator; the io.Writer variants are this library's addition, following the SaveXxx/WriteXxx convention used throughout the package.
type FileSelectBoxField ¶ added in v0.4.0
type FileSelectBoxField struct{ TextBoxField }
FileSelectBoxField is a text field whose value is a file path (FileSelect flag), used to attach a local file on submit.
func (*FileSelectBoxField) Flatten ¶ added in v0.4.0
func (b *FileSelectBoxField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*FileSelectBoxField) FullName ¶ added in v0.4.0
func (b *FileSelectBoxField) FullName() string
func (*FileSelectBoxField) IsReadOnly ¶ added in v0.4.0
func (b *FileSelectBoxField) IsReadOnly() bool
func (*FileSelectBoxField) IsRequired ¶ added in v0.4.0
func (b *FileSelectBoxField) IsRequired() bool
func (*FileSelectBoxField) PartialName ¶ added in v0.4.0
func (b *FileSelectBoxField) PartialName() string
func (*FileSelectBoxField) SetStyle ¶ added in v0.4.0
func (b *FileSelectBoxField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*FileSelectBoxField) Style ¶ added in v0.4.0
func (b *FileSelectBoxField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
type FlattenTransparencyOptions ¶ added in v0.10.0
type FlattenTransparencyOptions struct {
DPI float64 // dots per inch for the replacement raster; 0 -> DefaultDPI
Pages []int // 1-based page numbers to consider; empty -> every page
}
FlattenTransparencyOptions configures FlattenTransparency.
type FloatSide ¶ added in v0.4.0
type FloatSide int
FloatSide selects which edge a floated box hugs while text wraps around it.
type FloatingBox ¶ added in v0.4.0
type FloatingBox struct {
// contains filtered or unexported fields
}
FloatingBox is a positioned content container (Tier 2 of the flow model): a box with an optional border, background and padding that lays its own content (paragraphs, headings, images, lists) inside its width. Place it absolutely on a page with (*Page).AddFloatingBox, or insert it into a flow with (*Flow).AddFloatingBox (where it takes its measured height). Mirrors the intent of Aspose.PDF for .NET's FloatingBox. Text flow-around and multi-column layout are not implemented (Tier 3).
func NewFloatingBox ¶ added in v0.4.0
func NewFloatingBox() *FloatingBox
NewFloatingBox creates an empty floating box.
func (*FloatingBox) AddHeading ¶ added in v0.4.0
func (b *FloatingBox) AddHeading(level int, text string, style TextStyle) *FloatingBox
AddHeading appends a heading (level 1–6) to the box.
func (*FloatingBox) AddImage ¶ added in v0.4.0
func (b *FloatingBox) AddImage(path string, width, height float64) *FloatingBox
AddImage appends an image (height ≤ 0 preserves aspect) to the box.
func (*FloatingBox) AddImageAlt ¶ added in v0.4.0
func (b *FloatingBox) AddImageAlt(path string, width, height float64, alt string) *FloatingBox
AddImageAlt appends an image with alternate text to the box.
func (*FloatingBox) AddList ¶ added in v0.4.0
func (b *FloatingBox) AddList(items []string, ordered bool, style TextStyle) *FloatingBox
AddList appends a bulleted/numbered list to the box.
func (*FloatingBox) AddParagraph ¶ added in v0.4.0
func (b *FloatingBox) AddParagraph(text string, style TextStyle) *FloatingBox
AddParagraph appends a paragraph to the box.
func (*FloatingBox) AddSpacer ¶ added in v0.4.0
func (b *FloatingBox) AddSpacer(height float64) *FloatingBox
AddSpacer appends vertical space to the box.
func (*FloatingBox) SetBackground ¶ added in v0.4.0
func (b *FloatingBox) SetBackground(c *Color) *FloatingBox
SetBackground sets the box fill colour (nil = none).
func (*FloatingBox) SetBorder ¶ added in v0.4.0
func (b *FloatingBox) SetBorder(border BorderInfo) *FloatingBox
SetBorder sets the box border.
func (*FloatingBox) SetPadding ¶ added in v0.4.0
func (b *FloatingBox) SetPadding(m MarginInfo) *FloatingBox
SetPadding sets the inner padding between the border and the content.
func (*FloatingBox) SetSpacing ¶ added in v0.4.0
func (b *FloatingBox) SetSpacing(gap float64) *FloatingBox
SetSpacing sets the vertical gap between the box's elements (default 6pt). Set it to 0 for a single-paragraph box so the content sits flush with the padding (and symmetric padding then centres it vertically).
type Flow ¶ added in v0.4.0
type Flow struct {
// contains filtered or unexported fields
}
Flow is a document generator that lays content out top-to-bottom and paginates automatically — the "flow" counterpart to the Rectangle-based drawing API. Add paragraphs, headings, images, tables, lists and spacers, then Render lays them into the document, appending pages as needed and (optionally) tagging each element for accessibility. Mirrors the intent of Aspose.PDF for .NET's generator / Paragraphs flow model. Obtain one with (*Document).NewFlow.
func (*Flow) AddColumnBreak ¶ added in v0.4.0
AddColumnBreak forces the following content to start in the next column (or, from the last column, on the next page). A no-op in a single-column flow that is already at the top of a page.
func (*Flow) AddFloatBox ¶ added in v0.4.0
func (f *Flow) AddFloatBox(box *FloatingBox, side FloatSide, width float64) *Flow
AddFloatBox appends a floated box pinned to the given side at width points; the paragraphs that follow wrap around it until the text passes its bottom. Designed for single-column flows (in a multi-column flow the box floats within the current column).
func (*Flow) AddFloatingBox ¶ added in v0.4.0
func (f *Flow) AddFloatingBox(box *FloatingBox) *Flow
AddFloatingBox appends a floating box, which takes its measured height in the flow (moving to a new page if it does not fit).
func (*Flow) AddHeading ¶ added in v0.4.0
AddHeading appends a heading of the given level (1–6). Empty style fields get level-appropriate bold defaults.
func (*Flow) AddImage ¶ added in v0.4.0
AddImage appends an image scaled to width×height points. If height <= 0 the image's aspect ratio is preserved.
func (*Flow) AddImageAlt ¶ added in v0.4.0
AddImageAlt is AddImage with alternate text (used when the flow is tagged).
func (*Flow) AddMarkdown ¶ added in v0.6.0
AddMarkdown appends a Markdown fragment to the flow: its blocks become flow elements (headings, paragraphs, lists, tables, images, …) rendered with the flow's Markdown options.
func (*Flow) AddParagraph ¶ added in v0.4.0
AddParagraph appends a paragraph of flowing text (wraps and splits across pages).
func (*Flow) AddTable ¶ added in v0.4.0
AddTable appends a table (paginated when taller than a page).
func (*Flow) Render ¶ added in v0.4.0
Render lays out the queued elements into the document and returns the number of pages the flow occupies.
func (*Flow) SetMarkdownOptions ¶ added in v0.6.0
func (f *Flow) SetMarkdownOptions(o MarkdownOptions) *Flow
SetMarkdownOptions sets the theme/options used by subsequent AddMarkdown calls on this flow (fonts, base size, image base path).
type FlowOptions ¶ added in v0.4.0
type FlowOptions struct {
Format PageFormat // zero → A4
MarginLeft, MarginRight, MarginTop, MarginBottom float64 // zero → 54pt
ParagraphSpacing float64 // gap after each block; zero → 6pt
Columns int // ≤1 → single column; >1 → multi-column flow
ColumnGap float64 // gap between columns; zero → 18pt
Tagged *TaggedContent // non-nil → auto-tag elements (Tagged PDF / PDF/UA)
}
FlowOptions configures a Flow. Zero values pick sensible defaults.
type Font ¶
type Font interface {
// BaseFont returns the PostScript name, e.g. "Helvetica" or "ArialMT".
BaseFont() string
// IsEmbedded reports whether font data is embedded in the PDF (true for TTF, false for standard 14).
IsEmbedded() bool
}
Font is implemented by standard 14 fonts and embedded TTF fonts. Use the package-level vars (FontHelvetica, ...) or LoadFont to obtain a Font.
var ( FontHelvetica Font = standardFont{/* contains filtered or unexported fields */} FontHelveticaBold Font = standardFont{/* contains filtered or unexported fields */} FontHelveticaOblique Font = standardFont{/* contains filtered or unexported fields */} FontHelveticaBoldOblique Font = standardFont{/* contains filtered or unexported fields */} FontTimesRoman Font = standardFont{/* contains filtered or unexported fields */} FontTimesBold Font = standardFont{/* contains filtered or unexported fields */} FontTimesItalic Font = standardFont{/* contains filtered or unexported fields */} FontTimesBoldItalic Font = standardFont{/* contains filtered or unexported fields */} FontCourier Font = standardFont{/* contains filtered or unexported fields */} FontCourierBold Font = standardFont{/* contains filtered or unexported fields */} FontCourierOblique Font = standardFont{/* contains filtered or unexported fields */} FontCourierBoldOblique Font = standardFont{/* contains filtered or unexported fields */} FontSymbol Font = standardFont{/* contains filtered or unexported fields */} FontZapfDingbats Font = standardFont{/* contains filtered or unexported fields */} )
Standard 14 PDF fonts. These Fonts need not be embedded — every PDF viewer is required to render them.
type FontMetrics ¶ added in v0.13.0
type FontMetrics struct {
// Ascent is the distance AddText subtracts from a rectangle's top
// edge (or AddTextAt's caller would subtract from a desired top) to
// place the baseline: rect.URY - Ascent. Always >= 0.
Ascent float64
// Descent is how far the font's descender reaches below the
// baseline, as a negative value (0 if not tracked for this font —
// see below). Mirrors the existing internal descent convention
// (text.go) of a non-positive distance.
Descent float64
}
FontMetrics holds the vertical metrics AddText/AddTextAt use for a font at a given size, in points. Mirrors Aspose.PDF for .NET's Font.MeasureString returning the same kind of layout metrics.
func GetFontMetrics ¶ added in v0.13.0
func GetFontMetrics(f Font, size float64) (FontMetrics, error)
GetFontMetrics returns the ascent/descent AddText/AddTextAt use for f at size, in points — the quantity a caller doing its own vertical positioning with AddTextAt would otherwise have to reverse-engineer from AddText's rect.URY - ascent*size placement formula. size 0 is treated as 12, matching AddText/AddTextAt/MeasureText.
Descent is only tracked for an embedded TrueType font (its real hhea descender); AddText's own placement never consults a descent value for the Standard-14/Type3 fallback (a fixed 0.8 em ascent, no separate descender), so none is fabricated here either — Descent comes back 0 for those.
type Form ¶
type Form struct {
// contains filtered or unexported fields
}
Form is the document's AcroForm view. Always non-nil — for documents without an /AcroForm dict, Form is empty (no fields, no flags). Field instances returned from Form are live handles over the underlying pdfDict; SetValue mutates in place and the next Save writes the new state.
func (*Form) AddBarcodeField ¶ added in v0.10.0
func (f *Form) AddBarcodeField(pageNum int, rect Rectangle, name string, symbology BarcodeSymbology, value string) (*BarcodeField, error)
AddBarcodeField adds a barcode field: value is the text encoded into the symbol (a URL or short text for QR/PDF417; printable ASCII for Code128), and symbology selects the encoding. Errors (without creating the field) if value cannot be encoded under symbology.
Example ¶
Draw a QR code in place of text: the widget's value is the encoded text, so it reads/writes exactly like any other field.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
form := doc.Form()
field, err := form.AddBarcodeField(1, pdf.Rectangle{LLX: 50, LLY: 650, URX: 150, URY: 750},
"sku", pdf.BarcodeQR, "https://example.com/sku/123")
if err != nil {
log.Fatal(err)
}
fmt.Println(field.Symbology() == pdf.BarcodeQR, field.Value())
}
Output: true https://example.com/sku/123
func (*Form) AddCheckbox ¶
AddCheckbox creates a checkbox widget on pageNum with the given rectangle and field name. Default state is unchecked (/V = /Off). The widget's /AP/N has two appearance states: "/Yes" (export name for checked) and "/Off". Callers can call SetChecked(true) on the returned handle to flip state and ensure /V and /AS are in sync.
Errors on duplicate name, invalid pageNum, or empty name.
func (*Form) AddComboBox ¶
func (f *Form) AddComboBox(pageNum int, rect Rectangle, name string, options []ChoiceOption) (*ComboBoxField, error)
AddComboBox creates a single-select dropdown choice field. The caller can pre-populate options or pass an empty slice and call AddOption later. Field is non-editable by default; SetEditable(true) flips bit 19.
func (*Form) AddDateField ¶ added in v0.4.0
AddDateField adds a date field with the given format mask (e.g. "mm/dd/yyyy"; empty defaults to "mm/dd/yyyy").
func (*Form) AddFileSelectField ¶ added in v0.4.0
func (f *Form) AddFileSelectField(pageNum int, rect Rectangle, name string) (*FileSelectBoxField, error)
AddFileSelectField adds a file-select text field.
func (*Form) AddListBox ¶
func (f *Form) AddListBox(pageNum int, rect Rectangle, name string, options []ChoiceOption) (*ListBoxField, error)
AddListBox creates a single-select list field. SetMultiSelect(true) on the returned handle enables multi-selection (bit 22).
func (*Form) AddNumberField ¶ added in v0.4.0
func (f *Form) AddNumberField(pageNum int, rect Rectangle, name string, opts NumberFormatOptions) (*NumberField, error)
AddNumberField adds a number field formatted per opts.
func (*Form) AddPasswordField ¶ added in v0.4.0
func (f *Form) AddPasswordField(pageNum int, rect Rectangle, name string) (*PasswordBoxField, error)
AddPasswordField adds a masked text field.
func (*Form) AddPushButton ¶
func (f *Form) AddPushButton(pageNum int, rect Rectangle, name string, caption string) (*ButtonField, error)
AddPushButton creates a non-toggling button. The caption is stored in /MK/CA and rendered by viewers as the button label. Push buttons have no value semantics — Value() returns "", SetValue returns an error.
func (*Form) AddRadioGroup ¶
func (f *Form) AddRadioGroup(name string, items []RadioItem) (*RadioButtonField, error)
AddRadioGroup creates a radio-button parent field plus one widget per item. Items may live on different pages. Export values must be unique within the group.
func (*Form) AddRichTextField ¶ added in v0.4.0
func (f *Form) AddRichTextField(pageNum int, rect Rectangle, name string) (*RichTextBoxField, error)
AddRichTextField adds a rich-text field.
func (*Form) AddTextField ¶
AddTextField creates a single-line text input on pageNum with the given rectangle and field name, auto-creating /AcroForm and the default Helvetica font resource if needed. Returns the live *TextBoxField handle. Errors on duplicate name, invalid pageNum, or empty name.
Example ¶
Create a text form field, fill it, and read the value back.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
form := doc.Form()
field, err := form.AddTextField(1, pdf.Rectangle{LLX: 50, LLY: 700, URX: 300, URY: 725}, "customer")
if err != nil {
log.Fatal(err)
}
_ = field.SetValue("ACME Corp")
fmt.Println(form.Field("customer").Value())
}
Output: ACME Corp
func (*Form) ExportFDF ¶ added in v0.4.0
ExportFDF serialises the form's field values as an FDF (Forms Data Format) document — a small PDF-syntax file (`%FDF-1.2` … `/FDF /Fields [ … ]`) that Acrobat and other readers import. Field names are written flat (the full name in each `/T`); push buttons are skipped. Mirrors Aspose.PDF for .NET's `Facades.Form.ExportFdf`.
func (*Form) ExportJSON ¶ added in v0.4.0
func (f *Form) ExportJSON(opts ...JSONExportOptions) ([]byte, error)
ExportJSON serialises the form's field values to a typed JSON document keyed by each field's full name: `{"name": {"type": "...", "value": ...}}`. The value's JSON kind follows the field type — text/radio/combobox → string, checkbox → bool, listbox → array of strings. Push buttons (which hold no value) are skipped. Keys are emitted in sorted order. Mirrors the intent of Aspose.PDF for .NET's `Document.Form.ExportToJson`.
func (*Form) ExportXFDF ¶ added in v0.4.0
ExportXFDF serialises the form's field values as an XFDF document. Field names are written flat (the full name in each `name` attribute); push buttons are skipped. Mirrors Aspose.PDF for .NET's `Facades.Form.ExportXfdf`.
func (*Form) Field ¶
Field returns the leaf field by FullName, or nil if no such field exists. Mirrors the C# `doc.Form["name"]` indexer pattern.
func (*Form) Fields ¶
Fields returns all leaf form fields as a flat slice. Field tree hierarchy is resolved internally; callers see only the leaves whose FullName carries the dotted path.
func (*Form) Flatten ¶ added in v0.3.0
Flatten bakes every form field's current appearance into its page's content stream and then removes all fields, their widgets, and the /AcroForm dict, producing a non-interactive document that renders the same. A field whose widget has no normal appearance is removed without drawing.
Mirrors Aspose.PDF for .NET's Form.Flatten. After Flatten the Form is empty; previously returned Field handles are dangling and must not be used.
func (*Form) ImportFDF ¶ added in v0.4.0
ImportFDF applies field values from an FDF document and returns the number of fields set. Names are matched by full name (FDF `/Kids` nesting is resolved to dotted names); unknown names and non-applying values are skipped. Mirrors Aspose.PDF for .NET's `Facades.Form.ImportFdf`.
func (*Form) ImportJSON ¶ added in v0.4.0
ImportJSON applies field values from a typed JSON document (the shape ExportJSON produces) and returns the number of fields actually set. Each key is matched against the form by full name; unknown names and values that don't apply to their target field are skipped (not an error). Values are interpreted by the matching field's concrete type, so a checkbox accepts a bool or a boolean string and a listbox accepts an array or a single string. Setting a value regenerates the widget appearance, so imported values render in any viewer. Mirrors the intent of Aspose.PDF for .NET's `Document.Form.ImportFromJson`.
func (*Form) ImportXFDF ¶ added in v0.4.0
ImportXFDF applies field values from an XFDF document and returns the number of fields set. Names are matched by full name (nested `<field>` elements are resolved to dotted names); unknown names and non-applying values are skipped. Mirrors Aspose.PDF for .NET's `Facades.Form.ImportXfdf`.
func (*Form) NeedAppearances ¶
NeedAppearances reports whether /AcroForm/NeedAppearances is true, which tells viewers to regenerate cached /AP appearance streams when displaying form fields.
func (*Form) ReadFDF ¶ added in v0.4.0
ReadFDF reads an FDF document from r and applies it via ImportFDF.
func (*Form) ReadJSON ¶ added in v0.4.0
ReadJSON reads a JSON document from r and applies it via ImportJSON.
func (*Form) ReadXFDF ¶ added in v0.4.0
ReadXFDF reads an XFDF document from r and applies it via ImportXFDF.
func (*Form) RemoveField ¶
RemoveField removes the named field (and all its widget annotations) from /AcroForm/Fields and from each affected page's /Annots. The underlying pdfObjects are deleted from the document's object map. Returns true if the field was found and removed; false otherwise.
For combined-pattern fields (TextField, Checkbox, ComboBox, ListBox, PushButton), the single dict is both the field and its widget: it is removed from /Fields and from the owning page's /Annots.
For radio groups, the parent dict is removed from /Fields, and each widget kid is removed from its respective page's /Annots.
After removal, any *Field handles previously returned for this field are dangling and must not be used.
func (*Form) SetNeedAppearances ¶
SetNeedAppearances toggles /AcroForm/NeedAppearances. When set, viewers regenerate the /AP appearance stream on display instead of trusting the pre-generated one (which Acrobat treats as a document modification). The library auto-builds /AP for every field on creation and on every value mutation, so the default (false) is correct for nearly all cases; callers only need this for niche workflows where viewer-side regeneration is required.
On a Document with no /AcroForm dict, calling this with true creates a new /AcroForm dict in the catalog so the flag is preserved on Save.
type FormFieldType ¶
type FormFieldType int
FormFieldType identifies the kind of form field. Returned by FieldType().
const ( FormFieldTypeUnknown FormFieldType = iota FormFieldTypeText FormFieldTypeCheckbox FormFieldTypeRadioButton FormFieldTypePushButton FormFieldTypeComboBox FormFieldTypeListBox FormFieldTypePassword FormFieldTypeFileSelect FormFieldTypeRichText FormFieldTypeNumber FormFieldTypeDate FormFieldTypeBarcode )
func FieldType ¶
func FieldType(f Field) FormFieldType
FieldType returns the concrete kind of f. Convenience helper for callers who want a switch on type without the type-assertion form.
type FreeTextAnnotation ¶
type FreeTextAnnotation struct {
// contains filtered or unexported fields
}
FreeTextAnnotation displays text directly on the page, rendered into /AP/N using an embedded font. Per ISO 32000-1 §12.5.6.6.
Supports /BS border, /BG background, /Q alignment via TextStyle, plus /IT intent (FreeText / FreeTextCallout / FreeTextTypewriter), /CL callout points, /BE border effect (cloudy), and /RD inner rect for callouts. Full feature set added incrementally across Tasks 9-17.
func NewFreeTextAnnotation ¶
func NewFreeTextAnnotation(page *Page, rect Rectangle, contents string, style TextStyle) *FreeTextAnnotation
NewFreeTextAnnotation builds an unbound FreeText annotation. Page must be non-nil. Contents is the text body. style configures font, size, color, alignment, and background — serialized to /DA, /Q, /BG.
func (*FreeTextAnnotation) AnnotationType ¶
func (a *FreeTextAnnotation) AnnotationType() AnnotationType
func (*FreeTextAnnotation) BorderEffect ¶
func (a *FreeTextAnnotation) BorderEffect() BorderEffect
BorderEffect returns the /BE/S entry as a BorderEffect. Returns BorderEffectNone if /BE is absent or unrecognized.
func (*FreeTextAnnotation) BorderEffectIntensity ¶
func (a *FreeTextAnnotation) BorderEffectIntensity() float64
BorderEffectIntensity returns the /BE/I entry. Returns 0 if absent. Default visual intensity for cloudy border is 1.0 — caller of SetBorderEffect typically also sets intensity via SetBorderEffectIntensity.
func (*FreeTextAnnotation) BorderStyle ¶
func (d *FreeTextAnnotation) BorderStyle() BorderStyle
BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.
func (*FreeTextAnnotation) BorderWidth ¶
func (d *FreeTextAnnotation) BorderWidth() float64
BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.
func (*FreeTextAnnotation) CalloutPoints ¶
func (a *FreeTextAnnotation) CalloutPoints() []Point
CalloutPoints returns the /CL knee + endpoint points (page space). Returns nil if /CL is absent or malformed. Format: 2-element slice (knee, endpoint) for /CL = [x1 y1 x2 y2]; 3-element slice (knee1, knee2, endpoint) for /CL = [x1 y1 x2 y2 x3 y3].
func (*FreeTextAnnotation) Contents ¶
func (a *FreeTextAnnotation) Contents() string
Contents returns the /Contents text body. Overrides annotationBase to ensure the value is always read from the dict.
func (*FreeTextAnnotation) DashPattern ¶
func (d *FreeTextAnnotation) DashPattern() []float64
DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.
func (*FreeTextAnnotation) EndLineEnding ¶
func (a *FreeTextAnnotation) EndLineEnding() LineEndingStyle
EndLineEnding returns the /LE entry as a LineEndingStyle. Returns LineEndingNone if absent or unrecognized.
func (*FreeTextAnnotation) InnerRect ¶
func (a *FreeTextAnnotation) InnerRect() Rectangle
InnerRect returns the inner text rectangle derived from /RD entry. If /RD is absent, returns the full annotation /Rect.
func (*FreeTextAnnotation) Intent ¶
func (a *FreeTextAnnotation) Intent() FreeTextIntent
Intent returns the /IT entry mapped to a FreeTextIntent. Returns FreeTextIntentFreeText (the spec default) if /IT is absent.
func (*FreeTextAnnotation) RegenerateAppearance ¶
func (a *FreeTextAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current state.
func (*FreeTextAnnotation) SetBorderEffect ¶
func (a *FreeTextAnnotation) SetBorderEffect(e BorderEffect)
SetBorderEffect writes /BE/S. The default (BorderEffectNone) removes the /BE entry to keep the dict minimal.
func (*FreeTextAnnotation) SetBorderEffectIntensity ¶
func (a *FreeTextAnnotation) SetBorderEffectIntensity(i float64)
SetBorderEffectIntensity writes /BE/I (cloud intensity, typically 0-2). Setting to 0 removes the /I entry; if /BE becomes empty, removes /BE entirely.
func (*FreeTextAnnotation) SetBorderStyle ¶
func (d *FreeTextAnnotation) SetBorderStyle(s BorderStyle)
SetBorderStyle writes /BS/S using the PDF spec name codes.
func (*FreeTextAnnotation) SetBorderWidth ¶
func (d *FreeTextAnnotation) SetBorderWidth(w float64)
SetBorderWidth writes /BS/W and clears any legacy /Border array.
func (*FreeTextAnnotation) SetCalloutPoints ¶
func (a *FreeTextAnnotation) SetCalloutPoints(pts []Point)
SetCalloutPoints writes /CL (must be 2 or 3 points; otherwise the call is a no-op). Auto-sets Intent to FreeTextIntentCallout. The caller passes points in page-space coordinates; round-trip preserves them as written.
func (*FreeTextAnnotation) SetColor ¶
func (d *FreeTextAnnotation) SetColor(c *Color)
SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.
func (*FreeTextAnnotation) SetContents ¶
func (a *FreeTextAnnotation) SetContents(s string)
SetContents writes /Contents and regenerates /AP/N (the rendered text content depends on Contents).
func (*FreeTextAnnotation) SetDashPattern ¶
func (d *FreeTextAnnotation) SetDashPattern(p []float64)
SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.
func (*FreeTextAnnotation) SetEndLineEnding ¶
func (a *FreeTextAnnotation) SetEndLineEnding(s LineEndingStyle)
SetEndLineEnding writes /LE for the callout endpoint shape.
func (*FreeTextAnnotation) SetInnerRect ¶
func (a *FreeTextAnnotation) SetInnerRect(inner Rectangle)
SetInnerRect writes /RD computed from the difference between the outer /Rect and the supplied inner rect (page-space). Negative distances are clamped to 0 to keep /RD spec-valid.
func (*FreeTextAnnotation) SetIntent ¶
func (a *FreeTextAnnotation) SetIntent(i FreeTextIntent)
SetIntent writes the /IT entry. The default (FreeTextIntentFreeText) removes the entry to keep the dict minimal.
func (*FreeTextAnnotation) SetRect ¶
func (d *FreeTextAnnotation) SetRect(r Rectangle)
SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).
func (*FreeTextAnnotation) SetTextStyle ¶
func (a *FreeTextAnnotation) SetTextStyle(s TextStyle)
SetTextStyle writes the style as /DA + /Q + /BG and regenerates /AP/N. VAlign is preserved in-memory (not stored in the PDF dict) and honored by the /AP/N renderer.
func (*FreeTextAnnotation) TextStyle ¶
func (a *FreeTextAnnotation) TextStyle() TextStyle
TextStyle returns the text style reconstructed from /DA + /Q + /BG. Only fields that round-trip through PDF dict entries are populated: Font, Size, Color, Background, HAlign. Other fields (LineSpacing, Underline, Strikethrough, Rotation, VAlign) are rendering hints honored when /AP/N is generated; they don't survive a round-trip through the dict.
type FreeTextIntent ¶
type FreeTextIntent int
FreeTextIntent per ISO 32000-1 §12.5.6.6 /IT entry. Defaults to FreeTextIntentFreeText (plain text in a rectangle).
const ( FreeTextIntentFreeText FreeTextIntent = iota // /FreeText FreeTextIntentCallout // /FreeTextCallout FreeTextIntentTypewriter // /FreeTextTypeWriter )
type GenericAnnotation ¶
type GenericAnnotation struct {
// contains filtered or unexported fields
}
GenericAnnotation is the catch-all surface for /Subtype values this release does not yet model (Stamp, FreeText, Ink, etc.). It exposes only the base Annotation accessors — callers can detect it via AnnotationType() == AnnotationTypeUnknown.
func (*GenericAnnotation) AnnotationType ¶
func (a *GenericAnnotation) AnnotationType() AnnotationType
func (*GenericAnnotation) Color ¶
func (b *GenericAnnotation) Color() *Color
Color returns the /C array as an RGB Color. Returns nil if /C is absent.
func (*GenericAnnotation) Contents ¶
func (b *GenericAnnotation) Contents() string
Contents returns /Contents (the annotation body text).
func (*GenericAnnotation) Flatten ¶ added in v0.3.0
func (b *GenericAnnotation) Flatten() error
Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.
An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.
Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.
func (*GenericAnnotation) PageIndex ¶
func (b *GenericAnnotation) PageIndex() int
PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.
func (*GenericAnnotation) Rect ¶
func (b *GenericAnnotation) Rect() Rectangle
Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.
func (*GenericAnnotation) SetColor ¶
func (b *GenericAnnotation) SetColor(c *Color)
SetColor writes /C as an RGB array; nil removes the entry.
func (*GenericAnnotation) SetContents ¶
func (b *GenericAnnotation) SetContents(s string)
SetContents writes /Contents (the annotation body text); empty string removes the entry.
func (*GenericAnnotation) SetRect ¶
func (b *GenericAnnotation) SetRect(r Rectangle)
SetRect writes the annotation rectangle.
type GifDevice ¶ added in v0.3.0
type GifDevice struct {
// contains filtered or unexported fields
}
GifDevice renders a page to GIF. Mirrors Aspose.PDF for .NET's GifDevice.
func NewGifDevice ¶ added in v0.3.0
func NewGifDevice(res Resolution) *GifDevice
NewGifDevice returns a GifDevice for the given resolution.
type GoToAction ¶
type GoToAction struct {
// contains filtered or unexported fields
}
GoToAction navigates to a page within the same document. PageNum is 1-based; Top is the y-coordinate of the destination view in default user space.
func NewGoToAction ¶
func NewGoToAction(pageNum int, top float64) *GoToAction
NewGoToAction builds a /GoTo action targeting the given 1-based page and a y-coordinate (top of view).
func (*GoToAction) ActionType ¶
func (a *GoToAction) ActionType() ActionType
func (*GoToAction) PageNum ¶
func (a *GoToAction) PageNum() int
PageNum returns the 1-based destination page number.
func (*GoToAction) SetPageNum ¶
func (a *GoToAction) SetPageNum(n int)
SetPageNum updates the destination page number (1-based).
func (*GoToAction) SetTop ¶
func (a *GoToAction) SetTop(t float64)
SetTop updates the y-coordinate of the destination view.
func (*GoToAction) Top ¶
func (a *GoToAction) Top() float64
Top returns the y-coordinate of the destination view.
type GoToURIAction ¶
type GoToURIAction struct {
// contains filtered or unexported fields
}
GoToURIAction opens a URI in the user's default handler (typically a web browser).
func NewGoToURIAction ¶
func NewGoToURIAction(uri string) *GoToURIAction
NewGoToURIAction builds a /URI action. Empty URI is permitted but usually not what callers want.
func (*GoToURIAction) ActionType ¶
func (a *GoToURIAction) ActionType() ActionType
func (*GoToURIAction) SetURI ¶
func (a *GoToURIAction) SetURI(uri string)
SetURI updates the destination URI.
type Gradient ¶ added in v0.3.0
type Gradient interface {
// contains filtered or unexported methods
}
Gradient is a fill that varies colour across a shape: either a LinearGradient or a RadialGradient. Assign one to ShapeStyle.FillGradient to fill a DrawRectangle / DrawRoundedRectangle / DrawCircle / DrawEllipse / DrawPolygon / DrawPath shape with it.
Coordinates are PDF user space (points; origin at the page bottom-left, Y up) — the same space as the shape being filled. Implemented as PDF axial (Type 2) and radial (Type 3) shading patterns. Limitations mirror the SVG renderer: the spread method is pad (the end colours extend past the gradient vector) and per-stop alpha is not rendered (shadings are opaque DeviceRGB).
type GradientStop ¶ added in v0.3.0
GradientStop is one colour stop in a gradient, positioned at Offset (0 at the gradient's start, 1 at its end). Stops should be supplied in ascending Offset order.
type GraphicalPdfComparer ¶ added in v0.10.0
type GraphicalPdfComparer struct {
// Threshold is the per-pixel colour-distance percentage (0-100) below
// which a difference is ignored — a way to ignore small changes (JPEG
// recompression noise, anti-aliasing). The zero value compares exactly.
// Mirrors GraphicalPdfComparer.Threshold.
Threshold float64
// Color marks differing pixels in the default DifferenceToImage call and
// in CompareDocumentsToPdf/ComparePagesToImage output. The zero value is
// red. Mirrors GraphicalPdfComparer.Color.
Color Color
// Resolution is the DPI both pages are rasterized at before comparing.
// The zero value is 150 DPI. Mirrors GraphicalPdfComparer.Resolution.
Resolution Resolution
}
GraphicalPdfComparer compares PDF pages/documents pixel by pixel. Mirrors Aspose.PDF for .NET's GraphicalPdfComparer. Construct with NewGraphicalPdfComparer, or use the zero value (equivalent defaults).
func NewGraphicalPdfComparer ¶ added in v0.10.0
func NewGraphicalPdfComparer() *GraphicalPdfComparer
NewGraphicalPdfComparer returns a comparer with Aspose's defaults: exact comparison, red highlight, 150 DPI.
func (*GraphicalPdfComparer) CompareDocumentsToPdf ¶ added in v0.10.0
func (c *GraphicalPdfComparer) CompareDocumentsToPdf(doc1, doc2 *Document, outputPath string) error
CompareDocumentsToPdf compares every page pair by index (mirroring CompareDocumentsPageByPage's pairing; the longer document's tail pages are compared against a blank white page of the same size, so a page added or removed reports whatever fraction of it isn't blank/white as different, rather than erroring — a page that is itself mostly white reports a correspondingly small ratio despite being a genuine page-count change) and writes a new PDF with one page per pair: the difference image full-page, captioned with the changed-pixel ratio. Mirrors GraphicalPdfComparer.CompareDocumentsToPdf.
func (*GraphicalPdfComparer) ComparePagesToImage ¶ added in v0.10.0
func (c *GraphicalPdfComparer) ComparePagesToImage(page1, page2 *Page, path string) error
ComparePagesToImage renders the two pages' difference (DifferenceToImage with this comparer's Color as foreground, white as background) and saves it as a PNG. Mirrors GraphicalPdfComparer.ComparePagesToImage.
func (*GraphicalPdfComparer) GetDifference ¶ added in v0.10.0
func (c *GraphicalPdfComparer) GetDifference(page1, page2 *Page) (*ImagesDifference, error)
GetDifference rasterizes both pages at Resolution and compares them pixel by pixel. Mirrors GraphicalPdfComparer.GetDifference.
func (*GraphicalPdfComparer) WriteDocumentsToPdf ¶ added in v0.10.0
func (c *GraphicalPdfComparer) WriteDocumentsToPdf(doc1, doc2 *Document, w io.Writer) error
WriteDocumentsToPdf is the io.Writer variant of CompareDocumentsToPdf.
func (*GraphicalPdfComparer) WritePagesToImage ¶ added in v0.10.0
func (c *GraphicalPdfComparer) WritePagesToImage(page1, page2 *Page, w io.Writer) error
WritePagesToImage is the io.Writer variant of ComparePagesToImage (PNG).
type HTMLDiffOutputGenerator ¶ added in v0.10.0
type HTMLDiffOutputGenerator struct {
// contains filtered or unexported fields
}
HTMLDiffOutputGenerator renders comparison differences as an HTML fragment — colored spans for insertions/deletions, meant to be embedded into the caller's own page or email, not a standalone document. Mirrors Aspose.PDF for .NET's HtmlDiffOutputGenerator.
func NewHTMLDiffOutputGenerator ¶ added in v0.10.0
func NewHTMLDiffOutputGenerator(opts ...DiffOutputStyle) *HTMLDiffOutputGenerator
NewHTMLDiffOutputGenerator creates a generator with the given style (last one wins); the zero value uses DiffOutputStyle's defaults.
func (*HTMLDiffOutputGenerator) GenerateOutput ¶ added in v0.10.0
func (g *HTMLDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)
GenerateOutput renders ops as one HTML fragment, operations joined by a single space (matching AssembleSourceText/AssembleDestinationText). Equal text is emitted plain unless DiffOutputStyle.EqualColor/EqualBackground is set.
func (*HTMLDiffOutputGenerator) GenerateOutputPages ¶ added in v0.10.0
func (g *HTMLDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)
GenerateOutputPages renders one <div class="cmp-page"> section per page, each headed by "Page N".
func (*HTMLDiffOutputGenerator) SaveOutput ¶ added in v0.10.0
func (g *HTMLDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error
SaveOutput writes GenerateOutput's fragment to path.
func (*HTMLDiffOutputGenerator) SaveOutputPages ¶ added in v0.10.0
func (g *HTMLDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error
SaveOutputPages writes GenerateOutputPages's fragment to path.
func (*HTMLDiffOutputGenerator) WriteOutput ¶ added in v0.10.0
func (g *HTMLDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error
WriteOutput writes GenerateOutput's fragment to w.
func (*HTMLDiffOutputGenerator) WriteOutputPages ¶ added in v0.10.0
func (g *HTMLDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
WriteOutputPages writes GenerateOutputPages's fragment to w.
type HTMLMode ¶ added in v0.5.0
type HTMLMode int
HTMLMode selects how SaveHTML / WriteHTML represents page text.
const ( // HTMLModeFaithful (default) renders each page fully as a raster image // under a transparent selectable text layer — pixel-identical to // RenderPNG by construction. HTMLModeFaithful HTMLMode = iota // HTMLModeText renders the page background without glyphs and draws the // text as visible HTML spans (real colour/size/style, width-fitted to // the PDF layout) — crisp at any zoom, accessible, smaller output. HTMLModeText // HTMLModeNative drops the raster background entirely: page graphics // become one inline SVG layer per page (true-curve paths, native // strokes, clips, images with JPEG passthrough, blend modes), with // per-element raster patches only for content SVG cannot express // (shadings, patterns, soft masks, transparency groups). Text is the // same visible span layer as HTMLModeText (WOFF fonts included). HTMLModeNative // HTMLModeFlow produces reflowable HTML instead of positioned page // replicas: paragraphs and columns (from the Paragraphs() extractor) // become real <p>/<h1>-<h3> elements in reading order in a responsive // centered column, images flow between them. Position-based features // (link overlays, interactive forms) and DPI do not apply; tables and // vector graphics are not reconstructed — their text flows as // paragraphs. Mirrors Aspose.PDF for .NET's FixedLayout=false. HTMLModeFlow )
type HTMLSaveOptions ¶ added in v0.5.0
type HTMLSaveOptions struct {
// DPI is the raster resolution of the page backgrounds (0 → 144, crisp on
// high-density screens since pages display at their natural point size).
DPI float64
// Title overrides the HTML <title> (default: the document's Info title,
// else "Document").
Title string
// Mode selects faithful (default) or visible-text page representation.
Mode HTMLMode
// Pages selects which pages to export as 1-based numbers, in the given
// order (repeats allowed). Empty exports every page. Page anchors keep
// their source numbers, so cross-page links stay stable in a subset.
Pages []int
// NoFontEmbedding disables the WOFF @font-face embedding of the
// document's fonts in HTMLModeText (spans then always use the metric
// substitutes + width fitting). No effect in faithful mode.
NoFontEmbedding bool
// InteractiveForms converts AcroForm fields into real, fillable HTML
// controls (inputs, textareas, selects) positioned over the page, and
// removes their widget appearances from the background render. Text,
// checkbox, radio, combo and list fields convert; push buttons and
// signatures keep their static look. The form can be filled in and
// printed in a browser without JavaScript; writing values back into
// the PDF is out of scope. HTMLModeText / HTMLModeNative only.
InteractiveForms bool
// ResourceWriter externalizes the heavy binary parts — page background
// rasters, WOFF fonts, images and raster patches: it is called with a
// unique file name and the content and returns the URL to write into
// the HTML. nil keeps everything inlined as base64 data: URLs (the
// default single self-contained file). Mirrors the intent of Aspose
// .PDF for .NET's CustomResourceSavingStrategy / PartsEmbeddingMode.
ResourceWriter func(name string, data []byte) (url string, err error)
// ResourceDir (SaveHTML only) is the convenience form of
// ResourceWriter: resources are written as files into this directory
// (created on demand, relative to the output HTML) and referenced by
// relative URL. Ignored when ResourceWriter is set. Mirrors Aspose's
// SpecialFolderForAllImages.
ResourceDir string
// SplitPages (SaveHTML only) writes one HTML document per exported
// page as <stem>_p<N>.html instead of one big file; in-document links
// point across the files. Mirrors Aspose's SplitIntoPages.
SplitPages bool
// (bookmark) tree, linking to the page anchors — collapsible with pure
// HTML, no JavaScript. No-op for documents without outlines and in
// HTMLModeFlow (which has no page anchors).
OutlineNav bool
// contains filtered or unexported fields
}
HTMLSaveOptions configures SaveHTML / WriteHTML. The zero value exports all pages in faithful mode at 144 DPI with the document title taken from the Info dictionary.
type HiddenDataSanitizationOptions ¶ added in v0.11.0
type HiddenDataSanitizationOptions struct {
// RemoveMetadata clears the /Info dictionary and the XMP packet.
RemoveMetadata bool
// RemoveAttachments drops every embedded file, document-level and
// page-pinned.
RemoveAttachments bool
// RemoveJavaScriptsAndActions strips document-level and per-annotation
// JavaScript and Launch actions.
RemoveJavaScriptsAndActions bool
// RemoveAnnotations applies any pending redactions (ApplyRedactions)
// and then removes every remaining annotation from every page, except
// form-field widgets: those are FlattenForms's job (deleting a widget
// without also removing its field from /AcroForm/Fields would leave a
// dangling reference). Set FlattenForms too to also clear forms.
RemoveAnnotations bool
// RemoveSearchIndexAndPrivateInfo removes /PieceInfo private
// application data (a known privacy leak: Illustrator/InDesign's "PDF
// compatibility" mode keeps the original editable artwork here even
// in an otherwise-flattened PDF) from the catalog and every page, and
// drops any embedded file named like an Acrobat Catalog full-text
// search index (a *.pdx attachment). Best-effort: Aspose does not
// document this option's exact scope, so this is a defensible
// narrower reading, not a byte-for-byte mirror.
RemoveSearchIndexAndPrivateInfo bool
// FlattenForms bakes every form field's current appearance into page
// content and removes the AcroForm (Document.Flatten).
FlattenForms bool
// FlattenLayers removes the optional-content (layer) configuration
// and every layer-scoped resource reference, so content that used to
// be conditionally hidden under a layer is unconditionally visible
// and the layer dictionaries (including their /Name) become
// unreachable. Limitation: only checks each page's own
// /Resources/Properties, not a nested Form XObject's.
FlattenLayers bool
// ConvertPagesToImages replaces every page's content with a single
// rasterized image at ImageDPI, discarding whatever vector/text
// content survived every option above as a last line of defense. It
// does not touch annotations (a sticky note's /Contents, an
// attachment's bytes, an annotation's own /AA JavaScript) — combine
// with RemoveAnnotations/RemoveAttachments/RemoveJavaScriptsAndActions
// if those must go too. Runs after every other option. When set,
// ImageCompressionOptions is ignored.
ConvertPagesToImages bool
// ImageDPI is the resolution used by ConvertPagesToImages; 0 -> 150.
ImageDPI float64
// ImageCompressionOptions, used only when ConvertPagesToImages is
// false, recompresses the document's existing images in place.
ImageCompressionOptions *ImageCompressionOptions
}
HiddenDataSanitizationOptions configures (*Document).Sanitize. Mirrors Aspose.PDF for .NET's Aspose.Pdf.Security.HiddenDataSanitization. HiddenDataSanitizationOptions; this library composes it as a Document method (like Optimize/ConvertToPDFA/FlattenTransparency) rather than a separate executor object, since every operation the .NET HiddenDataSanitizer class performs already exists here as a primitive this type composes.
func AllHiddenDataSanitizationOptions ¶ added in v0.11.0
func AllHiddenDataSanitizationOptions() HiddenDataSanitizationOptions
AllHiddenDataSanitizationOptions returns every removal and flattening option enabled, leaving page rasterization and image compression off — either can noticeably change how the document looks, so the caller opts into ConvertPagesToImages/ImageDPI or ImageCompressionOptions separately. Mirrors Aspose.PDF for .NET's static HiddenDataSanitizationOptions.All().
type HiddenDataSanitizationResult ¶ added in v0.11.0
type HiddenDataSanitizationResult struct {
MetadataRemoved bool
AttachmentsRemoved int
ActionsRemoved bool
PrivateInfoRemoved int
FormsFlattened bool
LayersRemoved int
RedactionsApplied bool
AnnotationsRemoved int
PagesRasterized int
ImagesOptimized int
}
HiddenDataSanitizationResult reports what Sanitize changed.
func SanitizeAllToImages ¶ added in v0.11.0
func SanitizeAllToImages(doc *Document, dpi float64) (HiddenDataSanitizationResult, error)
SanitizeAllToImages rasterizes every page of doc at dpi (0 -> 150) after removing every other kind of hidden data first. Mirrors Aspose.PDF for .NET's static HiddenDataSanitizer.SanitizeAllToImages.
type HighlightAnnotation ¶
type HighlightAnnotation struct {
// contains filtered or unexported fields
}
HighlightAnnotation marks a region with a semi-transparent highlight colour, washed over the text the quads cover.
func NewHighlightAnnotation ¶
func NewHighlightAnnotation(page *Page, rect Rectangle) *HighlightAnnotation
NewHighlightAnnotation builds an unbound highlight annotation. Page must be non-nil.
func (*HighlightAnnotation) AnnotationType ¶
func (a *HighlightAnnotation) AnnotationType() AnnotationType
func (*HighlightAnnotation) QuadPoints ¶
func (m *HighlightAnnotation) QuadPoints() []QuadPoint
QuadPoints returns the array of quads describing the marked region. Returns nil if /QuadPoints is absent or its array length is not a multiple of 8 (malformed).
func (*HighlightAnnotation) RegenerateAppearance ¶ added in v0.9.0
func (a *HighlightAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*HighlightAnnotation) SetColor ¶
func (m *HighlightAnnotation) SetColor(c *Color)
SetColor writes /C and redraws the appearance in the new colour.
func (*HighlightAnnotation) SetQuadPoints ¶
func (m *HighlightAnnotation) SetQuadPoints(qp []QuadPoint)
SetQuadPoints writes /QuadPoints. nil or empty slice removes the entry.
type Image ¶
type Image struct {
Data []byte // encoded image bytes (PNG or JPEG)
Format ImageFormat // output format
Width int // pixel width
Height int // pixel height
BPC int // bits per component (original)
ColorSpace ImageColorSpace // original PDF color space
X, Y float64 // position on page (lower-left, in points)
PageWidth float64 // display width on page (in points)
PageHeight float64 // display height on page (in points)
Inline bool // true if from inline image (BI/ID/EI)
}
Image holds an extracted image with its encoded data and metadata.
type ImageColorSpace ¶
type ImageColorSpace int
ImageColorSpace describes the original color space of the image in the PDF.
const ( ColorSpaceDeviceRGB ImageColorSpace = iota ColorSpaceDeviceGray ColorSpaceDeviceCMYK ColorSpaceIndexed ColorSpaceICCBased )
type ImageCompressionOptions ¶ added in v0.11.0
type ImageCompressionOptions struct {
// ResizeImages downscales images above MaxResolution DPI. Leaving
// MaxResolution at its zero value together with ResizeImages true is
// rejected by Sanitize (it would otherwise silently downscale nothing).
ResizeImages bool
// MaxResolution is the DPI ceiling used when ResizeImages is set.
MaxResolution float64
// CompressImages converts opaque PNG images to JPEG.
CompressImages bool
}
ImageCompressionOptions configures the lossy recompression Sanitize applies to a document's existing images when ConvertPagesToImages is not set. Mirrors Aspose.PDF for .NET's ImageCompressionOptions (consumed by HiddenDataSanitizationOptions.ImageCompressionOptions); implemented here as a thin mapping onto the existing (*Document).OptimizeImages.
type ImageFormat ¶
type ImageFormat int
ImageFormat describes the output format of an extracted image.
const ( ImageFormatPNG ImageFormat = iota ImageFormatJPEG )
type ImageInfo ¶
type ImageInfo struct {
Width int // pixel width
Height int // pixel height
BPC int // bits per component (original)
ColorSpace ImageColorSpace // original PDF color space
Format ImageFormat // output format (PNG or JPEG)
X, Y float64 // position on page (lower-left, in points)
PageWidth float64 // display width on page (in points)
PageHeight float64 // display height on page (in points)
Inline bool // true if from inline image (BI/ID/EI)
Name string // XObject name (e.g. "/Im0"); empty for inline
// contains filtered or unexported fields
}
ImageInfo holds metadata about an image found on a page without decoding pixel data. Call Extract() to perform the actual decoding and get the full Image.
func (*ImageInfo) Remove ¶
Remove removes the image from the page. Deletes the XObject reference from page resources and the drawing operators from the content stream. The underlying XObject remains in the document's object store (safe for shared references). Images inside Form XObjects are not supported; only page-level images can be removed.
type ImageStamp ¶ added in v0.4.0
type ImageStamp struct {
// contains filtered or unexported fields
}
ImageStamp overlays a raster image (PNG or JPEG), stretched to fill Rect. Mirrors Aspose.Pdf.ImageStamp. Construct with NewImageStamp / NewImageStampFromStream.
func NewImageStamp ¶ added in v0.4.0
func NewImageStamp(path string) (*ImageStamp, error)
NewImageStamp creates an image stamp from a PNG/JPEG file. Mirrors Aspose's ImageStamp(string).
func NewImageStampFromStream ¶ added in v0.4.0
func NewImageStampFromStream(r io.Reader) (*ImageStamp, error)
NewImageStampFromStream creates an image stamp from a PNG/JPEG reader. Mirrors Aspose's ImageStamp(Stream).
type ImageToDocumentOptions ¶
type ImageToDocumentOptions struct {
PageWidth float64 // explicit page size in points; 0 = auto from image
PageHeight float64
MarginLeft float64
MarginRight float64
MarginTop float64
MarginBottom float64
}
ImageToDocumentOptions controls page sizing for ImageToDocument.
type ImagesDifference ¶ added in v0.10.0
type ImagesDifference struct {
// contains filtered or unexported fields
}
ImagesDifference is the result of comparing two rendered pages pixel by pixel. Mirrors Aspose.PDF for .NET's ImagesDifference; DifferentPixels / TotalPixels / Ratio are this library's addition (the design goal the backlog names it by: "difference image plus the changed-pixel ratio") — Aspose instead exposes the raw LockBits-style difference array plus its Height/Stride, a .NET Bitmap implementation detail with no Go equivalent worth mirroring literally when image.Image already carries that shape.
func (*ImagesDifference) DestinationImage ¶ added in v0.10.0
func (d *ImagesDifference) DestinationImage() image.Image
DestinationImage returns the second page's rendered image (padded to the compared canvas size, see newImagesDifference). Mirrors ImagesDifference.GetDestinationImage.
func (*ImagesDifference) DifferenceToImage ¶ added in v0.10.0
func (d *ImagesDifference) DifferenceToImage(foreground, background Color) image.Image
DifferenceToImage renders a bitmap the size of the compared canvas: foreground where pixels differ, background where they agree. Mirrors ImagesDifference.DifferenceToImage.
func (*ImagesDifference) DifferentPixels ¶ added in v0.10.0
func (d *ImagesDifference) DifferentPixels() int
DifferentPixels returns the number of pixels whose colour distance exceeded Threshold.
func (*ImagesDifference) HasDifferences ¶ added in v0.10.0
func (d *ImagesDifference) HasDifferences() bool
HasDifferences reports whether any pixel differs.
func (*ImagesDifference) Ratio ¶ added in v0.10.0
func (d *ImagesDifference) Ratio() float64
Ratio returns DifferentPixels/TotalPixels in [0,1]; 0 for an empty canvas.
func (*ImagesDifference) SourceImage ¶ added in v0.10.0
func (d *ImagesDifference) SourceImage() image.Image
SourceImage returns the first page's rendered image (padded to the compared canvas size, see newImagesDifference). Mirrors ImagesDifference.SourceImage.
func (*ImagesDifference) TotalPixels ¶ added in v0.10.0
func (d *ImagesDifference) TotalPixels() int
TotalPixels returns the pixel count of the compared (union) canvas.
type InkAnnotation ¶
type InkAnnotation struct {
// contains filtered or unexported fields
}
InkAnnotation draws a series of free-form strokes — typically used to represent handwritten ink. Each stroke is a sequence of points rendered as a polyline; in Task 16 strokes with 3+ points get Catmull-Rom smoothing for visual quality.
func NewInkAnnotation ¶
func NewInkAnnotation(page *Page, strokes [][]Point) *InkAnnotation
NewInkAnnotation builds an unbound ink annotation. Page must be non-nil. Each inner slice is one continuous stroke. The /Rect entry is auto-computed as the bounding box of all stroke points plus padding equal to BorderWidth.
func (*InkAnnotation) AddStroke ¶
func (a *InkAnnotation) AddStroke(stroke []Point)
AddStroke appends a single stroke to the annotation. Convenience for incremental construction.
func (*InkAnnotation) AnnotationType ¶
func (a *InkAnnotation) AnnotationType() AnnotationType
func (*InkAnnotation) BorderStyle ¶
func (d *InkAnnotation) BorderStyle() BorderStyle
BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.
func (*InkAnnotation) BorderWidth ¶
func (d *InkAnnotation) BorderWidth() float64
BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.
func (*InkAnnotation) DashPattern ¶
func (d *InkAnnotation) DashPattern() []float64
DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.
func (*InkAnnotation) RegenerateAppearance ¶
func (a *InkAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*InkAnnotation) SetBorderStyle ¶
func (d *InkAnnotation) SetBorderStyle(s BorderStyle)
SetBorderStyle writes /BS/S using the PDF spec name codes.
func (*InkAnnotation) SetBorderWidth ¶
func (a *InkAnnotation) SetBorderWidth(w float64)
SetBorderWidth overrides drawingAnnotationBase.SetBorderWidth so /Rect (whose padding scales with BorderWidth) is recomputed before /AP/N regenerates — single-pass /BBox sync.
func (*InkAnnotation) SetColor ¶
func (d *InkAnnotation) SetColor(c *Color)
SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.
func (*InkAnnotation) SetDashPattern ¶
func (d *InkAnnotation) SetDashPattern(p []float64)
SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.
func (*InkAnnotation) SetRect ¶
func (d *InkAnnotation) SetRect(r Rectangle)
SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).
func (*InkAnnotation) SetStrokes ¶
func (a *InkAnnotation) SetStrokes(strokes [][]Point)
SetStrokes writes /InkList. The slices are deep-copied; the caller may safely mutate after this returns.
func (*InkAnnotation) Strokes ¶
func (a *InkAnnotation) Strokes() [][]Point
Strokes returns a deep copy of /InkList. Mutating the result does not affect the annotation.
type Invoice ¶ added in v0.10.0
type Invoice struct {
XML []byte // the embedded invoice, byte for byte
FileName string // the attachment name
Profile InvoiceProfile // from the XMP ConformanceLevel, else from the XML
Standard string // "Factur-X 1.0 / ZUGFeRD 2.1+", "ZUGFeRD 2.0" or "ZUGFeRD 1.0"
Version string // the XMP Version property; "" when absent
}
Invoice is an e-invoice found in a document.
type InvoiceOptions ¶ added in v0.10.0
type InvoiceOptions struct {
FileName string // default: "factur-x.xml", or "xrechnung.xml" for XRechnung
Profile InvoiceProfile // default: read from the XML's guideline ID
Format PDFAFormat // PDFA3B or PDFA3A; the zero value (PDFA1B, never valid here) means PDFA3B
}
InvoiceOptions configures AttachInvoice. The zero value detects the profile from the XML, names the file as the standard prescribes, and produces PDF/A-3b.
type InvoiceProfile ¶ added in v0.10.0
type InvoiceProfile int
InvoiceProfile is the Factur-X / ZUGFeRD conformance level of an invoice.
const ( InvoiceProfileUnknown InvoiceProfile = iota InvoiceProfileMinimum // MINIMUM InvoiceProfileBasicWL // BASIC WL (without lines) InvoiceProfileBasic // BASIC InvoiceProfileEN16931 // EN 16931 (ZUGFeRD 1.0 COMFORT) InvoiceProfileExtended // EXTENDED InvoiceProfileXRechnung // XRECHNUNG )
func (InvoiceProfile) String ¶ added in v0.10.0
func (p InvoiceProfile) String() string
String gives the Factur-X spelling, as written to fx:ConformanceLevel.
type JSONDiffOutputGenerator ¶ added in v0.10.0
type JSONDiffOutputGenerator struct{}
JSONDiffOutputGenerator renders comparison differences as JSON. Mirrors Aspose.PDF for .NET's JsonDiffOutputGenerator.
func NewJSONDiffOutputGenerator ¶ added in v0.10.0
func NewJSONDiffOutputGenerator() *JSONDiffOutputGenerator
NewJSONDiffOutputGenerator creates a generator. It takes no options — the operation data speaks for itself in JSON, unlike HTML/PDF which need colors to mark differences visually.
func (*JSONDiffOutputGenerator) GenerateOutput ¶ added in v0.10.0
func (g *JSONDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)
GenerateOutput renders ops as a flat JSON array of operations.
func (*JSONDiffOutputGenerator) GenerateOutputPages ¶ added in v0.10.0
func (g *JSONDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)
GenerateOutputPages renders pages as a JSON array of {"page","operations"} objects, one per page.
func (*JSONDiffOutputGenerator) SaveOutput ¶ added in v0.10.0
func (g *JSONDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error
SaveOutput writes GenerateOutput's JSON to path.
func (*JSONDiffOutputGenerator) SaveOutputPages ¶ added in v0.10.0
func (g *JSONDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error
SaveOutputPages writes GenerateOutputPages's JSON to path.
func (*JSONDiffOutputGenerator) WriteOutput ¶ added in v0.10.0
func (g *JSONDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error
WriteOutput writes GenerateOutput's JSON to w.
func (*JSONDiffOutputGenerator) WriteOutputPages ¶ added in v0.10.0
func (g *JSONDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
WriteOutputPages writes GenerateOutputPages's JSON to w.
type JSONExportOptions ¶ added in v0.4.0
type JSONExportOptions struct {
// Indent pretty-prints the JSON with two-space indentation.
Indent bool
// OmitEmpty skips fields with no value (empty text, unchecked checkbox,
// unselected radio/choice). By default every non-button field is exported,
// producing a full snapshot of the form.
OmitEmpty bool
}
JSONExportOptions controls (*Form).ExportJSON / WriteJSON.
type JavaScriptAction ¶
type JavaScriptAction struct {
// contains filtered or unexported fields
}
JavaScriptAction holds a JavaScript snippet attached to an annotation. JS actions are both parsed from existing PDFs and constructable via NewJavaScriptAction; a constructed action is encoded back on Save.
func NewJavaScriptAction ¶
func NewJavaScriptAction(script string) *JavaScriptAction
NewJavaScriptAction builds a /JavaScript action carrying the given script. The action runs when its parent annotation is activated (clicked) by a viewer that supports JavaScript.
SECURITY WARNING: Embedding JavaScript in a PDF can introduce security risks for recipients. Scripts execute in the viewer's JavaScript engine context with access to form fields, navigation, and viewer-specific APIs (varies by viewer). Use only with scripts you authored or audited; never embed user-supplied JS without careful review.
JavaScript actions are commonly disabled by default in viewers (Acrobat: Preferences > Security > "Enable JavaScript") so behavior is not guaranteed across all rendering environments.
func (*JavaScriptAction) ActionType ¶
func (a *JavaScriptAction) ActionType() ActionType
func (*JavaScriptAction) Script ¶
func (a *JavaScriptAction) Script() string
type JavaScriptCollection ¶ added in v0.4.0
type JavaScriptCollection struct {
// contains filtered or unexported fields
}
JavaScriptCollection is the document-level JavaScript store, backed by the /Catalog/Names/JavaScript name tree (ISO 32000-1 §7.7.4 / §8.5.1). Each entry is a named script that the viewer executes when the document opens (after any /OpenAction). Always non-nil; empty for documents without document-level JavaScript. Lazy-parsed on first call.
Mirrors Aspose.PDF for .NET's Document.JavaScript (a named-script collection). Note this is distinct from action-level JavaScriptAction, which runs on a specific annotation/field event.
SECURITY WARNING: document-level JavaScript executes in the recipient's viewer when the file is opened. Embed only scripts you authored or audited; viewers commonly disable JavaScript by default.
func (*JavaScriptCollection) Add ¶ added in v0.4.0
func (c *JavaScriptCollection) Add(name, script string) error
Add registers (or replaces) a named script and writes it through to the /Catalog/Names/JavaScript name tree. An empty name is rejected.
func (*JavaScriptCollection) Clear ¶ added in v0.4.0
func (c *JavaScriptCollection) Clear()
Clear removes every named script.
func (*JavaScriptCollection) Count ¶ added in v0.4.0
func (c *JavaScriptCollection) Count() int
Count reports how many named scripts are in the collection.
func (*JavaScriptCollection) Get ¶ added in v0.4.0
func (c *JavaScriptCollection) Get(name string) string
Get returns the script registered under name, or "" if absent.
func (*JavaScriptCollection) Has ¶ added in v0.4.0
func (c *JavaScriptCollection) Has(name string) bool
Has reports whether a script with the given name exists.
func (*JavaScriptCollection) Names ¶ added in v0.4.0
func (c *JavaScriptCollection) Names() []string
Names returns the script names in lexical order (the order they are written to the name tree).
func (*JavaScriptCollection) Remove ¶ added in v0.4.0
func (c *JavaScriptCollection) Remove(name string) bool
Remove deletes the named script. Returns true if it existed.
type JpegDevice ¶ added in v0.3.0
type JpegDevice struct {
// contains filtered or unexported fields
}
JpegDevice renders a page to JPEG. Mirrors Aspose.PDF for .NET's JpegDevice.
func NewJpegDevice ¶ added in v0.3.0
func NewJpegDevice(res Resolution, quality int) *JpegDevice
NewJpegDevice returns a JpegDevice; quality outside 1..100 defaults to 90.
type Layer ¶ added in v0.4.0
type Layer struct {
// contains filtered or unexported fields
}
Layer is one Optional Content Group (OCG) in the document.
func (*Layer) IsVisible ¶ added in v0.4.0
IsVisible reports whether the layer is shown by default (not listed in the default configuration's /OFF set).
func (*Layer) SetVisible ¶ added in v0.4.0
SetVisible sets the layer's default visibility (its membership in the default configuration's /OFF set). Viewers can still toggle it interactively.
type LineAnnotation ¶
type LineAnnotation struct {
// contains filtered or unexported fields
}
LineAnnotation draws a straight line between two points, with optional line endings on each end (arrows, circles, etc. — added in Task 14). The /Rect entry is auto-computed from the endpoints + padding for line endings.
func NewLineAnnotation ¶
func NewLineAnnotation(page *Page, start, end Point) *LineAnnotation
NewLineAnnotation builds an unbound line annotation. Page must be non-nil. The /Rect is auto-computed as the bounding box of the line plus padding equal to 9 × BorderWidth (Acrobat convention) on each side.
func (*LineAnnotation) AnnotationType ¶
func (a *LineAnnotation) AnnotationType() AnnotationType
func (*LineAnnotation) BorderStyle ¶
func (d *LineAnnotation) BorderStyle() BorderStyle
BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.
func (*LineAnnotation) BorderWidth ¶
func (d *LineAnnotation) BorderWidth() float64
BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.
func (*LineAnnotation) DashPattern ¶
func (d *LineAnnotation) DashPattern() []float64
DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.
func (*LineAnnotation) EndLineEnding ¶
func (a *LineAnnotation) EndLineEnding() LineEndingStyle
EndLineEnding returns the style applied to the end of the line.
func (*LineAnnotation) InteriorColor ¶
func (a *LineAnnotation) InteriorColor() *Color
InteriorColor returns the /IC fill color (used for filled line endings: ClosedArrow, RClosedArrow, Square, Circle, Diamond). Returns nil if absent.
func (*LineAnnotation) LeaderLineLength ¶
func (a *LineAnnotation) LeaderLineLength() float64
LeaderLineLength returns the /LL value (0 if absent). Used for dimension-line annotations where the line is offset from the measured points by this much.
func (*LineAnnotation) RegenerateAppearance ¶
func (a *LineAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*LineAnnotation) SetBorderStyle ¶
func (d *LineAnnotation) SetBorderStyle(s BorderStyle)
SetBorderStyle writes /BS/S using the PDF spec name codes.
func (*LineAnnotation) SetBorderWidth ¶
func (a *LineAnnotation) SetBorderWidth(w float64)
SetBorderWidth overrides drawingAnnotationBase.SetBorderWidth so /Rect (which depends on BorderWidth via line-ending padding) is recomputed before /AP/N regenerates — ensuring the appearance stream's /BBox matches the new bounds in a single pass.
func (*LineAnnotation) SetColor ¶
func (d *LineAnnotation) SetColor(c *Color)
SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.
func (*LineAnnotation) SetDashPattern ¶
func (d *LineAnnotation) SetDashPattern(p []float64)
SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.
func (*LineAnnotation) SetEnd ¶
func (a *LineAnnotation) SetEnd(p Point)
SetEnd updates the line's end point and recomputes /Rect.
func (*LineAnnotation) SetEndLineEnding ¶
func (a *LineAnnotation) SetEndLineEnding(s LineEndingStyle)
SetEndLineEnding sets the end-side line-ending style.
func (*LineAnnotation) SetInteriorColor ¶
func (a *LineAnnotation) SetInteriorColor(c *Color)
SetInteriorColor writes /IC as an RGB array; nil removes the entry.
func (*LineAnnotation) SetLeaderLineLength ¶
func (a *LineAnnotation) SetLeaderLineLength(l float64)
SetLeaderLineLength writes /LL. Zero removes the entry.
func (*LineAnnotation) SetRect ¶
func (d *LineAnnotation) SetRect(r Rectangle)
SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).
func (*LineAnnotation) SetStart ¶
func (a *LineAnnotation) SetStart(p Point)
SetStart updates the line's start point and recomputes /Rect.
func (*LineAnnotation) SetStartLineEnding ¶
func (a *LineAnnotation) SetStartLineEnding(s LineEndingStyle)
SetStartLineEnding sets the start-side line-ending style.
func (*LineAnnotation) Start ¶
func (a *LineAnnotation) Start() Point
Start returns the line's start point.
func (*LineAnnotation) StartLineEnding ¶
func (a *LineAnnotation) StartLineEnding() LineEndingStyle
StartLineEnding returns the style applied to the start of the line. Defaults to LineEndingNone if /LE is absent or malformed.
type LineEndingStyle ¶
type LineEndingStyle int
LineEndingStyle is one of the 10 line-ending shapes per ISO 32000-1 §12.5.6.7 Table 176, used in /Line annotations' /LE entry.
const ( LineEndingNone LineEndingStyle = iota LineEndingSquare LineEndingCircle LineEndingDiamond LineEndingOpenArrow LineEndingClosedArrow LineEndingButt LineEndingROpenArrow // OpenArrow rotated 180° (away from line) LineEndingRClosedArrow // ClosedArrow rotated 180° LineEndingSlash )
type LineJoin ¶
type LineJoin int
LineJoin is the /j line join style per ISO 32000-1 §8.4.3.4 Table 55.
type LineStyle ¶
type LineStyle struct {
Color *Color // nil → black {0,0,0,1}
Width float64 // ≤ 0 → no stroke (the draw call becomes a no-op for stroke)
DashPattern []float64 // [on, off, on, off, ...]; nil or empty → solid
DashPhase float64 // offset into the dash pattern, default 0
Cap LineCap // default LineCapButt (see appearance_builder.go); per ISO 32000-1 §8.4.3.3
Join LineJoin // default LineJoinMiter (see appearance_builder.go); per ISO 32000-1 §8.4.3.4
MiterLimit float64 // ≤ 0 → PDF default (10)
}
LineStyle describes how a stroked path is drawn.
Zero value: black, 0pt wide (no stroke), solid, butt cap, miter join. Mirrors Aspose.PDF for .NET's GraphInfo stroke fields.
type LinearGradient ¶ added in v0.3.0
type LinearGradient struct {
X1, Y1, X2, Y2 float64
Stops []GradientStop
}
LinearGradient interpolates colour along the line from (X1, Y1) to (X2, Y2). Use NewLinearGradient for the common case.
func NewLinearGradient ¶ added in v0.3.0
func NewLinearGradient(x1, y1, x2, y2 float64, stops ...GradientStop) LinearGradient
NewLinearGradient builds a linear gradient from (x1, y1) to (x2, y2) with the given stops.
type LinkAnnotation ¶
type LinkAnnotation struct {
// contains filtered or unexported fields
}
LinkAnnotation is a clickable region. Its visual is rendered by the viewer (no /AP needed). The associated /A action determines what happens on click — see Action and the various NewXxxAction factories.
func NewLinkAnnotation ¶
func NewLinkAnnotation(page *Page, rect Rectangle) *LinkAnnotation
NewLinkAnnotation builds an unbound link annotation. Page must be non-nil. The annotation is not added to the document until page.Annotations().Add(link) succeeds.
Example ¶
Add a clickable link annotation that opens an external URL.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
link := pdf.NewLinkAnnotation(page, pdf.Rectangle{LLX: 50, LLY: 700, URX: 300, URY: 720})
link.SetAction(pdf.NewGoToURIAction("https://pkg.go.dev/github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"))
if err := page.Annotations().Add(link); err != nil {
log.Fatal(err)
}
fmt.Println("annotations:", page.Annotations().Count())
}
Output: annotations: 1
func (*LinkAnnotation) Action ¶
func (a *LinkAnnotation) Action() Action
Action returns the action attached to this link, or nil if no /A is present or the action type is unsupported.
func (*LinkAnnotation) AnnotationType ¶
func (a *LinkAnnotation) AnnotationType() AnnotationType
func (*LinkAnnotation) BorderWidth ¶ added in v0.3.0
func (a *LinkAnnotation) BorderWidth() float64
BorderWidth returns the width (in points) of the rectangular border drawn around the link annotation. Returns the PDF default of 1pt when /Border is absent, matching the behaviour of viewers like Acrobat.
func (*LinkAnnotation) Color ¶
func (b *LinkAnnotation) Color() *Color
Color returns the /C array as an RGB Color. Returns nil if /C is absent.
func (*LinkAnnotation) Contents ¶
func (b *LinkAnnotation) Contents() string
Contents returns /Contents (the annotation body text).
func (*LinkAnnotation) Flatten ¶ added in v0.3.0
func (b *LinkAnnotation) Flatten() error
Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.
An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.
Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.
func (*LinkAnnotation) Highlight ¶
func (a *LinkAnnotation) Highlight() LinkHighlightMode
Highlight returns the click-feedback mode (/H entry). Returns LinkHighlightInvert if /H is absent (the PDF default).
func (*LinkAnnotation) PageIndex ¶
func (b *LinkAnnotation) PageIndex() int
PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.
func (*LinkAnnotation) Rect ¶
func (b *LinkAnnotation) Rect() Rectangle
Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.
func (*LinkAnnotation) SetAction ¶
func (a *LinkAnnotation) SetAction(act Action)
SetAction writes the /A entry. nil clears /A.
func (*LinkAnnotation) SetBorderWidth ¶ added in v0.3.0
func (a *LinkAnnotation) SetBorderWidth(width float64)
SetBorderWidth writes the /Border entry — [horiz-corner-radius vert-corner-radius border-width]. Pass 0 to suppress the rectangle PDF viewers otherwise draw around the link by default.
func (*LinkAnnotation) SetColor ¶
func (b *LinkAnnotation) SetColor(c *Color)
SetColor writes /C as an RGB array; nil removes the entry.
func (*LinkAnnotation) SetContents ¶
func (b *LinkAnnotation) SetContents(s string)
SetContents writes /Contents (the annotation body text); empty string removes the entry.
func (*LinkAnnotation) SetHighlight ¶
func (a *LinkAnnotation) SetHighlight(h LinkHighlightMode)
SetHighlight writes the /H entry. LinkHighlightInvert (the default) removes /H entirely so that the dict matches a freshly-created link.
func (*LinkAnnotation) SetRect ¶
func (b *LinkAnnotation) SetRect(r Rectangle)
SetRect writes the annotation rectangle.
type LinkHighlightMode ¶
type LinkHighlightMode int
LinkHighlightMode controls the visual feedback when the link is activated by the user (the /H entry per ISO 32000-1 §12.5.6.5).
const ( // LinkHighlightInvert (default) inverts the contents of the link // rectangle when activated. LinkHighlightInvert LinkHighlightMode = iota // LinkHighlightNone means no visible feedback on activation. LinkHighlightNone // LinkHighlightOutline inverts the annotation's border. LinkHighlightOutline // LinkHighlightPush visually depresses the rectangle on activation. LinkHighlightPush )
type ListBoxField ¶
type ListBoxField struct {
// contains filtered or unexported fields
}
ListBoxField is a single- or multi-select list choice field.
func (*ListBoxField) AddOption ¶
func (f *ListBoxField) AddOption(o ChoiceOption)
AddOption appends a ChoiceOption to /Opt.
func (*ListBoxField) Flatten ¶ added in v0.3.0
func (b *ListBoxField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*ListBoxField) IsReadOnly ¶
func (b *ListBoxField) IsReadOnly() bool
func (*ListBoxField) IsRequired ¶
func (b *ListBoxField) IsRequired() bool
func (*ListBoxField) MultiSelect ¶
func (f *ListBoxField) MultiSelect() bool
func (*ListBoxField) Options ¶
func (f *ListBoxField) Options() []ChoiceOption
func (*ListBoxField) PartialName ¶
func (b *ListBoxField) PartialName() string
func (*ListBoxField) RemoveOption ¶
func (f *ListBoxField) RemoveOption(index int) error
RemoveOption removes the option at index. Errors on out-of-range.
func (*ListBoxField) Selected ¶
func (f *ListBoxField) Selected() []int
Selected returns the indices of currently selected options. Single- select listboxes return at most one element.
func (*ListBoxField) SetMultiSelect ¶
func (f *ListBoxField) SetMultiSelect(v bool)
SetMultiSelect toggles bit 22 (/Ff MultiSelect) on a ListBoxField.
func (*ListBoxField) SetReadOnly ¶
func (f *ListBoxField) SetReadOnly(v bool)
func (*ListBoxField) SetRequired ¶
func (f *ListBoxField) SetRequired(v bool)
func (*ListBoxField) SetSelected ¶
func (f *ListBoxField) SetSelected(indices ...int) error
SetSelected replaces the selected indices. Variadic arguments allow SetSelected() (clear), SetSelected(0) (single), SetSelected(0, 1) (multi). Multi-selection on a single-select listbox returns an error.
func (*ListBoxField) SetStyle ¶ added in v0.3.0
func (b *ListBoxField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*ListBoxField) SetValue ¶
func (f *ListBoxField) SetValue(s string) error
func (*ListBoxField) Style ¶ added in v0.3.0
func (b *ListBoxField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
func (*ListBoxField) Value ¶
func (f *ListBoxField) Value() string
type MarginInfo ¶
MarginInfo describes margins or padding in points: Top / Right / Bottom / Left. Inside a Cell, MarginInfo represents the padding between the cell's border and its text content. Mirrors Aspose.PDF for .NET's MarginInfo.
type MarkdownDiffOutputGenerator ¶ added in v0.10.0
type MarkdownDiffOutputGenerator struct{}
MarkdownDiffOutputGenerator renders comparison differences as GFM Markdown: **inserted** text bold, ~~deleted~~ text struck through. Mirrors Aspose.PDF for .NET's MarkdownDiffOutputGenerator. As in Aspose, it takes no style options — Markdown's syntax already fixes how insert/delete are marked, and it cannot represent a whitespace-only change at all.
func NewMarkdownDiffOutputGenerator ¶ added in v0.10.0
func NewMarkdownDiffOutputGenerator() *MarkdownDiffOutputGenerator
NewMarkdownDiffOutputGenerator creates a generator.
func (*MarkdownDiffOutputGenerator) GenerateOutput ¶ added in v0.10.0
func (g *MarkdownDiffOutputGenerator) GenerateOutput(ops []DiffOperation) (string, error)
GenerateOutput renders ops as one Markdown fragment, operations joined by a single space (matching AssembleSourceText/AssembleDestinationText).
func (*MarkdownDiffOutputGenerator) GenerateOutputPages ¶ added in v0.10.0
func (g *MarkdownDiffOutputGenerator) GenerateOutputPages(pages [][]DiffOperation) (string, error)
GenerateOutputPages renders one "## Page N" section per page.
func (*MarkdownDiffOutputGenerator) SaveOutput ¶ added in v0.10.0
func (g *MarkdownDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error
SaveOutput writes GenerateOutput's Markdown to path.
func (*MarkdownDiffOutputGenerator) SaveOutputPages ¶ added in v0.10.0
func (g *MarkdownDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error
SaveOutputPages writes GenerateOutputPages's Markdown to path.
func (*MarkdownDiffOutputGenerator) WriteOutput ¶ added in v0.10.0
func (g *MarkdownDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error
WriteOutput writes GenerateOutput's Markdown to w.
func (*MarkdownDiffOutputGenerator) WriteOutputPages ¶ added in v0.10.0
func (g *MarkdownDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
WriteOutputPages writes GenerateOutputPages's Markdown to w.
type MarkdownOptions ¶ added in v0.6.0
type MarkdownOptions struct {
Format PageFormat // zero → A4
Margin float64 // page margin; zero → 54pt
// Fonts. BaseFont nil → Helvetica (Standard-14, Latin-1 text only —
// load a Unicode face with Document.LoadFont for Cyrillic, Greek, …).
// The style variants default to the matching Standard-14 faces when
// BaseFont is nil, and to BaseFont itself otherwise.
BaseFont, BoldFont, ItalicFont, BoldItalicFont Font
CodeFont Font // nil → Courier
BaseSize float64 // body size; zero → 11pt (headings scale from it)
// FontFamily resolves and embeds a font family by name (registered
// folders/files first, then the OS fonts — see LoadFontByName) for the
// regular/bold/italic/bold-italic styles, giving full Unicode text
// (e.g. "Arial", "DejaVu Sans"). Styles that fail to resolve fall back
// to the regular face. Explicit BaseFont/BoldFont/… win over it.
// CodeFontFamily does the same for the code face (e.g. "Consolas").
FontFamily string
CodeFontFamily string
// BasePath resolves relative image paths. Empty → the .md file's
// directory (MarkdownToDocument) or the current directory.
BasePath string
// Tagged builds a logical structure tree while rendering (headings,
// paragraphs, lists, tables, figures) for accessible (PDF/UA) output.
Tagged bool
// Title and Language feed the tagged document's metadata (PDF/UA
// requires both). Title empty → derived from the first heading;
// Language empty → "en". Ignored when Tagged is false.
Title string
Language string
}
MarkdownOptions configures Markdown rendering. The zero value gives A4, 54pt margins, Helvetica/Courier at 11pt.
type MarkdownSaveOptions ¶ added in v0.7.0
type MarkdownSaveOptions struct {
// Pages is a 1-based subset (in the given order); nil = all pages.
Pages []int
// ImageDir (SaveMarkdown only) is the directory, relative to the output
// file, that images are written into. Empty → "<stem>_files".
ImageDir string
// ImageWriter externalizes images anywhere (S3, CDN, …): it receives a
// unique name + bytes and returns the URL to reference. Byte-identical
// images are written once (SHA-256 dedup).
ImageWriter func(name string, data []byte) (url string, err error)
// EmbedImages inlines images as data: URLs instead of files. Note that
// some renderers (e.g. GitHub) do not display data: images.
EmbedImages bool
// NoImages skips images entirely.
NoImages bool
}
MarkdownSaveOptions configures SaveMarkdown / WriteMarkdown. The zero value exports all pages; SaveMarkdown writes images into "<stem>_files" next to the output.
type MarkupParagraph ¶ added in v0.4.0
type MarkupParagraph struct {
Text string // the paragraph text (its lines joined with spaces)
Rectangle Rectangle // bounding box in PDF user space
Lines []TextLine // the paragraph's lines (with per-fragment positions)
}
MarkupParagraph is a run of consecutive lines forming one paragraph.
type MarkupSection ¶ added in v0.4.0
type MarkupSection struct {
Rectangle Rectangle
Paragraphs []MarkupParagraph
}
MarkupSection is a column of paragraphs (left-to-right across the page).
type MissingGlyphPolicy ¶ added in v0.14.0
type MissingGlyphPolicy int
MissingGlyphPolicy is TextStyle.MissingGlyph's type. See its doc comment for what each value does.
const ( // MissingGlyphAllow draws .notdef (or, for Type3, nothing) for a // character the font has no glyph for — today's existing behavior, // and the zero value, so no caller is affected unless it opts in. MissingGlyphAllow MissingGlyphPolicy = iota // MissingGlyphError makes the draw/measure call fail, naming the // first character the font cannot show. MissingGlyphError // MissingGlyphReplace substitutes TextStyle.ReplacementRune for // every character the font cannot show, drawing that instead of // .notdef. MissingGlyphReplace )
type NUpOptions ¶ added in v0.4.0
type NUpOptions struct {
// Rows and Cols define the grid; both must be >= 1.
Rows, Cols int
// PageSize is the output sheet size. The zero value uses A4.
PageSize PageFormat
// Margin is the blank border around the whole grid, in points.
Margin float64
// Gutter is the spacing between adjacent cells, in points.
Gutter float64
// Order is the cell-filling order (row-major by default).
Order NUpOrder
// DrawBorder draws a thin frame around each placed page.
DrawBorder bool
}
NUpOptions configures NUp imposition.
type NUpOrder ¶ added in v0.4.0
type NUpOrder int
NUpOrder controls the order in which source pages fill the grid cells of an N-up sheet.
type NamedAction ¶
type NamedAction struct {
// contains filtered or unexported fields
}
NamedAction triggers a built-in viewer command (FirstPage, Print, ...).
func NewNamedAction ¶
func NewNamedAction(n NamedActionType) *NamedAction
NewNamedAction builds a /Named action.
func (*NamedAction) ActionType ¶
func (a *NamedAction) ActionType() ActionType
func (*NamedAction) Name ¶
func (a *NamedAction) Name() NamedActionType
func (*NamedAction) SetName ¶
func (a *NamedAction) SetName(n NamedActionType)
type NamedActionType ¶
type NamedActionType int
NamedActionType identifies one of the standard viewer commands supported by /Named actions per ISO 32000-1 §12.6.4.11.
const ( NamedActionUnknown NamedActionType = iota NamedActionFirstPage NamedActionLastPage NamedActionNextPage NamedActionPrevPage NamedActionPrint )
type NamedDestination ¶
type NamedDestination struct {
// contains filtered or unexported fields
}
NamedDestination wraps a name reference into the document's NamedDestinations collection. Implements Destination so it can be used wherever an explicit destination is accepted (outline entries, future link annotation /Dest values, GoToAction).
Resolution is lazy: Page() and Resolve() look up the name in doc.NamedDestinations() at call time. This allows constructing a NamedDestination before adding the entry to the collection (forward reference).
Per ISO 32000-1 §12.3.2.3.
func NewNamedDestination ¶
func NewNamedDestination(doc *Document, name string) *NamedDestination
NewNamedDestination builds a name-reference destination. The name need not be registered yet — resolution is lazy at Page() and write time.
Aspose .NET: new NamedDestination(name) Go: pdf.NewNamedDestination(doc, name)
func (*NamedDestination) DestinationType ¶
func (n *NamedDestination) DestinationType() DestinationType
DestinationType returns DestinationTypeNamed.
func (*NamedDestination) Name ¶
func (n *NamedDestination) Name() string
Name returns the registered name this destination references.
func (*NamedDestination) Page ¶
func (n *NamedDestination) Page() *Page
Page resolves the underlying destination's page via the document's NamedDestinations collection. Returns nil if the name is not registered or the underlying destination has no Page.
func (*NamedDestination) Resolve ¶
func (n *NamedDestination) Resolve() Destination
Resolve returns the underlying explicit destination registered under this name, or nil if absent. Useful when you need the typed concrete (e.g. *DestinationXYZ to read coordinates).
type NamedDestinations ¶
type NamedDestinations struct {
// contains filtered or unexported fields
}
NamedDestinations is a name-to-destination map per ISO 32000-1 §12.3.2.3. Backed at PDF level by the modern /Catalog/Names/Dests name tree (PDF 1.2+); on read it also absorbs legacy /Catalog/Dests for backward compatibility. On write, only /Names/Dests is emitted.
Mirrors Aspose.PDF for .NET's NamedDestinations collection.
func (*NamedDestinations) Add ¶
func (n *NamedDestinations) Add(name string, dest Destination) error
Add registers dest under name. Errors on:
- empty name
- nil dest
- dest is itself a *NamedDestination (would create a name→name loop)
If name was already present, the previous value is replaced silently.
func (*NamedDestinations) All ¶
func (n *NamedDestinations) All() map[string]Destination
All returns a snapshot map of name → destination.
func (*NamedDestinations) Count ¶
func (n *NamedDestinations) Count() int
Count returns the number of registered entries.
func (*NamedDestinations) Document ¶
func (n *NamedDestinations) Document() *Document
Document returns the document this collection is bound to.
func (*NamedDestinations) Get ¶
func (n *NamedDestinations) Get(name string) Destination
Get returns the destination registered under name, or nil if absent. Never returns a *NamedDestination (no recursive lookups).
func (*NamedDestinations) Has ¶
func (n *NamedDestinations) Has(name string) bool
Has reports whether name is registered.
func (*NamedDestinations) Names ¶
func (n *NamedDestinations) Names() []string
Names returns a snapshot slice of all registered names in lex order.
func (*NamedDestinations) Remove ¶
func (n *NamedDestinations) Remove(name string) bool
Remove deletes the entry; returns true if it existed.
type NumberField ¶ added in v0.4.0
type NumberField struct{ TextBoxField }
NumberField is a text field with a JavaScript number-format action, so viewers display and validate the value as a formatted number.
func (*NumberField) Flatten ¶ added in v0.4.0
func (b *NumberField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*NumberField) IsReadOnly ¶ added in v0.4.0
func (b *NumberField) IsReadOnly() bool
func (*NumberField) IsRequired ¶ added in v0.4.0
func (b *NumberField) IsRequired() bool
func (*NumberField) PartialName ¶ added in v0.4.0
func (b *NumberField) PartialName() string
func (*NumberField) SetStyle ¶ added in v0.4.0
func (b *NumberField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*NumberField) Style ¶ added in v0.4.0
func (b *NumberField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
type NumberFormatOptions ¶ added in v0.4.0
type NumberFormatOptions struct {
Decimals int // number of decimal places (0 = integer)
UseSeparator bool // group thousands (1,234)
CurrencySymbol string // e.g. "$", "€" (empty = none)
CurrencyPrepend bool // symbol before the number ("$1" vs "1$")
}
NumberFormatOptions configures a NumberField's display formatting (maps to Acrobat's AFNumber_Format). The zero value is a plain integer.
type Operation ¶ added in v0.9.0
type Operation int
Operation is the kind of a difference. Mirrors Aspose.PDF for .NET's Aspose.Pdf.Comparison.Operation.
type OptimizationOptions ¶ added in v0.6.0
type OptimizationOptions struct {
// RemoveUnusedObjects drops objects that neither a page nor the
// document catalog uses.
RemoveUnusedObjects bool
// SubsetFonts rebuilds embedded TrueType fonts to the glyphs used.
SubsetFonts bool
// UnembedFonts drops the embedded program from a simple font whose name
// and metrics match a Helvetica/Times/Courier Standard-14 face, relying
// on the renderer's substitution instead. Opt-in: unlike the other
// options this can change how the document looks in a viewer whose
// installed substitute differs from what was embedded.
UnembedFonts bool
// CompressStreams Flate-compresses source streams stored uncompressed
// (lossless).
CompressStreams bool
// RemoveDuplicateStreams merges byte-identical stream objects into one
// and repoints references (lossless).
RemoveDuplicateStreams bool
// CompressObjects packs non-stream objects into object streams and writes
// a cross-reference stream on Save/WriteTo (lossless; the file becomes
// PDF 1.5 or later). Ignored by SaveLinearized.
CompressObjects bool
// Images, when non-nil, downscales/recodes images per the options
// (potentially lossy — opt-in).
Images *OptimizeImageOptions
}
OptimizationOptions selects which reductions Document.Optimize applies. The zero value does nothing; use DefaultOptimizationOptions for the safe lossless preset. Mirrors Aspose.PDF for .NET's OptimizationOptions consumed by Document.OptimizeResources.
func DefaultOptimizationOptions ¶ added in v0.6.0
func DefaultOptimizationOptions() OptimizationOptions
DefaultOptimizationOptions returns the safe, lossless preset: remove unused objects, subset fonts, compress uncompressed streams, dedupe identical streams, and pack objects into object streams. Image recompression is left off (opt-in via Images because it can be lossy).
type OptimizationResult ¶ added in v0.6.0
type OptimizationResult struct {
RemovedObjects int
SubsettedFonts int
UnembeddedFonts int
OptimizedImages int
CompressedStreams int
DeduplicatedStreams int
// CompressedObjects is the number of objects eligible for packing when
// Optimize ran; the packing itself happens on Save/WriteTo.
CompressedObjects int
}
OptimizationResult reports what Document.Optimize changed.
type OptimizeImageOptions ¶
type OptimizeImageOptions struct {
MaxDPI float64 // images above this DPI are downscaled; 0 = no downscaling
JPEGQuality int // JPEG quality 1-100; 0 = default (75)
ConvertPNGToJPEG bool // convert opaque PNG (no alpha) to JPEG
}
OptimizeImageOptions controls image optimization behavior.
type OutlineItemCollection ¶
type OutlineItemCollection struct {
// contains filtered or unexported fields
}
OutlineItemCollection represents an outline entry and the collection of its children. The recursive structure mirrors Aspose.PDF for .NET: each entry is both a tree node (with Title, Color, Action, Destination, etc.) and a collection (Add/At/Remove/Count for children). The root collection — returned by Document.Outlines() — has no parent and an empty Title; only its children are visible as top-level bookmarks.
Per ISO 32000-1 §12.3.3.
func NewOutlineItemCollection ¶
func NewOutlineItemCollection(doc *Document) *OutlineItemCollection
NewOutlineItemCollection builds an unattached outline entry bound to the given document. Add it to a parent via Document.Outlines().Add(...) or via another entry's Add(...) — until added it has no effect on the saved PDF.
Aspose .NET: new OutlineItemCollection(doc.Outlines) Go: pdf.NewOutlineItemCollection(doc)
func (*OutlineItemCollection) Action ¶
func (o *OutlineItemCollection) Action() Action
Action returns the action attached via /A. Reuses the Action interface defined for annotations.
func (*OutlineItemCollection) Add ¶
func (o *OutlineItemCollection) Add(child *OutlineItemCollection) error
Add appends child as the last child of this entry. Errors on nil, cross-document, cycle, or already-attached child.
func (*OutlineItemCollection) All ¶
func (o *OutlineItemCollection) All() []*OutlineItemCollection
All returns a snapshot slice of direct children.
func (*OutlineItemCollection) At ¶
func (o *OutlineItemCollection) At(index int) *OutlineItemCollection
At returns the child at the given 0-based index, or nil if out-of-range.
func (*OutlineItemCollection) Bold ¶
func (o *OutlineItemCollection) Bold() bool
Bold corresponds to /F bit 2 in the outline item dict. Default false.
func (*OutlineItemCollection) Color ¶
func (o *OutlineItemCollection) Color() *Color
Color returns the RGB label color, or nil if /C is absent (default black). SetColor(nil) clears /C.
func (*OutlineItemCollection) Count ¶
func (o *OutlineItemCollection) Count() int
Count returns the number of direct children (placeholder until Task 5 adds the rest of the collection API).
func (*OutlineItemCollection) Destination ¶
func (o *OutlineItemCollection) Destination() Destination
Destination returns the explicit view destination via /Dest, or nil if absent. If both Destination and Action are set, /Dest takes priority per ISO 32000-1 §12.3.3.
func (*OutlineItemCollection) Document ¶
func (o *OutlineItemCollection) Document() *Document
Document returns the document this collection is bound to.
func (*OutlineItemCollection) Insert ¶
func (o *OutlineItemCollection) Insert(index int, child *OutlineItemCollection) error
Insert inserts child at the given 0-based index among this entry's children.
func (*OutlineItemCollection) IsExpanded ¶
func (o *OutlineItemCollection) IsExpanded() bool
IsExpanded controls the viewer's initial expand/collapse state. Encoded via the sign of /Count. Default true.
func (*OutlineItemCollection) Italic ¶
func (o *OutlineItemCollection) Italic() bool
Italic corresponds to /F bit 1. Default false.
func (*OutlineItemCollection) Parent ¶
func (o *OutlineItemCollection) Parent() *OutlineItemCollection
Parent returns the parent entry, or nil for the root collection.
func (*OutlineItemCollection) Remove ¶
func (o *OutlineItemCollection) Remove(child *OutlineItemCollection) bool
Remove detaches child if it's a direct child. Returns true on hit.
func (*OutlineItemCollection) RemoveAt ¶
func (o *OutlineItemCollection) RemoveAt(index int) error
RemoveAt detaches the child at the given index.
func (*OutlineItemCollection) SetAction ¶
func (o *OutlineItemCollection) SetAction(a Action)
SetAction sets the /A action. Pass nil to clear.
func (*OutlineItemCollection) SetBold ¶
func (o *OutlineItemCollection) SetBold(b bool)
func (*OutlineItemCollection) SetColor ¶
func (o *OutlineItemCollection) SetColor(c *Color)
func (*OutlineItemCollection) SetDestination ¶
func (o *OutlineItemCollection) SetDestination(d Destination)
SetDestination sets the /Dest entry. Pass nil to clear.
func (*OutlineItemCollection) SetIsExpanded ¶
func (o *OutlineItemCollection) SetIsExpanded(b bool)
func (*OutlineItemCollection) SetItalic ¶
func (o *OutlineItemCollection) SetItalic(b bool)
func (*OutlineItemCollection) SetTitle ¶
func (o *OutlineItemCollection) SetTitle(s string)
SetTitle replaces the bookmark text.
func (*OutlineItemCollection) Title ¶
func (o *OutlineItemCollection) Title() string
Title returns the bookmark text.
type PDFAFormat ¶ added in v0.4.0
type PDFAFormat int
PDFAFormat identifies a PDF/A conformance level. The "b" (basic) levels cover visual reproducibility; the "a" (accessible) levels add the PDF/A "a" requirement of a Tagged PDF logical structure tree (author one with (*Document).TaggedContent). Mirrors the PDF/A members of Aspose.PDF for .NET's PdfFormat enum.
const ( PDFA1B PDFAFormat = iota // PDF/A-1b (ISO 19005-1, PDF 1.4) PDFA2B // PDF/A-2b (ISO 19005-2, PDF 1.7) PDFA3B // PDF/A-3b (ISO 19005-3, PDF 1.7; allows embedded files) PDFA1A // PDF/A-1a (ISO 19005-1, accessible/tagged) PDFA2A // PDF/A-2a (ISO 19005-2, accessible/tagged) PDFA3A // PDF/A-3a (ISO 19005-3, accessible/tagged) )
func (PDFAFormat) String ¶ added in v0.4.0
func (f PDFAFormat) String() string
String returns the human-readable conformance name, e.g. "PDF/A-1B".
type PDFAValidationReport ¶ added in v0.4.0
type PDFAValidationReport struct {
Format PDFAFormat
// Conformant is true when no violations were found for the requested level.
Conformant bool
Issues []PDFAIssue
}
PDFAValidationReport is returned by (*Document).ValidatePDFA.
type PDFDiffOutputGenerator ¶ added in v0.10.0
type PDFDiffOutputGenerator struct {
// contains filtered or unexported fields
}
PDFDiffOutputGenerator renders comparison differences as a generated PDF report — colored, word-wrapped, paginated text — built through this library's Flow layer rather than Aspose's own (presumably fixed-layout) renderer. Mirrors Aspose.PDF for .NET's PdfOutputGenerator. Unlike HTML/JSON/Markdown, a PDF cannot be produced as a string, so this type only implements FileDiffOutputGenerator, matching Aspose (PdfOutputGenerator does not implement IStringOutputGenerator either).
func NewPDFDiffOutputGenerator ¶ added in v0.10.0
func NewPDFDiffOutputGenerator(opts ...PDFDiffReportOptions) *PDFDiffOutputGenerator
NewPDFDiffOutputGenerator creates a generator with the given options (last one wins); the zero value uses PDFDiffReportOptions's defaults.
func (*PDFDiffOutputGenerator) SaveOutput ¶ added in v0.10.0
func (g *PDFDiffOutputGenerator) SaveOutput(path string, ops []DiffOperation) error
SaveOutput writes a single-section report to path.
func (*PDFDiffOutputGenerator) SaveOutputPages ¶ added in v0.10.0
func (g *PDFDiffOutputGenerator) SaveOutputPages(path string, pages [][]DiffOperation) error
SaveOutputPages writes a report with one heading section per page to path.
func (*PDFDiffOutputGenerator) WriteOutput ¶ added in v0.10.0
func (g *PDFDiffOutputGenerator) WriteOutput(w io.Writer, ops []DiffOperation) error
WriteOutput writes a single-section report to w.
func (*PDFDiffOutputGenerator) WriteOutputPages ¶ added in v0.10.0
func (g *PDFDiffOutputGenerator) WriteOutputPages(w io.Writer, pages [][]DiffOperation) error
WriteOutputPages writes a report with one heading section per page to w.
type PDFDiffReportOptions ¶ added in v0.10.0
type PDFDiffReportOptions struct {
DiffOutputStyle
Format PageFormat // zero → A4
Title string // zero → "Comparison Report"
}
PDFDiffReportOptions configures PDFDiffOutputGenerator. The zero value resolves to A4, the default DiffOutputStyle colors, and the title "Comparison Report". Mirrors the constructor overloads of Aspose.PDF for .NET's PdfOutputGenerator (OutputTextStyle, PageInfo), folded into one options struct since Go has no overloading.
type PDFUAIssue ¶ added in v0.4.0
PDFUAIssue describes a single PDF/UA (accessibility) conformance violation.
type PDFUAValidationReport ¶ added in v0.4.0
type PDFUAValidationReport struct {
// Conformant is true when no violations were found.
Conformant bool
Issues []PDFUAIssue
}
PDFUAValidationReport is returned by (*Document).ValidatePDFUA.
type Page ¶
type Page struct {
// contains filtered or unexported fields
}
Page is a live view of a single page within a Document. It reflects the current state of the document, including any mutations.
func (*Page) AddFloatingBox ¶ added in v0.4.0
func (p *Page) AddFloatingBox(box *FloatingBox, rect Rectangle) error
AddFloatingBox draws box at an absolute position inside rect: it paints the background and border, then lays out the box content within rect minus padding (content that overflows the box is clipped). When the document is tagged the box becomes a /Div structure element and its decoration an artifact.
func (*Page) AddForm ¶ added in v0.4.0
AddForm places the form on the page so its box maps onto rect, preserving the form's own scale per axis. The form is built (frozen) on the first call and reused for every subsequent placement — one /Form XObject, many Do invocations across pages and positions. A zero-size rect is rejected.
func (*Page) AddImage ¶
AddImage adds an image from a file to the page within the given rectangle.
Example ¶
Place a JPEG image on a blank page.
package main
import (
"bytes"
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
rect := pdf.Rectangle{LLX: 50, LLY: 50, URX: 300, URY: 300}
if err := page.AddImage("testdata/Koala.jpg", rect); err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
if _, err := doc.WriteTo(&buf); err != nil {
log.Fatal(err)
}
fmt.Println("ok")
}
Output: ok
func (*Page) AddImageFromStream ¶
AddImageFromStream adds an image from a reader to the page within the given rectangle.
func (*Page) AddInlineImage ¶ added in v0.4.0
AddInlineImage draws a small image directly into the page content stream as an inline image (BI … ID … EI, ISO 32000-1 §8.9.7) rather than an Image XObject. Inline images suit tiny, one-off pictures (icons, rules); for anything larger, AddImage (an XObject) is the better choice and the recommended default. PNG and JPEG inputs are supported; PNG transparency is dropped (inline images cannot carry a soft mask). The image is scaled to fill rect. Mirrors the inline-image idiom of ISO 32000-1 §8.9.7.
func (*Page) AddInlineImageFromStream ¶ added in v0.4.0
AddInlineImageFromStream is the io.Reader variant of AddInlineImage.
func (*Page) AddMarkdown ¶ added in v0.6.0
func (p *Page) AddMarkdown(md string, rect Rectangle, opts ...MarkdownOptions) error
AddMarkdown renders a Markdown fragment inside the rectangle. Content that does not fit is clipped (same convention as FloatingBox).
func (*Page) AddSVG ¶ added in v0.2.0
AddSVG reads an SVG file and renders it into the given rectangle on the page. Unsupported elements (text, image, gradients, masks) are skipped silently per Phase 2 scope.
Returns error only on XML parse failure, invalid numeric attributes, or I/O errors.
func (*Page) AddSVGFromStream ¶ added in v0.2.0
AddSVGFromStream renders an SVG from any io.Reader into the given rectangle on the page. Best-effort: unsupported elements are silently skipped.
func (*Page) AddSVGObject ¶ added in v0.2.0
AddSVGObject renders a pre-parsed SVG into the given rectangle on the page. Useful when the same SVG is rendered on multiple pages without re-parsing.
func (*Page) AddStamp ¶ added in v0.4.0
AddStamp draws a stamp onto the page. Mirrors Aspose.PDF for .NET's Page.AddStamp(Stamp).
func (*Page) AddTOC ¶ added in v0.4.0
AddTOC renders a table of contents from a supplied list of entries into rect on this page. Entries flow top-to-bottom; long titles are truncated to fit before the page-number column. When the entries overflow rect, continuation pages of the same size are appended to the document and the number of pages added is returned (0 if everything fits in rect).
Each entry with a non-nil Page is drawn with its page number and a clickable GoTo link (unless disabled in TOCOptions). Mirrors building a TOC region by hand in Aspose.PDF for .NET.
func (*Page) AddTable ¶
AddTable renders the table inside the given rectangle.
Returns the number of pages automatically appended to the document (0 when the table fits in rect). When the table doesn't fit and overflow is needed, new pages are appended with dimensions matching the receiver page; the continuation rectangle is computed from t.OverflowMargins(). Repeating header rows (see Table.SetRepeatingRowsCount) draw at the top of each page, including the original.
Errors before any drawing on validation failures: nil table, bad rect, non-positive column widths, mismatched cell counts (span-aware), merge overlaps, rowspan crossing the header/body boundary, or a spanning group too tall to fit any page.
func (*Page) AddTaggedList ¶ added in v0.4.0
func (p *Page) AddTaggedList(tc *TaggedContent, parent *StructElement, items []string, style TextStyle, rect Rectangle, ordered bool) (*StructElement, error)
AddTaggedList draws a bulleted (ordered=false) or numbered (ordered=true) list of items inside rect and builds its accessible structure: an /L element under parent (nil = the document root), with an /LI per item containing an /Lbl (the bullet/number) and an /LBody (the item text). Each item's text wraps within the body column; items are stacked top-down and any that would fall below rect are dropped (no auto-pagination in this version). Returns the /L element. Requires Document.TaggedContent.
func (*Page) AddTaggedTable ¶ added in v0.4.0
func (p *Page) AddTaggedTable(tc *TaggedContent, parent *StructElement, t *Table, rect Rectangle) (*StructElement, int, error)
AddTaggedTable renders t inside rect like AddTable, and at the same time builds the table's logical structure (/Table → /TR → /TH/TD) under parent (nil = the document root), tagging each cell's content as marked content and bracketing cell backgrounds and borders as /Artifact. The first RepeatingRowsCount rows are tagged as header cells (/TH). Returns the /Table structure element and the number of continuation pages appended. Requires Document.TaggedContent to have been called. Mirrors the table tagging of Aspose.PDF for .NET's tagged content.
func (*Page) AddText ¶
AddText draws text inside the rectangle using the given style. Text is wrapped at word boundaries to fit the rectangle width. Content exceeding the rectangle height is clipped.
Example ¶
Draw "Hello, world!" centered on a blank A4 page and write the resulting PDF to an in-memory buffer.
package main
import (
"bytes"
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
size, _ := page.Size()
style := pdf.TextStyle{
Font: pdf.FontHelveticaBold,
Size: 24,
HAlign: pdf.HAlignCenter,
VAlign: pdf.VAlignMiddle,
}
rect := pdf.Rectangle{LLX: 0, LLY: 0, URX: size.Width, URY: size.Height}
if err := page.AddText("Hello, world!", style, rect); err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
if _, err := doc.WriteTo(&buf); err != nil {
log.Fatal(err)
}
fmt.Println("wrote:", buf.Len() > 0)
}
Output: wrote: true
func (*Page) AddTextAt ¶ added in v0.13.0
AddTextAt draws text as a single line whose baseline starts at (x, y): no word-wrapping, no clipping to any rectangle, and whitespace is kept exactly as given — unlike AddText, which normalizes runs of whitespace through strings.Fields while wrapping. For a caller that already does its own line-breaking and positioning and only needs this library to place and shape individual lines (GitHub issue #18, `pdf-go-xe3l`). Uses the same font resources, OpenType shaping (GSUB/GPOS) and bidi reordering as AddText, so MeasureText/GetFontMetrics below always agree with what this draws.
HAlign anchors the line at x the way SVG's text-anchor does: HAlignLeft (the default) starts the line at x, HAlignCenter centers it on x, HAlignRight ends it at x. y is always the exact baseline — no ascent-based offset is applied, unlike AddText's rect-relative vertical placement (see GetFontMetrics to compute that offset yourself, the same way AddText does internally).
Color, Underline, Strikethrough, Rotation (pivot = (x, y) instead of a rectangle corner), Skew, Invisible, Behind and RTL from TextStyle all apply the same way they do in AddText. Background and VAlign have no meaning without a rectangle to fill or align within and are ignored.
func (*Page) Annotations ¶
func (p *Page) Annotations() *AnnotationCollection
Annotations returns the page's annotation collection. Always non-nil; for a page with no /Annots array, the collection is empty.
func (*Page) ArtBox ¶
ArtBox returns the art box of the page as a Rectangle. Falls back to CropBox, then MediaBox if not set.
func (*Page) BeginLayer ¶ added in v0.4.0
BeginLayer starts a marked-content section on the page assigned to layer: content drawn after this call (AddText, Draw*, AddImage, …) belongs to the layer until EndLayer. Pair every BeginLayer with an EndLayer.
func (*Page) BleedBox ¶
BleedBox returns the bleed box of the page as a Rectangle. Falls back to CropBox, then MediaBox if not set.
func (*Page) CropBox ¶
CropBox returns the crop box of the page as a Rectangle. Falls back to MediaBox if not set. Mirrors Aspose.PDF for .NET's Page.CropBox.
func (*Page) DrawCircle ¶
func (p *Page) DrawCircle(center Point, radius float64, style ShapeStyle) error
DrawCircle strokes and/or fills a circle. Returns error for negative radius. No-op if radius is zero or neither stroke nor fill is configured.
Mirrors Aspose.PDF for .NET's Drawing.Circle.
func (*Page) DrawEllipse ¶
func (p *Page) DrawEllipse(center Point, rx, ry float64, style ShapeStyle) error
DrawEllipse strokes and/or fills an axis-aligned ellipse. Returns error for negative semi-axis. No-op if either semi-axis is zero or neither stroke nor fill is configured.
Mirrors Aspose.PDF for .NET's Drawing.Ellipse.
func (*Page) DrawLine ¶
DrawLine strokes a single line segment from→to with the given style. No-op if style.Width <= 0.
Mirrors Aspose.PDF for .NET's Drawing.Line shape.
func (*Page) DrawPath ¶
func (p *Page) DrawPath(path *Path, style ShapeStyle) error
DrawPath strokes and/or fills the previously-built path. Errors if path is nil. No-op if path has no operations or style is empty.
Mirrors Aspose.PDF for .NET's Drawing.GraphicsPath / Drawing.Curve.
func (*Page) DrawPolygon ¶
func (p *Page) DrawPolygon(points []Point, style ShapeStyle) error
DrawPolygon strokes and/or fills a closed polygon (last point connects back to the first via `h`). Errors if len(points) < 3. No-op if neither stroke nor fill is configured.
Mirrors Aspose.PDF for .NET's Drawing.Polygon.
func (*Page) DrawPolyline ¶
DrawPolyline strokes an open polyline (first and last points are NOT connected). No fill — even if one were specified, an open path has ambiguous fill semantics. Errors if len(points) < 2. No-op if style.Width <= 0.
Mirrors Aspose.PDF for .NET's Drawing.Polyline.
func (*Page) DrawRectangle ¶
func (p *Page) DrawRectangle(rect Rectangle, style ShapeStyle) error
DrawRectangle strokes and/or fills an axis-aligned rectangle. No-op if neither stroke (Width > 0) nor fill (FillColor != nil) is set.
Mirrors Aspose.PDF for .NET's Drawing.Rectangle shape.
Example ¶
Draw a filled rectangle with a stroked border on a blank page.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
style := pdf.ShapeStyle{
LineStyle: pdf.LineStyle{
Color: &pdf.Color{R: 0.1, G: 0.3, B: 0.6, A: 1},
Width: 2,
},
FillColor: &pdf.Color{R: 0.85, G: 0.92, B: 1, A: 1},
}
rect := pdf.Rectangle{LLX: 100, LLY: 600, URX: 400, URY: 750}
if err := page.DrawRectangle(rect, style); err != nil {
log.Fatal(err)
}
fmt.Println("ok")
}
Output: ok
func (*Page) DrawRoundedRectangle ¶
func (p *Page) DrawRoundedRectangle(rect Rectangle, radius float64, style ShapeStyle) error
DrawRoundedRectangle strokes and/or fills an axis-aligned rectangle with rounded corners of the given radius. The radius is clamped to half the shorter side. Returns error for negative radius.
Implemented as a Path: 4 straight edges + 4 quarter-arc corners.
Mirrors Aspose.PDF for .NET's Drawing.RoundedRectangle.
func (*Page) EndLayer ¶ added in v0.4.0
EndLayer closes the marked-content section opened by BeginLayer.
func (*Page) ExtractImages ¶
ExtractImages returns all images found on the page.
func (*Page) ExtractText ¶
func (p *Page) ExtractText(opts ...TextExtractOptions) (string, error)
ExtractText returns the text content of the page. Characters from fonts with unrecognized encodings are replaced with U+FFFD. An optional TextExtractOptions selects reading order (default) or raw content-stream order.
func (*Page) ExtractTextWithLayout ¶
ExtractTextWithLayout returns structured text lines sorted in visual (top-to-bottom, left-to-right) reading order. Each line contains its concatenated text and individual fragments with positions.
func (*Page) Forms ¶ added in v0.4.0
Forms returns the Form XObjects referenced by the page's resources — the reusable content groups already present (e.g. parsed from a loaded PDF or placed earlier). Each can be re-placed on any page of the same document with AddForm, or imported into another document with Document.ImportForm.
func (*Page) ImageInfos ¶
ImageInfos returns metadata for all images found on the page without decoding pixel data.
func (*Page) Label ¶
Label returns the formatted page label for this page as defined by the document's /PageLabels number tree (PDF spec §12.4.2).
Common label styles:
- /D — decimal integers: 1, 2, 3, …
- /r — lowercase roman: i, ii, iii, …
- /R — uppercase roman: I, II, III, …
- /a — lowercase alphabetic: a, b, …, z, aa, ab, …
- /A — uppercase alphabetic: A, B, …, Z, AA, AB, …
A /P prefix string is prepended when present (e.g. "A-1", "A-2").
If the document has no /PageLabels entry, the decimal page number is returned.
func (*Page) MediaBox ¶ added in v0.3.0
MediaBox returns the page's MediaBox as a Rectangle in PDF user space. If not set on the page itself, it is inherited from the page tree. Mirrors Aspose.PDF for .NET's Page.MediaBox.
func (*Page) Paragraphs ¶ added in v0.4.0
func (p *Page) Paragraphs() (PageMarkup, error)
Paragraphs returns the page's text grouped into columns (sections) and paragraphs. Mirrors Aspose.PDF for .NET's ParagraphAbsorber.
func (*Page) RenderBMP ¶ added in v0.3.0
func (p *Page) RenderBMP(w io.Writer, opts RenderOptions) error
RenderBMP renders the page and writes it as an uncompressed BMP.
func (*Page) RenderGIF ¶ added in v0.3.0
func (p *Page) RenderGIF(w io.Writer, opts RenderOptions) error
RenderGIF renders the page and writes it as GIF (256 colours, quantized).
func (*Page) RenderImage ¶ added in v0.3.0
func (p *Page) RenderImage(opts RenderOptions) (image.Image, error)
RenderImage rasterizes the page to an *image.RGBA at the requested DPI. The rendered region is the CropBox intersected with the MediaBox per ISO 32000-1 §7.7.3.3 (a stray CropBox larger than the page would otherwise shrink the content into a corner of an oversized canvas). Content the renderer does not yet support is skipped rather than erroring, so a page always produces an image.
func (*Page) RenderJPEG ¶ added in v0.3.0
RenderJPEG renders the page and writes it as JPEG. quality is 1..100; values outside that range use 90.
func (*Page) RenderPNG ¶ added in v0.3.0
func (p *Page) RenderPNG(w io.Writer, opts RenderOptions) error
RenderPNG renders the page and writes it as PNG.
func (*Page) RenderTIFF ¶ added in v0.3.0
func (p *Page) RenderTIFF(w io.Writer, opts RenderOptions) error
RenderTIFF renders the page and writes it as a single-page Deflate TIFF.
func (*Page) ReplaceText ¶ added in v0.4.0
func (p *Page) ReplaceText(old, replacement string, opts ...ReplaceOptions) (int, error)
ReplaceText replaces every occurrence of old with replacement on the page and returns the number of replacements made. The matched glyphs are removed and the replacement is drawn at the same baseline, size, and colour in a metric-compatible Standard-14 face chosen from the original's family and style (so any replacement text renders, even when the original used an embedded subset font that lacks the new glyphs). The line is not re-flowed: a much longer replacement may overrun following content. Matches are located within a single line, like SearchText. Mirrors the find-and-replace idiom of Aspose.PDF for .NET's TextFragmentAbsorber + TextFragment.Text.
Removing the old text reuses the SAME content-stream rewriter ApplyRedactions does (rewriteTextOperatorsInStream), so it shares that function's one hard limit: a match drawn with a font this pipeline cannot resolve (an undeclared font name, or a simple font with no usable /Encoding/ToUnicode) makes this call return an error instead of replacing it — rather than, as before, silently leaving the OLD text underneath the new replacement text it still drew on top (a real, if cosmetic, bug this change trades for a clear error; found during an independent review of pdf-go-oq9i, the ApplyRedactions fix this inherited). Also removes the dead, now-unreferenced ORIGINAL content stream from the document once at least one match was replaced (RemoveUnusedObjects, the same reason ApplyRedactions calls it — pdf-go-2qkq's class of leak otherwise applies here too, since old text containing whatever was just "replaced" would stay recoverable in the saved file) — so, like ApplyRedactions, call ReplaceText only after placing everything else you mean to keep.
func (*Page) Rotation ¶
func (p *Page) Rotation() RotationAngle
Rotation returns the effective rotation of the page in degrees (0, 90, 180, 270).
func (*Page) SaveSVG ¶ added in v0.7.0
func (p *Page) SaveSVG(path string, opts ...SVGSaveOptions) error
SaveSVG writes the page as a standalone SVG file.
func (*Page) SearchText ¶ added in v0.3.0
func (p *Page) SearchText(query string, opts ...SearchOptions) ([]TextMatch, error)
SearchText finds every occurrence of query on the page and returns the matches in visual reading order (top-to-bottom, left-to-right). Each match carries the matched text and a bounding rectangle in PDF user space.
By default the query is a case-sensitive literal string; pass a SearchOptions to enable case-insensitive and/or regular-expression matching. At most one SearchOptions is honored (the last, if several are passed).
This mirrors Aspose.PDF for .NET's TextFragmentAbsorber + page.Accept flow. Matches are located within a single text line: a query that would straddle a line break is not found. An empty query, or an invalid regular expression, returns an error.
Example ¶
Search for text on a page and get the bounding box of each match.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
_ = page.AddText("The quick brown fox jumps over the lazy dog.",
pdf.TextStyle{Size: 14}, pdf.Rectangle{LLX: 50, LLY: 700, URX: 545, URY: 780})
matches, err := page.SearchText("brown fox")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%d match: %q\n", len(matches), matches[0].Text)
}
Output: 1 match: "brown fox"
func (*Page) SetArtBox ¶ added in v0.3.0
SetArtBox sets the page's ArtBox (meaningful content extent).
func (*Page) SetBleedBox ¶ added in v0.3.0
SetBleedBox sets the page's BleedBox (production bleed region).
func (*Page) SetCropBox ¶ added in v0.3.0
SetCropBox sets the page's CropBox (the visible region). Mirrors Page.CropBox.
func (*Page) SetMediaBox ¶ added in v0.3.0
SetMediaBox sets the page's MediaBox (the full page rectangle) in PDF user space. The box is written directly on the page, overriding any inherited or referenced value. Mirrors Aspose.PDF for .NET's Page.MediaBox setter.
func (*Page) SetPageSize ¶ added in v0.3.0
SetPageSize resizes the page by setting its MediaBox to [0 0 width height] (points). Existing content is not scaled or moved — only the page rectangle changes. Mirrors Aspose.PDF for .NET's Page.SetPageSize.
func (*Page) SetTrimBox ¶ added in v0.3.0
SetTrimBox sets the page's TrimBox (intended finished dimensions).
func (*Page) Size ¶
Size returns the page dimensions from its MediaBox. If MediaBox is not set on the page itself, it is inherited from the page tree.
func (*Page) TagArtifact ¶ added in v0.4.0
TagArtifact brackets a block of page drawing as an /Artifact marked-content sequence, so it is treated as decoration and excluded from the logical structure tree. Use it for running headers/footers, page numbers, backgrounds and rules in a Tagged PDF — PDF/UA requires every content item to be either tagged as structure or marked as an artifact. Requires Document.TaggedContent.
func (*Page) TagContent ¶ added in v0.4.0
func (p *Page) TagContent(parent *StructElement, t StructType, draw func() error) (*StructElement, error)
TagContent draws a block of page content (everything the draw callback emits) inside a marked-content sequence and adds a corresponding leaf structure element of type t as a child of parent (nil = the document root). The returned element can carry alternate text (e.g. for a Figure). Returns an error if the document is not set up for tagging or the draw callback fails.
func (*Page) TrimBox ¶
TrimBox returns the trim box of the page as a Rectangle. Falls back to CropBox, then MediaBox if not set.
func (*Page) WriteSVG ¶ added in v0.7.0
func (p *Page) WriteSVG(w io.Writer, opts ...SVGSaveOptions) error
WriteSVG writes the page as one standalone SVG document to w.
Example ¶
Export a page as a standalone true-vector SVG file.
package main
import (
"fmt"
"log"
"strings"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
_ = page.DrawCircle(pdf.Point{X: 200, Y: 600}, 50,
pdf.ShapeStyle{FillColor: &pdf.Color{R: 1, G: 0.8, A: 1}})
var svg strings.Builder
if err := page.WriteSVG(&svg); err != nil {
log.Fatal(err)
}
fmt.Println("vector output:", strings.Contains(svg.String(), "<svg"))
}
Output: vector output: true
type PageFormat ¶
PageFormat describes a page size in points (1/72 inch).
func (PageFormat) Landscape ¶
func (f PageFormat) Landscape() PageFormat
Landscape returns the format with width and height swapped.
type PageLabelRange ¶ added in v0.3.0
type PageLabelRange struct {
StartPage int // 1-based page where this range begins
Style PageLabelStyle // numbering style
Prefix string // optional label prefix (e.g. "A-")
StartNum int // first number for this range; treated as 1 if ≤ 0
}
PageLabelRange describes a contiguous run of pages that share a numbering style. The first range must start at page 1; subsequent ranges inherit every preceding range's style/prefix until overridden. Mirrors the entries of a /PageLabels /Nums leaf per PDF spec §12.4.2.
type PageLabelStyle ¶ added in v0.3.0
type PageLabelStyle int
PageLabelStyle is the numbering style applied within a PageLabelRange. Mirrors the /S values from PDF spec §12.4.2 Table 159.
const ( PageLabelStyleNone PageLabelStyle = iota // no /S — only the prefix is rendered PageLabelDecimal // /D — 1, 2, 3, … PageLabelRomanLower // /r — i, ii, iii, … PageLabelRomanUpper // /R — I, II, III, … PageLabelAlphabeticLower // /a — a, b, …, z, aa, ab, … PageLabelAlphabeticUpper // /A — A, B, …, Z, AA, AB, … )
type PageMarkup ¶ added in v0.4.0
type PageMarkup struct {
PageNumber int
Sections []MarkupSection
}
PageMarkup is the structured text of one page.
type PageNumberStamp ¶ added in v0.4.0
type PageNumberStamp struct {
// Format is the template. "{0}" is replaced by the current page number and
// "{1}" by the total page count — e.g. "Page {0} of {1}". Empty = "{0}".
// Mirrors Aspose PageNumberStamp.Format (which uses "#").
Format string
// StartingNumber is the number shown on page 1 (default 1); page n shows
// StartingNumber-1+n. Mirrors Aspose PageNumberStamp.StartingNumber.
StartingNumber int
// TextStyle controls font, size, and colour.
TextStyle TextStyle
// contains filtered or unexported fields
}
PageNumberStamp stamps the page number (and optionally the total), formatted by Format. Mirrors Aspose.Pdf.PageNumberStamp. Construct with NewPageNumberStamp; typically placed as a footer (set VAlign = VAlignBottom).
func NewPageNumberStamp ¶ added in v0.4.0
func NewPageNumberStamp(format string, style TextStyle) *PageNumberStamp
NewPageNumberStamp creates a page-number stamp. Mirrors Aspose's PageNumberStamp(format, ...).
type PageRange ¶
type PageRange struct {
From, To int
}
PageRange specifies an inclusive range of pages (1-based).
type PasswordBoxField ¶ added in v0.4.0
type PasswordBoxField struct{ TextBoxField }
PasswordBoxField is a text field whose input is masked (Password flag). Its value is not stored in a saved file by conforming viewers.
func (*PasswordBoxField) Flatten ¶ added in v0.4.0
func (b *PasswordBoxField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*PasswordBoxField) IsReadOnly ¶ added in v0.4.0
func (b *PasswordBoxField) IsReadOnly() bool
func (*PasswordBoxField) IsRequired ¶ added in v0.4.0
func (b *PasswordBoxField) IsRequired() bool
func (*PasswordBoxField) PartialName ¶ added in v0.4.0
func (b *PasswordBoxField) PartialName() string
func (*PasswordBoxField) SetStyle ¶ added in v0.4.0
func (b *PasswordBoxField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*PasswordBoxField) Style ¶ added in v0.4.0
func (b *PasswordBoxField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is a sequence of MoveTo/LineTo/CurveTo/Close operations defining an arbitrary 2D path in PDF user space (origin at page bottom-left, Y up).
Construct via NewPath() and chain mutator methods, then pass to (*Page).DrawPath. Path is a builder type — it accumulates operations and holds no rendering state.
func (*Path) Arc ¶
Arc adds an arc to the path, approximated by cubic Bezier curves.
(cx, cy) is the center; r is the radius. startAngle and sweepAngle are in radians; sweepAngle may be negative (clockwise). The arc is subdivided into segments of ≤90°, each approximated by one cubic Bezier using k = (4/3) * tan(segmentAngle / 4) for the control-point magnitude.
If the path has no current point, MoveTo to the arc's start is implicit. After the call, the path's current point is the arc's endpoint.
No-op if r <= 0 or sweepAngle == 0.
func (*Path) Close ¶
Close closes the current subpath with a line back to the most recent MoveTo. PDF operator h.
func (*Path) CurveTo ¶
CurveTo adds a cubic Bezier curve from the current point to (x, y) with control points (c1x, c1y) and (c2x, c2y). PDF operator c.
func (*Path) LineTo ¶
LineTo adds a straight line segment from the current point to (x, y). If there is no current point, equivalent to MoveTo per PDF spec semantics.
func (*Path) QuadTo ¶
QuadTo adds a quadratic Bezier curve (one control point) from the current point to (x, y), automatically converted to the equivalent cubic per the standard quadratic-to-cubic formula:
C1 = P0 + (2/3) * (Q - P0) C2 = P3 + (2/3) * (Q - P3)
If there is no current point, treats (0, 0) as the start (matching PDF path semantics).
type PdfPageStamp ¶ added in v0.4.0
type PdfPageStamp struct {
// contains filtered or unexported fields
}
PdfPageStamp overlays (or underlays) a page from another PDF document as a stamp — the source page is imported once as a Form XObject and drawn into the stamp's Rect, scaled to fit while preserving aspect ratio, positioned by HAlign/VAlign, and honoring Opacity, RotateAngle and Background. Mirrors Aspose.PDF for .NET's PdfPageStamp. Construct with NewPdfPageStamp.
func NewPdfPageStamp ¶ added in v0.4.0
func NewPdfPageStamp(srcDoc *Document, srcPageNum int) (*PdfPageStamp, error)
NewPdfPageStamp creates a stamp that draws page srcPageNum (1-based) of srcDoc.
type Permissions ¶
type Permissions struct {
AllowPrint bool
AllowModify bool
AllowCopy bool
AllowAnnotations bool
AllowFormFill bool
AllowAccessibility bool
AllowAssembly bool
AllowPrintHighRes bool
}
Permissions controls what a viewer allows on an encrypted PDF. The zero value denies every operation. Permissions only take effect when the document is also encrypted (SetPassword); viewers enforce the bits — the library itself is not a DRM enforcer.
Per ISO 32000-1 §7.6.3.2 Table 22, bit meanings for R=3/R=4:
AllowPrint — bit 3 (low-resolution print) AllowModify — bit 4 (modify page contents) AllowCopy — bit 5 (copy text / extract graphics) AllowAnnotations — bit 6 (add/modify text annotations) AllowFormFill — bit 9 (fill in existing form fields) AllowAccessibility — bit 10 (extract text/graphics for accessibility) AllowAssembly — bit 11 (insert/rotate/delete pages) AllowPrintHighRes — bit 12 (print in high resolution)
type PngDevice ¶ added in v0.3.0
type PngDevice struct {
// contains filtered or unexported fields
}
PngDevice renders a page to PNG at a fixed resolution. Mirrors Aspose.PDF for .NET's PngDevice.
func NewPngDevice ¶ added in v0.3.0
func NewPngDevice(res Resolution) *PngDevice
NewPngDevice returns a PngDevice for the given resolution.
type Point ¶
type Point struct {
X, Y float64
}
Point is a single point in PDF user-space coordinates.
type PolygonAnnotation ¶ added in v0.4.0
type PolygonAnnotation struct {
// contains filtered or unexported fields
}
PolygonAnnotation draws a closed polygon through a list of vertices, with a stroked border and optional interior fill. Mirrors Aspose.PDF for .NET's PolygonAnnotation.
func NewPolygonAnnotation ¶ added in v0.4.0
func NewPolygonAnnotation(page *Page, vertices []Point) *PolygonAnnotation
NewPolygonAnnotation builds an unbound polygon annotation through the given vertices (PDF user space). Page must be non-nil. The /Rect is auto-computed from the vertices; the annotation is not added to the document until page.Annotations().Add(poly) succeeds.
func (*PolygonAnnotation) AnnotationType ¶ added in v0.4.0
func (a *PolygonAnnotation) AnnotationType() AnnotationType
func (*PolygonAnnotation) InteriorColor ¶ added in v0.4.0
func (a *PolygonAnnotation) InteriorColor() *Color
InteriorColor returns the /IC fill colour, or nil if absent. For a Polygon this fills the closed shape; for a PolyLine it fills any closed line endings (ClosedArrow/Square/Circle/Diamond).
func (*PolygonAnnotation) RegenerateAppearance ¶ added in v0.4.0
func (a *PolygonAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*PolygonAnnotation) SetBorderWidth ¶ added in v0.4.0
func (a *PolygonAnnotation) SetBorderWidth(w float64)
SetBorderWidth overrides drawingAnnotationBase.SetBorderWidth so /Rect (whose padding scales with BorderWidth) is recomputed before /AP/N regenerates — single-pass /BBox sync, matching Line/Ink.
func (*PolygonAnnotation) SetInteriorColor ¶ added in v0.4.0
func (a *PolygonAnnotation) SetInteriorColor(c *Color)
SetInteriorColor writes /IC as an RGB array; nil removes the entry.
func (*PolygonAnnotation) SetVertices ¶ added in v0.4.0
func (a *PolygonAnnotation) SetVertices(v []Point)
SetVertices writes /Vertices (a flat x y x y … array), recomputes /Rect, and regenerates /AP/N. The slice is copied; the caller may safely mutate it after this returns.
type PolylineAnnotation ¶ added in v0.4.0
type PolylineAnnotation struct {
// contains filtered or unexported fields
}
PolylineAnnotation draws an open polyline through a list of vertices, with a stroked border, optional line endings at the first and last vertex, and optional interior fill for closed endings. Mirrors Aspose.PDF for .NET's PolylineAnnotation.
func NewPolylineAnnotation ¶ added in v0.4.0
func NewPolylineAnnotation(page *Page, vertices []Point) *PolylineAnnotation
NewPolylineAnnotation builds an unbound polyline annotation through the given vertices (PDF user space). Page must be non-nil. The /Rect is auto-computed from the vertices.
func (*PolylineAnnotation) AnnotationType ¶ added in v0.4.0
func (a *PolylineAnnotation) AnnotationType() AnnotationType
func (*PolylineAnnotation) EndLineEnding ¶ added in v0.4.0
func (a *PolylineAnnotation) EndLineEnding() LineEndingStyle
EndLineEnding returns the style applied to the last vertex.
func (*PolylineAnnotation) InteriorColor ¶ added in v0.4.0
func (a *PolylineAnnotation) InteriorColor() *Color
InteriorColor returns the /IC fill colour, or nil if absent. For a Polygon this fills the closed shape; for a PolyLine it fills any closed line endings (ClosedArrow/Square/Circle/Diamond).
func (*PolylineAnnotation) RegenerateAppearance ¶ added in v0.4.0
func (a *PolylineAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*PolylineAnnotation) SetBorderWidth ¶ added in v0.4.0
func (a *PolylineAnnotation) SetBorderWidth(w float64)
SetBorderWidth overrides drawingAnnotationBase.SetBorderWidth so /Rect (whose padding scales with BorderWidth) is recomputed before /AP/N regenerates — single-pass /BBox sync, matching Line/Ink.
func (*PolylineAnnotation) SetEndLineEnding ¶ added in v0.4.0
func (a *PolylineAnnotation) SetEndLineEnding(s LineEndingStyle)
SetEndLineEnding sets the end-side (last vertex) line-ending style.
func (*PolylineAnnotation) SetInteriorColor ¶ added in v0.4.0
func (a *PolylineAnnotation) SetInteriorColor(c *Color)
SetInteriorColor writes /IC as an RGB array; nil removes the entry.
func (*PolylineAnnotation) SetStartLineEnding ¶ added in v0.4.0
func (a *PolylineAnnotation) SetStartLineEnding(s LineEndingStyle)
SetStartLineEnding sets the start-side (first vertex) line-ending style.
func (*PolylineAnnotation) SetVertices ¶ added in v0.4.0
func (a *PolylineAnnotation) SetVertices(v []Point)
SetVertices writes /Vertices (a flat x y x y … array), recomputes /Rect, and regenerates /AP/N. The slice is copied; the caller may safely mutate it after this returns.
func (*PolylineAnnotation) StartLineEnding ¶ added in v0.4.0
func (a *PolylineAnnotation) StartLineEnding() LineEndingStyle
StartLineEnding returns the style applied to the first vertex.
type QuadPoint ¶
type QuadPoint struct {
X1, Y1, X2, Y2, X3, Y3, X4, Y4 float64
}
QuadPoint is one quadrilateral within a markup annotation's /QuadPoints array. Per ISO 32000-1 §12.5.6.10 the eight floats name the corners in this order: (X1,Y1)=upper-left, (X2,Y2)=upper-right, (X3,Y3)=lower-left, (X4,Y4)=lower-right (in default user space, so "upper" means higher Y).
type RadialGradient ¶ added in v0.3.0
type RadialGradient struct {
CX, CY, R, FX, FY float64
Stops []GradientStop
}
RadialGradient interpolates colour from the focal point (FX, FY) out to the circle centred at (CX, CY) with radius R. NewRadialGradient sets the focal point to the centre (the common case); set FX/FY explicitly for an off-centre highlight.
func NewRadialGradient ¶ added in v0.3.0
func NewRadialGradient(cx, cy, r float64, stops ...GradientStop) RadialGradient
NewRadialGradient builds a radial gradient on the circle centred at (cx, cy) with radius r, focal point at the centre.
type RadioButtonField ¶
type RadioButtonField struct {
// contains filtered or unexported fields
}
RadioButtonField is a group of mutually exclusive options.
func (*RadioButtonField) Flatten ¶ added in v0.3.0
func (b *RadioButtonField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*RadioButtonField) IsReadOnly ¶
func (b *RadioButtonField) IsReadOnly() bool
func (*RadioButtonField) IsRequired ¶
func (b *RadioButtonField) IsRequired() bool
func (*RadioButtonField) Options ¶
func (f *RadioButtonField) Options() []*RadioButtonOptionField
Options returns one RadioButtonOptionField per widget in the group.
func (*RadioButtonField) PartialName ¶
func (b *RadioButtonField) PartialName() string
func (*RadioButtonField) SetReadOnly ¶
func (f *RadioButtonField) SetReadOnly(v bool)
func (*RadioButtonField) SetRequired ¶
func (f *RadioButtonField) SetRequired(v bool)
func (*RadioButtonField) SetStyle ¶ added in v0.3.0
func (b *RadioButtonField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*RadioButtonField) SetValue ¶
func (f *RadioButtonField) SetValue(s string) error
SetValue takes the export name of the option to select. Empty string clears the selection (writes /Off). Any other unknown value returns an error.
func (*RadioButtonField) Style ¶ added in v0.3.0
func (b *RadioButtonField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
func (*RadioButtonField) Value ¶
func (f *RadioButtonField) Value() string
type RadioButtonOptionField ¶
type RadioButtonOptionField struct {
// contains filtered or unexported fields
}
RadioButtonOptionField is one of the option widgets inside a RadioButtonField. Mirrors the C# nested type pattern.
func (*RadioButtonOptionField) Name ¶
func (o *RadioButtonOptionField) Name() string
Name returns the option's export value (its /AS state when selected, equivalently its non-/Off key in the widget's /AP/N dict).
func (*RadioButtonOptionField) Selected ¶
func (o *RadioButtonOptionField) Selected() bool
Selected reports whether this option is the currently selected one.
func (*RadioButtonOptionField) SetSelected ¶
func (o *RadioButtonOptionField) SetSelected(v bool)
SetSelected selects this option and clears all siblings (true), or clears the selection if this option is currently selected; siblings are unaffected.
type RadioItem ¶
RadioItem describes one widget inside a radio group. PageNum is 1-based; Export is the unique export value for this option (becomes the /AS state name when selected).
type Recipient ¶ added in v0.8.0
type Recipient struct {
// Certificate is the recipient's X.509 certificate (RSA public key).
Certificate *x509.Certificate
// Permissions limits what this recipient may do; nil grants everything.
Permissions *Permissions
}
Recipient is one certificate that may open a public-key-encrypted document, optionally with its own permission set.
type Rectangle ¶
type Rectangle struct {
LLX, LLY float64 // lower-left corner
URX, URY float64 // upper-right corner
}
Rectangle represents a PDF rectangle [llx, lly, urx, ury] in points (1/72 inch).
type RedactAnnotation ¶
type RedactAnnotation struct {
// contains filtered or unexported fields
}
RedactAnnotation marks regions for redaction. Mark mode (this type) renders a semi-transparent fill of /QuadPoints regions. The destructive content removal happens when (*Document).ApplyRedactions is called — this annotation is then removed and the underlying page content is irreversibly rewritten. Per ISO 32000-1 §12.5.6.20.
func NewRedactAnnotation ¶
func NewRedactAnnotation(page *Page, rect Rectangle) *RedactAnnotation
NewRedactAnnotation builds an unbound redact annotation. Page must be non-nil. By default, /QuadPoints is empty (rendering uses /Rect as a single quad). Callers typically call SetQuadPoints to specify multiple disjoint regions.
func (*RedactAnnotation) AnnotationType ¶
func (a *RedactAnnotation) AnnotationType() AnnotationType
func (*RedactAnnotation) BorderStyle ¶
func (d *RedactAnnotation) BorderStyle() BorderStyle
BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.
func (*RedactAnnotation) BorderWidth ¶
func (d *RedactAnnotation) BorderWidth() float64
BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.
func (*RedactAnnotation) DashPattern ¶
func (d *RedactAnnotation) DashPattern() []float64
DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.
func (*RedactAnnotation) InteriorColor ¶
func (a *RedactAnnotation) InteriorColor() *Color
InteriorColor returns the /IC fill color (used for both mark visual and post-apply overlay). Returns nil if absent.
func (*RedactAnnotation) OverlayText ¶
func (a *RedactAnnotation) OverlayText() string
OverlayText returns /OverlayText. Empty string if absent.
func (*RedactAnnotation) OverlayTextStyle ¶
func (a *RedactAnnotation) OverlayTextStyle() TextStyle
OverlayTextStyle returns the style reconstructed from /DA + /Q. Background is not relevant for redact overlay.
func (*RedactAnnotation) QuadPoints ¶
func (a *RedactAnnotation) QuadPoints() []QuadPoint
QuadPoints returns the regions to redact in page space. Returns nil if /QuadPoints is absent (Apply uses /Rect as the single region).
func (*RedactAnnotation) RegenerateAppearance ¶
func (a *RedactAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt.
func (*RedactAnnotation) RepeatOverlayText ¶
func (a *RedactAnnotation) RepeatOverlayText() bool
RepeatOverlayText returns /Repeat. False if absent.
func (*RedactAnnotation) SetBorderStyle ¶
func (d *RedactAnnotation) SetBorderStyle(s BorderStyle)
SetBorderStyle writes /BS/S using the PDF spec name codes.
func (*RedactAnnotation) SetBorderWidth ¶
func (d *RedactAnnotation) SetBorderWidth(w float64)
SetBorderWidth writes /BS/W and clears any legacy /Border array.
func (*RedactAnnotation) SetColor ¶
func (d *RedactAnnotation) SetColor(c *Color)
SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.
func (*RedactAnnotation) SetDashPattern ¶
func (d *RedactAnnotation) SetDashPattern(p []float64)
SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.
func (*RedactAnnotation) SetInteriorColor ¶
func (a *RedactAnnotation) SetInteriorColor(c *Color)
SetInteriorColor writes /IC. nil deletes the entry.
func (*RedactAnnotation) SetOverlayText ¶
func (a *RedactAnnotation) SetOverlayText(s string)
SetOverlayText writes /OverlayText. Empty string deletes the entry.
func (*RedactAnnotation) SetOverlayTextStyle ¶
func (a *RedactAnnotation) SetOverlayTextStyle(s TextStyle)
SetOverlayTextStyle writes /DA + /Q.
func (*RedactAnnotation) SetQuadPoints ¶
func (a *RedactAnnotation) SetQuadPoints(qp []QuadPoint)
SetQuadPoints writes /QuadPoints. nil/empty slice removes the entry (Apply will then use /Rect as single region).
func (*RedactAnnotation) SetRect ¶
func (d *RedactAnnotation) SetRect(r Rectangle)
SetRect overrides annotationBase.SetRect to regenerate /AP/N after the rectangle changes (the appearance stream's BBox is derived from /Rect).
func (*RedactAnnotation) SetRepeatOverlayText ¶
func (a *RedactAnnotation) SetRepeatOverlayText(repeat bool)
SetRepeatOverlayText writes /Repeat. False removes the entry.
type RenderOptions ¶ added in v0.3.0
type RenderOptions struct {
DPI float64 // dots per inch; 0 → DefaultDPI
Background *Color // page backdrop; nil → opaque white
}
RenderOptions controls page rasterization.
type RepairReport ¶ added in v0.10.0
type RepairReport struct {
// XRefReconstructed is set when the cross-reference table was rebuilt by
// scanning the file for "N G obj" headers, because the one in the file
// was missing, unparseable, or did not lead to a usable catalog.
XRefReconstructed bool
// ObjectsRecovered is how many objects that scan found. Zero unless
// XRefReconstructed is set.
ObjectsRecovered int
// TrailerRecovered is set when the trailer had to be synthesised from a
// /Type /Catalog object because the file's own trailer was missing or
// carried no /Root.
TrailerRecovered bool
}
RepairReport describes what had to be reconstructed to open the document. The zero value means the file parsed as written.
Scope: this reports structural recovery, decided while the file is being opened. Per-stream tolerance — a wrong /Length resolved by scanning for "endstream", a Flate stream with a bad checksum whose inflated bytes are kept — happens deep in the parser without a document in reach and is not counted here.
type ReplaceOptions ¶ added in v0.4.0
type ReplaceOptions struct {
// CaseInsensitive folds case when matching.
CaseInsensitive bool
// Regex treats the search string as an RE2 regular expression.
Regex bool
}
ReplaceOptions tunes how ReplaceText matches the search text. The zero value matches the literal string, case-sensitively. Mirrors the matching half of Aspose.PDF for .NET's TextReplaceOptions / TextSearchOptions.
type ResetFormAction ¶
type ResetFormAction struct {
// contains filtered or unexported fields
}
ResetFormAction resets named form fields to their /DV defaults.
func NewResetFormAction ¶
func NewResetFormAction(fields []string) *ResetFormAction
NewResetFormAction builds a /ResetForm action targeting the given field names. Empty fields means "reset all fields" per spec. The fields slice is copied; the caller may safely mutate it after this returns.
func (*ResetFormAction) ActionType ¶
func (a *ResetFormAction) ActionType() ActionType
func (*ResetFormAction) FieldNames ¶
func (a *ResetFormAction) FieldNames() []string
FieldNames returns a copy of the field-name list. The returned slice is owned by the caller; mutating it does not affect the action.
func (*ResetFormAction) SetFieldNames ¶
func (a *ResetFormAction) SetFieldNames(f []string)
SetFieldNames replaces the field-name list. The slice is copied; the caller may safely mutate f after this returns.
type Resolution ¶ added in v0.3.0
type Resolution struct{ DPI float64 }
Resolution is a rendering resolution in DPI. Mirrors Aspose.PDF for .NET's Aspose.Pdf.Devices.Resolution.
func NewResolution ¶ added in v0.3.0
func NewResolution(dpi float64) Resolution
NewResolution returns a Resolution of the given DPI.
type RevocationCheck ¶ added in v0.10.0
type RevocationCheck int
RevocationCheck selects how far verification goes in establishing whether a signing certificate was revoked.
const ( // RevocationNone performs no check. The zero value. RevocationNone RevocationCheck = iota // RevocationOffline uses only revocation material the document carries. RevocationOffline // RevocationOnline additionally fetches what the document lacks, from the // OCSP responder and CRL distribution points named in the certificate. RevocationOnline )
type RevocationFetcher ¶ added in v0.10.0
type RevocationFetcher interface {
// FetchOCSP posts a DER OCSPRequest to url and returns the DER response.
FetchOCSP(ctx context.Context, url string, req []byte) ([]byte, error)
// FetchCRL retrieves the DER CRL at url.
FetchCRL(ctx context.Context, url string) ([]byte, error)
}
RevocationFetcher retrieves revocation material. Implement it to route through a proxy, serve from a cache, or refuse the network entirely.
func DefaultRevocationFetcher ¶ added in v0.10.0
func DefaultRevocationFetcher(timeout time.Duration) RevocationFetcher
DefaultRevocationFetcher returns the built-in HTTP fetcher, the one used when ValidationOptions.Fetcher is nil. Exported so a caller can wrap it — to add a cache, or to log what is fetched — rather than reimplement it. timeout bounds each request; zero means 10 seconds.
type RevocationSource ¶ added in v0.10.0
type RevocationSource int
RevocationSource records where an answer came from.
const ( // RevocationFromDocument — material embedded in the PDF. RevocationFromDocument RevocationSource = iota // RevocationFromOCSP — a responder answered. RevocationFromOCSP // RevocationFromCRL — a revocation list was consulted. RevocationFromCRL )
func (RevocationSource) String ¶ added in v0.10.0
func (s RevocationSource) String() string
String names the source, for messages and test failures.
type RevocationState ¶ added in v0.10.0
type RevocationState int
RevocationState is what a responder or a CRL says about a certificate.
const ( // RevocationUnknown means no usable answer was obtained — no responder, // an unparseable or stale response, a signature that did not check out. RevocationUnknown RevocationState = iota // RevocationGood means the issuer states the certificate is not revoked. RevocationGood // RevocationRevoked means the issuer states it is revoked. RevocationRevoked )
func (RevocationState) String ¶ added in v0.10.0
func (s RevocationState) String() string
String names the state, for messages and test failures.
type RevocationStatus ¶ added in v0.10.0
type RevocationStatus struct {
Status RevocationState
Source RevocationSource
RevokedAt time.Time // set only when Status is RevocationRevoked
Reason int // CRL reason code (RFC 5280 §5.3.1); 0 when unspecified
ProducedAt time.Time // when the answer was produced
Err error // why the status is unknown
}
RevocationStatus is what the issuer says about a signing certificate.
type RichTextBoxField ¶ added in v0.4.0
type RichTextBoxField struct{ TextBoxField }
RichTextBoxField is a text field that carries a rich-text value (RichText flag + /RV) in addition to its plain /V.
func (*RichTextBoxField) Flatten ¶ added in v0.4.0
func (b *RichTextBoxField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*RichTextBoxField) IsReadOnly ¶ added in v0.4.0
func (b *RichTextBoxField) IsReadOnly() bool
func (*RichTextBoxField) IsRequired ¶ added in v0.4.0
func (b *RichTextBoxField) IsRequired() bool
func (*RichTextBoxField) PartialName ¶ added in v0.4.0
func (b *RichTextBoxField) PartialName() string
func (*RichTextBoxField) RichValue ¶ added in v0.4.0
func (r *RichTextBoxField) RichValue() string
RichValue returns the field's /RV rich-text value.
func (*RichTextBoxField) SetRichValue ¶ added in v0.4.0
func (r *RichTextBoxField) SetRichValue(rv, plain string) error
SetRichValue sets the rich-text value (/RV, XHTML) and mirrors a plain-text fallback into /V.
func (*RichTextBoxField) SetStyle ¶ added in v0.4.0
func (b *RichTextBoxField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*RichTextBoxField) Style ¶ added in v0.4.0
func (b *RichTextBoxField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
type RotationAngle ¶
type RotationAngle int
RotationAngle represents a valid PDF page rotation in clockwise degrees.
const ( Rotate0 RotationAngle = 0 Rotate90 RotationAngle = 90 Rotate180 RotationAngle = 180 Rotate270 RotationAngle = 270 )
type Row ¶
type Row struct {
// contains filtered or unexported fields
}
Row is a single row within a Table.
func (*Row) Background ¶
Background returns the row-level background color, or nil if unset.
func (*Row) Border ¶
func (r *Row) Border() *BorderInfo
Border returns the row-level border override, or nil if unset.
func (*Row) Margin ¶
func (r *Row) Margin() *MarginInfo
Margin returns the row-level margin override, or nil if unset.
func (*Row) SetBackground ¶
SetBackground sets a row-level background color. Cells in the row inherit this background unless the cell itself calls SetBackground.
func (*Row) SetBorder ¶
func (r *Row) SetBorder(b BorderInfo) *Row
SetBorder sets a row-level default border. Cells inherit unless overridden.
func (*Row) SetHeight ¶
SetHeight sets the row's drawn height in points. Pass 0 to use auto-fit (the renderer measures cell contents to compute a row height that fits).
func (*Row) SetMargin ¶
func (r *Row) SetMargin(m MarginInfo) *Row
SetMargin sets a row-level default cell padding. Cells inherit unless overridden.
func (*Row) SetTextStyle ¶
SetTextStyle sets a row-level default text style. Cells in the row inherit this style (overlaid on table.DefaultCellStyle) unless overridden per-cell.
type SVG ¶ added in v0.2.0
type SVG struct {
// contains filtered or unexported fields
}
SVG is the pre-parsed SVG document.
type SVGFontResolver ¶ added in v0.2.0
SVGFontResolver maps an SVG font-family + style to a pdf.Font. Return nil to fall back to the library's built-in heuristic (Standard 14 mapping based on family keyword).
type SVGSaveOptions ¶ added in v0.7.0
type SVGSaveOptions struct {
// DPI sets the coordinate scale (the viewBox is the page at this
// resolution) and the resolution of raster patches. 0 → 150. The vector
// content itself is resolution-independent.
DPI float64
// Pages is a 1-based subset for Document.SaveSVG; nil = all pages.
Pages []int
// ResourceWriter externalizes binary parts (images, raster patches)
// instead of embedding them as data: URLs: it receives a unique name +
// bytes and returns the URL to reference from the SVG.
ResourceWriter func(name string, data []byte) (url string, err error)
}
SVGSaveOptions configures SaveSVG / WriteSVG. The zero value exports all pages at 150 DPI with images embedded as data: URLs (self-contained files).
type SearchOptions ¶ added in v0.3.0
type SearchOptions struct {
// CaseInsensitive folds case when matching (literal and regex alike).
CaseInsensitive bool
// Regex treats the query as an RE2 regular expression instead of a literal
// string. Invalid patterns are reported as an error by SearchText.
Regex bool
// Rectangle, when non-nil, limits results to matches whose bounding box
// intersects this region (PDF user space, applied to every page). nil
// searches the whole page. Mirrors Aspose.PDF for .NET's
// TextSearchOptions.Rectangle.
Rectangle *Rectangle
// SearchInAnnotations also searches the text content (/Contents) of the
// page's annotations — sticky notes, free text, markup, etc. Each match's
// Rect is the annotation's rectangle. Mirrors Aspose.PDF for .NET's
// TextSearchOptions.SearchInAnnotations.
SearchInAnnotations bool
}
SearchOptions tunes how SearchText interprets the query. The zero value is a case-sensitive literal search, matching the default of Aspose.PDF for .NET's TextFragmentAbsorber.
type ShapeStyle ¶
type ShapeStyle struct {
LineStyle
FillColor *Color // nil = no fill
FillPattern string // optional PDF pattern resource name (e.g. "/P0"); overrides FillColor when set
FillGradient Gradient // optional linear/radial gradient fill; overrides FillColor
FillTiling *TilingPattern // optional repeating tiling-pattern fill; overrides FillColor
}
ShapeStyle combines a stroke (LineStyle) with an optional fill color.
FillColor nil → no fill (stroke-only). Width ≤ 0 in the embedded LineStyle → no stroke (fill-only). If both are unset, the draw call is a no-op.
FillPattern, when non-empty, overrides FillColor: the fill uses a PDF /Pattern colorspace with the named pattern resource (e.g. "/P0"). Used internally by the SVG renderer to wire gradient fills.
FillGradient, when non-nil, fills the shape with a LinearGradient or RadialGradient. It takes precedence over FillColor; the draw call registers the necessary PDF shading pattern on the page automatically.
FillTiling, when non-nil, fills the shape with a repeating TilingPattern (a user-drawn cell tiled across the shape). It takes precedence over FillColor; the draw call registers the PatternType 1 pattern automatically. Precedence on fill: FillTiling → FillGradient → FillPattern → FillColor.
Mirrors Aspose.PDF for .NET's GraphInfo (stroke + fill).
type SideBySideComparisonOptions ¶ added in v0.10.0
type SideBySideComparisonOptions struct {
ComparisonOptions
// InsertColor / DeleteColor style the markup on each pane, same meaning
// as DiffMarkupOptions. Defaults: green insertions, red deletions.
InsertColor *Color
DeleteColor *Color
}
SideBySideComparisonOptions configures a side-by-side spread. Embeds ComparisonOptions — phase 1's word-diff options (ExtractionArea, ExcludeAreas1/2, ExcludeTables, EditOperationsOrder, IgnoreCase) apply here too, since the spread is built on the same word-diff engine. Mirrors Aspose.PDF for .NET's SideBySideComparisonOptions, minus ComparisonMode (this library's tokenizer already splits words on whitespace, so behaviour already matches Aspose's IgnoreSpaces mode; the Normal/ParseSpaces whitespace-sensitivity distinction is out of scope for v1) and AdditionalChangeMarks (margin change bars — out of scope for v1).
type SideBySideDocsComparisonResult ¶ added in v0.10.0
type SideBySideDocsComparisonResult struct {
*ComparisonResult
}
SideBySideDocsComparisonResult reports a document-level side-by-side comparison. Mirrors Aspose.PDF for .NET's SideBySideDocsComparisonResult; embeds *ComparisonResult, so HasChanges/Operations/PageOperations/ Statistics all apply directly to the spread's underlying comparison.
func SideBySideCompareDocuments ¶ added in v0.10.0
func SideBySideCompareDocuments(doc1, doc2 *Document, outputPath string, opts ...SideBySideComparisonOptions) (*SideBySideDocsComparisonResult, error)
SideBySideCompareDocuments lays every page pair of doc1 and doc2 side by side — paired by index like CompareDocumentsPageByPage, so the longer document's tail pages get an empty pane on the missing side — one output page per pair, and saves the spread as a new PDF at outputPath. Mirrors Aspose.PDF for .NET's SideBySidePdfComparer.Compare(Document, Document, string, SideBySideComparisonOptions).
func WriteSideBySideDocuments ¶ added in v0.10.0
func WriteSideBySideDocuments(doc1, doc2 *Document, w io.Writer, opts ...SideBySideComparisonOptions) (*SideBySideDocsComparisonResult, error)
WriteSideBySideDocuments is the io.Writer variant of SideBySideCompareDocuments.
type SideBySidePagesComparisonResult ¶ added in v0.10.0
type SideBySidePagesComparisonResult struct {
// contains filtered or unexported fields
}
SideBySidePagesComparisonResult reports a page-level side-by-side comparison. Mirrors Aspose.PDF for .NET's SideBySidePagesComparisonResult.
func SideBySideComparePages ¶ added in v0.10.0
func SideBySideComparePages(page1, page2 *Page, outputPath string, opts ...SideBySideComparisonOptions) (*SideBySidePagesComparisonResult, error)
SideBySideComparePages lays page1 and page2 side by side on one output page — page1 (deletions struck through) on the left, page2 (insertions highlighted) on the right — and saves it as a new PDF at outputPath. Mirrors Aspose.PDF for .NET's SideBySidePdfComparer.Compare(Page, Page, string, SideBySideComparisonOptions).
func WriteSideBySidePages ¶ added in v0.10.0
func WriteSideBySidePages(page1, page2 *Page, w io.Writer, opts ...SideBySideComparisonOptions) (*SideBySidePagesComparisonResult, error)
WriteSideBySidePages is the io.Writer variant of SideBySideComparePages.
func (*SideBySidePagesComparisonResult) HasChanges ¶ added in v0.10.0
func (r *SideBySidePagesComparisonResult) HasChanges() bool
HasChanges reports whether the two pages differ.
func (*SideBySidePagesComparisonResult) Operations ¶ added in v0.10.0
func (r *SideBySidePagesComparisonResult) Operations() []DiffOperation
Operations returns the underlying word-level differences (the same model ComparePages returns).
type SignOptions ¶ added in v0.4.0
type SignOptions struct {
Certificate *x509.Certificate
PrivateKey crypto.Signer
Chain []*x509.Certificate // optional intermediates, embedded alongside the signer cert
Reason string // optional /Reason
Location string // optional /Location
ContactInfo string // optional /ContactInfo
Name string // optional /Name (signer name shown by viewers)
SigningTime time.Time // zero → time of signing
// Visible draws the signature on the page as a widget in Rect with a
// generated appearance (mirrors Aspose.PDF for .NET's
// PdfFileSignature.Sign(..., visible, rect, ...)). The zero value keeps
// the signature invisible.
Visible bool
// Rect is the widget rectangle in PDF user space (required when Visible).
Rect Rectangle
// Page is the 1-based page for the visible widget; 0 means page 1.
Page int
// Appearance customizes the visible block's text and style (mirrors
// Aspose.PDF for .NET's SignatureCustomAppearance). nil = a sensible
// default (signer name + date, plus reason/location when set).
Appearance *SignatureAppearance
// SignHash signs a digest instead of holding the key: the alternative to
// PrivateKey for a hardware module or a remote signing service that only
// ever sees the hash. It is handed the digest and the hash that produced
// it, and returns the raw signature — PKCS#1 v1.5 for an RSA
// certificate, ASN.1 ECDSA for an elliptic-curve one, matching what
// crypto.Signer would have produced. Exactly one of PrivateKey and
// SignHash must be set; Certificate is required either way, since the
// SignerInfo is built from it. Mirrors the intent of Aspose.PDF for
// .NET's CustomSignHash.
SignHash func(digest []byte, hash crypto.Hash) ([]byte, error)
// Digest selects the hash used for the message digest and the signature
// itself. The zero value is SHA-256. Mirrors Aspose.PDF for .NET's
// DigestHashAlgorithm.
Digest DigestAlgorithm
// PAdES produces an ETSI.CAdES.detached (PAdES baseline) signature: the
// CMS carries the ESS signing-certificate-v2 attribute and /SubFilter is
// /ETSI.CAdES.detached. The zero value produces a classic
// /adbe.pkcs7.detached signature.
PAdES bool
// Certify makes this a certification (author / DocMDP) signature that
// records which later changes are permitted without invalidating it.
// The zero value (NotCertified) is an ordinary approval signature.
// Mirrors Aspose.PDF for .NET's PdfFileSignature.Certify +
// DocMDPAccessPermissions.
Certify CertifyPermission
// TimestampURL, when set, fetches an RFC 3161 trusted timestamp from that
// Time-Stamp Authority over the signature and embeds it, anchoring the
// signing time to a trusted clock. Requires network access at sign time.
TimestampURL string
// Incremental appends the signature as a new revision instead of
// rewriting the file, preserving the original bytes verbatim. This is
// REQUIRED to add a second signature without invalidating earlier ones,
// and is auto-enabled when the document already contains a signature.
// Requires a document opened from an existing PDF (Open/OpenStream).
Incremental bool
// LTV appends a further revision carrying the long-term validation
// material (/DSS) once the signature is written, so the signature can
// still be verified after the certificate expires. It runs
// AddValidationInfo with RevocationOnline, so it needs network access at
// sign time; without a reachable responder only the certificates are
// embedded. Mirrors the intent of Aspose.PDF for .NET's LTV support.
LTV bool
}
SignOptions configures a digital signature. Certificate and PrivateKey are required; the key is any crypto.Signer (RSA or ECDSA), so callers load it however they like (PEM via the standard library, an HSM, a freshly generated test key, …) — no certificate file is needed in the repository.
type SignatureAppearance ¶ added in v0.4.0
type SignatureAppearance struct {
ShowName bool // "Digitally signed by <signer>"
ShowDate bool // "Date: <signing time>"
ShowReason bool // "Reason: <reason>" (only if a reason is set)
ShowLocation bool // "Location: <location>" (only if a location is set)
Font Font // text font; nil = Helvetica
FontSize float64 // text size in points; 0 = auto-fit to the rectangle
Color *Color // text color; nil = dark blue
}
SignatureAppearance controls the visible signature block's content and styling. Mirrors the intent of Aspose.PDF for .NET's SignatureCustomAppearance. The zero value (with the Show… flags false) is only used when an explicit *SignatureAppearance is supplied; passing nil to SignOptions.Appearance yields the full default block.
type SignatureVerification ¶ added in v0.4.0
type SignatureVerification struct {
FieldName string // the /T of the signature field
SignerName string // /Name from the signature dictionary, if present
Reason string // /Reason
Location string // /Location
SigningTime time.Time // parsed from /M (zero if absent/unparseable)
Valid bool // signature cryptographically valid AND content intact
IntegrityOK bool // the /ByteRange bytes match the signature digest
CoversWholeDocument bool // the signature covers the entire file
Certificate *x509.Certificate // signer certificate (nil on parse failure)
// Chain holds the other certificates the signer embedded — the
// intermediates a caller needs to build a path to a trust anchor. The
// signer certificate itself is not repeated here.
Chain []*x509.Certificate
// Revocation is what the issuer says about the signing certificate. It is
// nil unless ValidationOptions asked for a check. A revoked certificate
// does not make Valid false: Valid stays cryptographic, and what to do
// about revocation is the caller's policy.
Revocation *RevocationStatus
// LTVEnabled reports that the document carries everything needed to verify
// this signature offline. Mirrors Aspose.PDF for .NET's IsLtvEnabled.
LTVEnabled bool
Err error // non-nil reason when Valid is false
}
SignatureVerification is the result of verifying one digital signature.
type SquareAnnotation ¶
type SquareAnnotation struct {
// contains filtered or unexported fields
}
SquareAnnotation draws a rectangular annotation with stroked border and optional interior fill. Renders natively from /AP/N — Solid, Dashed, Beveled, Inset, and Underline border styles supported.
func NewSquareAnnotation ¶
func NewSquareAnnotation(page *Page, rect Rectangle) *SquareAnnotation
NewSquareAnnotation builds an unbound square annotation. Page must be non-nil. The annotation is not added to the document until page.Annotations().Add(square) succeeds.
func (*SquareAnnotation) AnnotationType ¶
func (a *SquareAnnotation) AnnotationType() AnnotationType
func (*SquareAnnotation) BorderStyle ¶
func (d *SquareAnnotation) BorderStyle() BorderStyle
BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.
func (*SquareAnnotation) BorderWidth ¶
func (d *SquareAnnotation) BorderWidth() float64
BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.
func (*SquareAnnotation) DashPattern ¶
func (d *SquareAnnotation) DashPattern() []float64
DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.
func (*SquareAnnotation) InteriorColor ¶
func (a *SquareAnnotation) InteriorColor() *Color
InteriorColor returns the /IC fill color, or nil if absent.
func (*SquareAnnotation) RegenerateAppearance ¶
func (a *SquareAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties. Useful when the underlying dict was mutated directly (bypassing setters).
func (*SquareAnnotation) SetBorderStyle ¶
func (d *SquareAnnotation) SetBorderStyle(s BorderStyle)
SetBorderStyle writes /BS/S using the PDF spec name codes.
func (*SquareAnnotation) SetBorderWidth ¶
func (d *SquareAnnotation) SetBorderWidth(w float64)
SetBorderWidth writes /BS/W and clears any legacy /Border array.
func (*SquareAnnotation) SetColor ¶
func (d *SquareAnnotation) SetColor(c *Color)
SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.
func (*SquareAnnotation) SetDashPattern ¶
func (d *SquareAnnotation) SetDashPattern(p []float64)
SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.
func (*SquareAnnotation) SetInteriorColor ¶
func (a *SquareAnnotation) SetInteriorColor(c *Color)
SetInteriorColor writes /IC as an RGB array; nil removes the entry.
type SquigglyAnnotation ¶
type SquigglyAnnotation struct {
// contains filtered or unexported fields
}
SquigglyAnnotation draws a wavy underline under text (typically used for spell-check style hints).
func NewSquigglyAnnotation ¶
func NewSquigglyAnnotation(page *Page, rect Rectangle) *SquigglyAnnotation
NewSquigglyAnnotation builds an unbound squiggly-underline annotation.
func (*SquigglyAnnotation) AnnotationType ¶
func (a *SquigglyAnnotation) AnnotationType() AnnotationType
func (*SquigglyAnnotation) QuadPoints ¶
func (m *SquigglyAnnotation) QuadPoints() []QuadPoint
QuadPoints returns the array of quads describing the marked region. Returns nil if /QuadPoints is absent or its array length is not a multiple of 8 (malformed).
func (*SquigglyAnnotation) RegenerateAppearance ¶ added in v0.9.0
func (a *SquigglyAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*SquigglyAnnotation) SetColor ¶
func (m *SquigglyAnnotation) SetColor(c *Color)
SetColor writes /C and redraws the appearance in the new colour.
func (*SquigglyAnnotation) SetQuadPoints ¶
func (m *SquigglyAnnotation) SetQuadPoints(qp []QuadPoint)
SetQuadPoints writes /QuadPoints. nil or empty slice removes the entry.
type Stamp ¶ added in v0.4.0
type Stamp interface {
// contains filtered or unexported methods
}
Stamp is content overlaid on (or behind) a page: a TextStamp, an ImageStamp, or a PageNumberStamp. Apply it with (*Page).AddStamp or (*Document).AddStamp. Mirrors Aspose.PDF for .NET's Aspose.Pdf.Stamp class hierarchy.
Every stamp shares the placement and appearance fields of stampBase (embedded): a placement Rect (zero value = the whole page), HAlign/VAlign within that Rect, Opacity, RotateAngle, and Background (draw behind page content). Concrete types add their own content.
type StampAnnotation ¶
type StampAnnotation struct {
// contains filtered or unexported fields
}
StampAnnotation is a rubber-stamp annotation. Renders one of 14 predefined visuals (Approved, Confidential, Draft, etc.) or a custom image. Per ISO 32000-1 §12.5.6.13.
func NewStampAnnotation ¶
func NewStampAnnotation(page *Page, rect Rectangle, name StampName) *StampAnnotation
NewStampAnnotation builds an unbound stamp annotation. Page must be non-nil. /Name defaults to the supplied name (use StampNameDraft if uncertain).
func (*StampAnnotation) AnnotationType ¶
func (a *StampAnnotation) AnnotationType() AnnotationType
func (*StampAnnotation) BorderStyle ¶
func (d *StampAnnotation) BorderStyle() BorderStyle
BorderStyle returns the /BS/S style. Defaults to BorderSolid if absent.
func (*StampAnnotation) BorderWidth ¶
func (d *StampAnnotation) BorderWidth() float64
BorderWidth returns the stroke line width. Reads /BS/W (preferred) or /Border[2] (legacy fallback). Defaults to 1 if neither is present.
func (*StampAnnotation) ClearCustomImage ¶
func (a *StampAnnotation) ClearCustomImage()
ClearCustomImage reverts /AP/N to the predefined-name template visual. The previously-attached image XObject becomes orphan and can be reclaimed via doc.RemoveUnusedObjects().
func (*StampAnnotation) DashPattern ¶
func (d *StampAnnotation) DashPattern() []float64
DashPattern returns a defensive copy of the dash array. Reads /BS/D (preferred) or falls back to the legacy /Border[3] entry per ISO 32000-1 §12.5.4. Returns nil if neither is present.
func (*StampAnnotation) HasCustomImage ¶
func (a *StampAnnotation) HasCustomImage() bool
HasCustomImage returns true if SetCustomImage / SetCustomImageFromStream has been called and not subsequently cleared. Stub for now — full custom-image support in Task 8.
func (*StampAnnotation) Name ¶
func (a *StampAnnotation) Name() StampName
Name returns the StampName decoded from /Name. Returns StampNameUnknown for non-spec custom names.
func (*StampAnnotation) RawName ¶
func (a *StampAnnotation) RawName() string
RawName returns the /Name entry as a raw string ("/Approved", custom).
func (*StampAnnotation) RegenerateAppearance ¶
func (a *StampAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current state.
func (*StampAnnotation) SetBorderStyle ¶
func (d *StampAnnotation) SetBorderStyle(s BorderStyle)
SetBorderStyle writes /BS/S using the PDF spec name codes.
func (*StampAnnotation) SetBorderWidth ¶
func (d *StampAnnotation) SetBorderWidth(w float64)
SetBorderWidth writes /BS/W and clears any legacy /Border array.
func (*StampAnnotation) SetColor ¶
func (d *StampAnnotation) SetColor(c *Color)
SetColor overrides annotationBase.SetColor to regenerate /AP/N after the stroke color changes.
func (*StampAnnotation) SetCustomImage ¶
func (a *StampAnnotation) SetCustomImage(path string) error
SetCustomImage embeds the image at path as the stamp's /AP/N visual, overriding the predefined-name template. Format auto-detected from magic bytes (JPEG, PNG).
func (*StampAnnotation) SetCustomImageFromStream ¶
func (a *StampAnnotation) SetCustomImageFromStream(r io.Reader) error
SetCustomImageFromStream is the io.Reader variant of SetCustomImage.
func (*StampAnnotation) SetDashPattern ¶
func (d *StampAnnotation) SetDashPattern(p []float64)
SetDashPattern writes /BS/D. The slice is copied; the caller may safely mutate p after this returns.
func (*StampAnnotation) SetName ¶
func (a *StampAnnotation) SetName(n StampName)
SetName writes the /Name entry from a typed StampName.
func (*StampAnnotation) SetRawName ¶
func (a *StampAnnotation) SetRawName(s string)
SetRawName writes the /Name entry from a raw string. Used for non-spec custom names. Calling SetRawName with a value not matching any spec name will cause Name() to return StampNameUnknown.
type StampName ¶
type StampName int
StampName names per ISO 32000-1 §12.5.6.13 Table 184. Used in /Subtype /Stamp annotations' /Name entry. Unknown handles non-spec custom names (round-tripped via RawName).
const ( StampNameUnknown StampName = iota StampNameApproved StampNameAsIs StampNameConfidential StampNameDepartmental StampNameDraft // PDF default StampNameExperimental StampNameExpired StampNameFinal StampNameForComment StampNameForPublicRelease StampNameNotApproved StampNameNotForPublicRelease StampNameSold StampNameTopSecret )
type StrikeOutAnnotation ¶
type StrikeOutAnnotation struct {
// contains filtered or unexported fields
}
StrikeOutAnnotation draws a horizontal line through text.
func NewStrikeOutAnnotation ¶
func NewStrikeOutAnnotation(page *Page, rect Rectangle) *StrikeOutAnnotation
NewStrikeOutAnnotation builds an unbound strike-out annotation.
func (*StrikeOutAnnotation) AnnotationType ¶
func (a *StrikeOutAnnotation) AnnotationType() AnnotationType
func (*StrikeOutAnnotation) QuadPoints ¶
func (m *StrikeOutAnnotation) QuadPoints() []QuadPoint
QuadPoints returns the array of quads describing the marked region. Returns nil if /QuadPoints is absent or its array length is not a multiple of 8 (malformed).
func (*StrikeOutAnnotation) RegenerateAppearance ¶ added in v0.9.0
func (a *StrikeOutAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*StrikeOutAnnotation) SetColor ¶
func (m *StrikeOutAnnotation) SetColor(c *Color)
SetColor writes /C and redraws the appearance in the new colour.
func (*StrikeOutAnnotation) SetQuadPoints ¶
func (m *StrikeOutAnnotation) SetQuadPoints(qp []QuadPoint)
SetQuadPoints writes /QuadPoints. nil or empty slice removes the entry.
type StringDiffOutputGenerator ¶ added in v0.10.0
type StringDiffOutputGenerator interface {
// GenerateOutput renders a single, unlabeled list of operations — the
// shape ComparePages returns.
GenerateOutput(ops []DiffOperation) (string, error)
// GenerateOutputPages renders one section per page — the shape
// (*ComparisonResult).Pages returns.
GenerateOutputPages(pages [][]DiffOperation) (string, error)
}
StringDiffOutputGenerator produces comparison output as a string. Mirrors Aspose.PDF for .NET's IStringOutputGenerator.
type StructElement ¶ added in v0.4.0
type StructElement struct {
// contains filtered or unexported fields
}
StructElement is a node in the logical structure tree.
func (*StructElement) AddChild ¶ added in v0.4.0
func (e *StructElement) AddChild(t StructType) *StructElement
AddChild creates a grouping structure element of type t as a child of e and returns it. Use it for containers (Sect, Table, TR, TD, L, LI, …) that hold other elements rather than wrapping content directly.
func (*StructElement) AddObjectReference ¶ added in v0.10.0
func (e *StructElement) AddObjectReference(annot Annotation) error
AddObjectReference ties e directly to annot via an Object Reference (/OBJR, ISO 32000-1 §14.7.4.4) rather than marked content — the mechanism a /Link structure element uses to point at its LinkAnnotation, so assistive technology can associate the two (also valid for any other annotation type, e.g. bringing a Widget into reading order). annot must already be attached to a page (via (*AnnotationCollection).Add) before calling this — /Pg is read from that attachment, not asked of the caller, so it can never disagree with where the annotation actually lives. annot gains a /StructParent entry pointing back at e; an annotation already referenced by another structure element is rejected; each annotation is meant to appear in the reading order exactly once.
Composes with the existing primitives rather than replacing them: a link whose visible text is itself tagged calls this on the element TagContent returned; a link with no separately-tagged visible text (e.g. an image link tagged as /Figure elsewhere) calls it on a bare AddChild(StructLink).
func (*StructElement) SetActualText ¶ added in v0.4.0
func (e *StructElement) SetActualText(text string)
SetActualText sets the exact text (/ActualText) the element represents.
func (*StructElement) SetAlt ¶ added in v0.4.0
func (e *StructElement) SetAlt(text string)
SetAlt sets alternate text (/Alt) — required on Figure/Formula for PDF/UA.
func (*StructElement) SetLanguage ¶ added in v0.4.0
func (e *StructElement) SetLanguage(lang string)
SetLanguage overrides the natural language for this element's content.
type StructType ¶ added in v0.4.0
type StructType string
StructType is a PDF standard structure type (ISO 32000-1 §14.8.4), used as the /S value of a structure element. The value includes the leading slash.
const ( StructDocument StructType = "/Document" StructPart StructType = "/Part" StructArt StructType = "/Art" StructSect StructType = "/Sect" StructDiv StructType = "/Div" StructP StructType = "/P" StructH StructType = "/H" StructH1 StructType = "/H1" StructH2 StructType = "/H2" StructH3 StructType = "/H3" StructH4 StructType = "/H4" StructH5 StructType = "/H5" StructH6 StructType = "/H6" StructSpan StructType = "/Span" StructQuote StructType = "/Quote" StructNote StructType = "/Note" StructCode StructType = "/Code" StructFigure StructType = "/Figure" StructFormula StructType = "/Formula" StructCaption StructType = "/Caption" StructList StructType = "/L" StructListItem StructType = "/LI" StructLabel StructType = "/Lbl" StructListBody StructType = "/LBody" StructTable StructType = "/Table" StructTR StructType = "/TR" StructTH StructType = "/TH" StructTD StructType = "/TD" StructTHead StructType = "/THead" StructTBody StructType = "/TBody" StructTFoot StructType = "/TFoot" StructLink StructType = "/Link" // StructAnnot wraps content associated with an annotation other than a // link (e.g. a comment's visible marker). StructAnnot StructType = "/Annot" // StructForm marks a form field's visible representation as part of the // reading order — distinct from the AcroForm field itself. StructForm StructType = "/Form" // StructBibEntry is one entry in a bibliography. StructBibEntry StructType = "/BibEntry" // StructBlockQuote is a block-level (multi-paragraph) quotation, as // opposed to StructQuote's inline one. StructBlockQuote StructType = "/BlockQuote" // StructIndex is a sequence of entries in a back-of-book index. StructIndex StructType = "/Index" // StructTOC is a table of contents; its entries are StructTOCI. StructTOC StructType = "/TOC" // StructTOCI is one table-of-contents entry, typically containing a // StructLink (AddObjectReference) to its target. StructTOCI StructType = "/TOCI" // StructNonStruct groups content that carries no useful structural // meaning of its own without excluding it from the tree entirely (unlike // TagArtifact, which removes content from the tree). StructNonStruct StructType = "/NonStruct" // StructPrivate is application-specific content a generic reader can // ignore the internal structure of, but should not discard. StructPrivate StructType = "/Private" // StructReference is a citation to content elsewhere in the document. StructReference StructType = "/Reference" // StructRuby and StructWarichu are East Asian typography annotations // (ISO 32000-2): a ruby gloss above/beside base text, and interlinear // (two-line) annotation text respectively. StructRuby StructType = "/Ruby" StructWarichu StructType = "/Warichu" )
Standard structure types. Grouping types (Document, Part, Sect, Div, Table, TR, L, …) hold child elements; the rest typically wrap marked content.
type SubmitFormAction ¶
type SubmitFormAction struct {
// contains filtered or unexported fields
}
SubmitFormAction submits form field values to a URL.
func NewSubmitFormAction ¶
func NewSubmitFormAction(url string, fields []string, flags SubmitFormFlags) *SubmitFormAction
NewSubmitFormAction builds a /SubmitForm action. The fields slice is copied; the caller may safely mutate it after this returns.
func (*SubmitFormAction) ActionType ¶
func (a *SubmitFormAction) ActionType() ActionType
func (*SubmitFormAction) FieldNames ¶
func (a *SubmitFormAction) FieldNames() []string
FieldNames returns a copy of the field-name list. The returned slice is owned by the caller; mutating it does not affect the action.
func (*SubmitFormAction) Flags ¶
func (a *SubmitFormAction) Flags() SubmitFormFlags
func (*SubmitFormAction) SetFieldNames ¶
func (a *SubmitFormAction) SetFieldNames(f []string)
SetFieldNames replaces the field-name list. The slice is copied; the caller may safely mutate f after this returns.
func (*SubmitFormAction) SetFlags ¶
func (a *SubmitFormAction) SetFlags(f SubmitFormFlags)
func (*SubmitFormAction) SetURL ¶
func (a *SubmitFormAction) SetURL(u string)
func (*SubmitFormAction) URL ¶
func (a *SubmitFormAction) URL() string
type SubmitFormFlags ¶
type SubmitFormFlags int
SubmitFormFlags is the /Flags bitfield for a /SubmitForm action per ISO 32000-1 Table 237. Bit 1 is least significant.
const ( SubmitIncludeNoValueFields SubmitFormFlags = 1 << 1 SubmitExportFormat SubmitFormFlags = 1 << 2 SubmitGetMethod SubmitFormFlags = 1 << 3 SubmitSubmitCoordinates SubmitFormFlags = 1 << 4 SubmitXFDF SubmitFormFlags = 1 << 5 SubmitIncludeAppendSaves SubmitFormFlags = 1 << 6 SubmitIncludeAnnotations SubmitFormFlags = 1 << 7 SubmitSubmitPDF SubmitFormFlags = 1 << 8 SubmitCanonicalFormat SubmitFormFlags = 1 << 9 SubmitExclNonUserAnnots SubmitFormFlags = 1 << 10 SubmitExclFKey SubmitFormFlags = 1 << 11 SubmitEmbedForm SubmitFormFlags = 1 << 13 )
type TOCEntry ¶ added in v0.4.0
type TOCEntry struct {
Title string
Level int
Page *Page
// Label overrides the displayed page number. Empty uses the target
// Page's 1-based number; set it to show a logical label instead (e.g.
// a /PageLabels label like "iv" or a body number that differs from the
// physical page index). The link still targets Page.
Label string
}
TOCEntry is one line of a table of contents: a title, an indent level (0 = top level), and the page it points at. A nil Page renders the line without a page number or link.
type TOCOptions ¶ added in v0.4.0
type TOCOptions struct {
// Title is the heading drawn above the entries (e.g. "Table of
// Contents"). Empty draws no heading.
Title string
// TitleStyle styles the heading. Zero value = Helvetica-Bold 18, black.
TitleStyle TextStyle
// EntryStyle styles every entry line. Zero value = Helvetica 12, black.
// HAlign/VAlign are managed internally and ignored here.
EntryStyle TextStyle
// IndentStep is the horizontal indent added per level, in points.
// Zero = 18.
IndentStep float64
// LineSpacing multiplies the entry font size to get the row height.
// Zero = 1.6.
LineSpacing float64
// Margin is the page margin used for the pages GenerateTOC inserts,
// in points. Zero = 54. Ignored by Page.AddTOC (which uses its rect).
Margin float64
NoPageNumbers bool // zero value draws page numbers
NoLeader bool // zero value draws a dotted leader between title and number
NoLinks bool // zero value adds a GoTo link over each entry
}
TOCOptions controls how a table of contents is rendered. The zero value produces a sensible TOC: black 12pt entries, an 18pt-per-level indent, 1.6 line spacing, dotted leaders, page numbers, and clickable links. The negative ("No…") booleans turn those defaults off so that the zero value stays the full-featured one.
Loosely mirrors Aspose.PDF for .NET's TocInfo (a title plus per-entry formatting and dotted leaders).
type Table ¶
type Table struct {
// contains filtered or unexported fields
}
Table is a transient builder for a tabular layout drawn onto a Page. Mirrors Aspose.PDF for .NET's Table class. After (*Page).AddTable renders the table, the *Table is not held by the document.
func NewTable ¶
func NewTable() *Table
NewTable returns an empty table. Configure via Set* methods + AddRow. Mirrors Aspose.PDF for .NET's `new Table()` constructor.
Example ¶
Build a tiny invoice-style table and render it onto a blank page.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
doc := pdf.NewDocumentFromFormat(pdf.PageFormatA4)
page, _ := doc.Page(1)
table := pdf.NewTable().
SetColumnWidths([]float64{300, 100}).
SetDefaultCellBorder(pdf.BorderInfo{Sides: pdf.BorderSideAll, Width: 0.5}).
SetDefaultCellMargin(pdf.MarginInfo{Top: 4, Right: 6, Bottom: 4, Left: 6})
header := table.AddRow()
header.AddCell("Item").SetTextStyle(pdf.TextStyle{Font: pdf.FontHelveticaBold, Size: 11})
header.AddCell("Price").SetTextStyle(pdf.TextStyle{Font: pdf.FontHelveticaBold, Size: 11}).
SetHAlign(pdf.HAlignRight)
table.AddRows([][]string{
{"Espresso", "€3.50"},
{"Cappuccino", "€4.50"},
{"Tiramisu", "€7.50"},
})
rect := pdf.Rectangle{LLX: 50, LLY: 500, URX: 450, URY: 750}
if _, err := page.AddTable(table, rect); err != nil {
log.Fatal(err)
}
fmt.Println("rows:", table.RowCount())
}
Output: rows: 4
func (*Table) AddRows ¶
AddRows is a convenience that creates one Row per inner slice and one Cell per string in that slice. Returns the rows in insertion order so callers can apply further per-row customization (SetBackground, SetHeight, etc.).
Rows added through AddRows have plain cells — no ColSpan/RowSpan. For spanning, use the explicit AddRow + Cell.SetColSpan flow.
func (*Table) Border ¶
func (t *Table) Border() BorderInfo
func (*Table) ColumnWidths ¶
ColumnWidths returns a copy of the column widths.
func (*Table) DefaultCellBorder ¶
func (t *Table) DefaultCellBorder() BorderInfo
func (*Table) DefaultCellMargin ¶
func (t *Table) DefaultCellMargin() MarginInfo
func (*Table) DefaultCellStyle ¶
func (*Table) OverflowMargins ¶
OverflowMargins returns the configured overflow margins (defaults 50/50 if SetOverflowMargins has not been called).
func (*Table) RepeatingRowsCount ¶
RepeatingRowsCount returns the number of header rows that repeat on each continuation page (default 0).
func (*Table) SetBorder ¶
func (t *Table) SetBorder(b BorderInfo) *Table
func (*Table) SetColumnWidths ¶
SetColumnWidths sets the column widths in points. Defensive-copies the slice.
func (*Table) SetDefaultCellBorder ¶
func (t *Table) SetDefaultCellBorder(b BorderInfo) *Table
func (*Table) SetDefaultCellMargin ¶
func (t *Table) SetDefaultCellMargin(m MarginInfo) *Table
func (*Table) SetDefaultCellStyle ¶
func (*Table) SetOverflowMargins ¶
SetOverflowMargins sets the top/bottom margins (in points) used to compute the continuation-page bounding rectangle when the table overflows the original rect. Defaults: 50pt on each side.
The continuation rect uses the same LLX/URX as the original rect; the Y range becomes [bottom, pageHeight - top].
func (*Table) SetRepeatingRowsCount ¶
SetRepeatingRowsCount marks the first n rows as headers that repeat at the top of every continuation page. Default 0 (no repeat).
Mirrors Aspose.PDF for .NET's Table.RepeatingRowsCount property.
type TableAbsorber ¶ added in v0.7.0
type TableAbsorber struct {
// contains filtered or unexported fields
}
TableAbsorber detects tables on a page and exposes their logical structure (epic pdf-go-w4ht). Mirrors Aspose.PDF for .NET's TableAbsorber:
absorber := pdf.NewTableAbsorber()
if err := absorber.Visit(page); err != nil { ... }
for _, table := range absorber.TableList() {
for _, row := range table.RowList() {
for _, cell := range row.CellList() { _ = cell.Text() }
}
}
The current detector is vector-native lattice recognition (ruled tables, including borders drawn as thin filled rectangles, dashed/segmented rules, and rowspan/colspan from missing inner rulings). Borderless (stream-mode) recognition is the next phase; note Aspose's own absorber handles ruled tables only.
func NewTableAbsorber ¶ added in v0.7.0
func NewTableAbsorber() *TableAbsorber
NewTableAbsorber creates a table absorber.
func (*TableAbsorber) TableList ¶ added in v0.7.0
func (ta *TableAbsorber) TableList() []*AbsorbedTable
TableList returns the tables recognized by the last Visit, top-to-bottom.
func (*TableAbsorber) Visit ¶ added in v0.7.0
func (ta *TableAbsorber) Visit(p *Page) error
Visit runs table detection on the page, replacing the absorber's TableList.
type TaggedContent ¶ added in v0.4.0
type TaggedContent struct {
// contains filtered or unexported fields
}
TaggedContent is the facade for authoring a Tagged PDF (ISO 32000-1 §14.8): it owns the document's logical structure tree and sets the catalog marks PDF/UA requires. Obtain it with (*Document).TaggedContent. Mirrors the intent of Aspose.PDF for .NET's Document.TaggedContent / ITaggedContent.
func (*TaggedContent) Root ¶ added in v0.4.0
func (tc *TaggedContent) Root() *StructElement
Root returns the document-level (/Document) structure element — the default parent for top-level content.
func (*TaggedContent) SetLanguage ¶ added in v0.4.0
func (tc *TaggedContent) SetLanguage(lang string)
SetLanguage sets the document's default natural language (/Catalog/Lang), e.g. "en-US".
func (*TaggedContent) SetTitle ¶ added in v0.4.0
func (tc *TaggedContent) SetTitle(title string)
SetTitle sets the document title (so PDF/UA's title requirement is met).
type TextAnnotation ¶
type TextAnnotation struct {
// contains filtered or unexported fields
}
TextAnnotation is a sticky-note annotation. Renders as an icon (no /AP/N — viewers draw their own icon for the /Name value). The associated /Contents is the note's body text shown in a popup when the icon is clicked.
func NewTextAnnotation ¶
func NewTextAnnotation(page *Page, position Point) *TextAnnotation
NewTextAnnotation builds an unbound text-note annotation. Page must be non-nil. The /Rect is auto-computed as a 24×24 pt square anchored at position (Acrobat sticky-note convention).
func (*TextAnnotation) AnnotationType ¶
func (a *TextAnnotation) AnnotationType() AnnotationType
func (*TextAnnotation) Color ¶
func (b *TextAnnotation) Color() *Color
Color returns the /C array as an RGB Color. Returns nil if /C is absent.
func (*TextAnnotation) Contents ¶
func (b *TextAnnotation) Contents() string
Contents returns /Contents (the annotation body text).
func (*TextAnnotation) Flatten ¶ added in v0.3.0
func (b *TextAnnotation) Flatten() error
Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.
An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.
Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.
func (*TextAnnotation) Icon ¶
func (a *TextAnnotation) Icon() TextIcon
Icon returns the /Name value mapped to a TextIcon. Returns TextIconNote (the spec default) if /Name is absent.
func (*TextAnnotation) Open ¶
func (a *TextAnnotation) Open() bool
Open returns the /Open flag (whether the popup is initially shown).
func (*TextAnnotation) PageIndex ¶
func (b *TextAnnotation) PageIndex() int
PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.
func (*TextAnnotation) Rect ¶
func (b *TextAnnotation) Rect() Rectangle
Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.
func (*TextAnnotation) RegenerateAppearance ¶
func (a *TextAnnotation) RegenerateAppearance()
RegenerateAppearance is a no-op for TextAnnotation (no /AP — viewers render the icon themselves). Present for API symmetry across all annotation types.
func (*TextAnnotation) SetColor ¶
func (b *TextAnnotation) SetColor(c *Color)
SetColor writes /C as an RGB array; nil removes the entry.
func (*TextAnnotation) SetContents ¶
func (b *TextAnnotation) SetContents(s string)
SetContents writes /Contents (the annotation body text); empty string removes the entry.
func (*TextAnnotation) SetIcon ¶
func (a *TextAnnotation) SetIcon(t TextIcon)
SetIcon writes the /Name entry. Unknown is encoded as /Note (default) to avoid producing an empty name.
func (*TextAnnotation) SetOpen ¶
func (a *TextAnnotation) SetOpen(open bool)
SetOpen writes the /Open flag.
func (*TextAnnotation) SetRect ¶
func (b *TextAnnotation) SetRect(r Rectangle)
SetRect writes the annotation rectangle.
type TextBoxField ¶
type TextBoxField struct {
// contains filtered or unexported fields
}
TextBoxField is a single- or multi-line text input.
func (*TextBoxField) Flatten ¶ added in v0.3.0
func (b *TextBoxField) Flatten() error
Flatten bakes this single field's appearance (each of its widgets) into the owning page content and removes the field, leaving every other field and the /AcroForm dict intact. Mirrors Aspose.PDF for .NET's Field.Flatten.
After Flatten the field handle is dangling and must not be used.
func (*TextBoxField) IsMultiline ¶
func (f *TextBoxField) IsMultiline() bool
func (*TextBoxField) IsPassword ¶
func (f *TextBoxField) IsPassword() bool
func (*TextBoxField) IsReadOnly ¶
func (b *TextBoxField) IsReadOnly() bool
func (*TextBoxField) IsRequired ¶
func (b *TextBoxField) IsRequired() bool
func (*TextBoxField) MaxLen ¶
func (f *TextBoxField) MaxLen() int
func (*TextBoxField) PartialName ¶
func (b *TextBoxField) PartialName() string
func (*TextBoxField) SetMaxLen ¶
func (f *TextBoxField) SetMaxLen(n int)
SetMaxLen sets the maximum number of characters. 0 removes the limit.
func (*TextBoxField) SetMultiline ¶
func (f *TextBoxField) SetMultiline(v bool)
func (*TextBoxField) SetPassword ¶
func (f *TextBoxField) SetPassword(v bool)
func (*TextBoxField) SetReadOnly ¶
func (f *TextBoxField) SetReadOnly(v bool)
func (*TextBoxField) SetRequired ¶
func (f *TextBoxField) SetRequired(v bool)
func (*TextBoxField) SetStyle ¶ added in v0.3.0
func (b *TextBoxField) SetStyle(s FieldStyle) error
SetStyle applies s to the field, writing /MK, /BS, /DA, and /Q on the field and its widgets and regenerating each widget's /AP appearance so the new look is visible immediately in every viewer. Returns an error only if the field is detached or a styled font cannot be registered.
func (*TextBoxField) SetValue ¶
func (f *TextBoxField) SetValue(s string) error
func (*TextBoxField) Style ¶ added in v0.3.0
func (b *TextBoxField) Style() FieldStyle
Style reads back the field's current styling from /DA, /Q, /MK, and /BS. Properties never set return their zero/default value. The first widget is used for /MK and /BS.
func (*TextBoxField) Value ¶
func (f *TextBoxField) Value() string
type TextExtractOptions ¶ added in v0.4.0
type TextExtractOptions struct {
Mode TextExtractionMode
}
TextExtractOptions configures ExtractText. The zero value is reading order.
type TextExtractionMode ¶ added in v0.4.0
type TextExtractionMode int
TextExtractionMode selects how ExtractText orders the extracted text. Mirrors the intent of Aspose.PDF for .NET's TextExtractionOptions.TextFormattingMode.
const ( // TextExtractReading returns text in visual reading order (fragments sorted // top-to-bottom, left-to-right, grouped into lines). This is the default. TextExtractReading TextExtractionMode = iota // TextExtractRaw returns text in the order the content stream emits it, // without visual sorting — useful when the emission order is significant or // when the reading-order heuristics reorder columned/overlapping content. TextExtractRaw // TextExtractFlatten lays the page out on a fixed-pitch character grid: // every word keeps its horizontal position, padded with spaces, so // columns stay columns and the output reads like the page when shown in a // monospace font. Mirrors Aspose.PDF for .NET's TextFormattingMode.Flatten // — useful for fixed-format reports, for diffing two revisions of a page, // and for tabular text no table detector was asked about. TextExtractFlatten )
type TextFragment ¶
type TextFragment struct {
Text string
X float64 // horizontal position in points (from left edge)
Y float64 // vertical position in points (from bottom edge)
Width float64 // width in points
FontName string // e.g. "Helvetica", "Arial-BoldMT"
FontSize float64 // effective size in points
Height float64 // text height in points (from ascent/descent metrics)
Bold bool
Italic bool
CharSpacing float64 // character spacing (Tc operator) in text space units
Color Color // fill color
IsSubscript bool // Y is below the line baseline
IsSuperscript bool // Y is above the line baseline
Rotation float64 // baseline angle in degrees CCW; 0 = horizontal (diagonal watermarks, axis labels, …)
// contains filtered or unexported fields
}
TextFragment represents a contiguous run of text with uniform font.
type TextIcon ¶
type TextIcon int
TextIcon names per ISO 32000-1 §12.5.6.4 Table 172, used in /Subtype /Text annotations' /Name entry.
type TextLine ¶
type TextLine struct {
Text string // concatenated text of all fragments (with spaces)
Y float64 // vertical position in points (from bottom edge)
Fragments []TextFragment
}
TextLine represents a horizontal line of text fragments at a common Y position.
type TextMatch ¶ added in v0.3.0
type TextMatch struct {
Text string // the matched text as it appears on the page
PageNumber int // 1-based page number the match was found on
Rect Rectangle // bounding box of the match in PDF user space (points)
}
TextMatch is a single occurrence located by SearchText.
type TextStamp ¶ added in v0.4.0
type TextStamp struct {
// Value is the text to stamp. Mirrors Aspose TextStamp.Value.
Value string
// TextStyle controls font, size, and colour (the stamp's HAlign/VAlign/
// RotateAngle/Background override the style's alignment/rotation/behind).
// Mirrors Aspose TextStamp.TextState.
TextStyle TextStyle
// contains filtered or unexported fields
}
TextStamp overlays a line (or wrapped block) of text. Mirrors Aspose.Pdf.TextStamp. Construct with NewTextStamp.
func NewTextStamp ¶ added in v0.4.0
NewTextStamp creates a text stamp. Mirrors Aspose's TextStamp(string, ...).
type TextStyle ¶
type TextStyle struct {
Font Font // nil defaults to FontHelvetica in AddText
Size float64 // in points; 0 treated as 12
Color *Color // nil → black opaque {0,0,0,1}
Background *Color // nil → no background
HAlign HAlign // default: HAlignLeft
VAlign VAlign // default: VAlignTop
LineSpacing float64 // multiplier of font size; 0 treated as 1.2
Underline bool
Strikethrough bool
Rotation float64 // degrees counter-clockwise; pivot = lower-left corner of rect; default 0
Behind bool // if true, text is drawn under existing page content; default false
RTL bool // if true, the paragraph base direction is right-to-left (Hebrew/Arabic); default false (auto-detected from the text when it contains RTL characters)
Skew float64 // synthetic oblique: glyph slant in degrees (positive leans right, ~12 matches typical italics); applied per line about its baseline — faux italic for fonts without an italic face
Invisible bool // if true, glyphs use text rendering mode 3 (ISO 32000-1 §9.3.6): nothing is painted, but the text remains selectable, searchable, and extractable. Underline/Strikethrough decorations are suppressed too. Used for hidden OCR text layers over scanned pages.
// MissingGlyph controls what AddText/AddTextAt/MeasureText do when
// the font has no glyph for a character in text. Zero value
// (MissingGlyphAllow) keeps the long-standing default: the character
// draws .notdef (glyph 0) — or, for a Type3 font, is silently
// dropped — with no signal at all (GitHub issue #19,
// shadowhunter1470-svg). A default-ignorable code point (a zero-width
// joiner, a variation selector, …) is never flagged regardless of
// this setting — drawing nothing for one of those is correct, not
// missing.
MissingGlyph MissingGlyphPolicy
// ReplacementRune is substituted for a missing glyph when
// MissingGlyph is MissingGlyphReplace. Zero value (rune 0) means
// U+FFFD, the Unicode replacement character — the same substitution
// this library's own text extraction already uses for a character
// it can't map back from a glyph. If the font has no glyph for the
// replacement rune either, that draws .notdef in turn; pick a
// replacement the font actually covers if that matters.
ReplacementRune rune
}
TextStyle defines reusable text formatting properties.
type TiffDevice ¶ added in v0.3.0
type TiffDevice struct {
// contains filtered or unexported fields
}
TiffDevice renders pages to TIFF. Mirrors Aspose.PDF for .NET's TiffDevice: Process writes one page, ProcessDocument writes a whole document as a single multi-page TIFF.
func NewTiffDevice ¶ added in v0.3.0
func NewTiffDevice(res Resolution) *TiffDevice
NewTiffDevice returns a TiffDevice for the given resolution.
func (*TiffDevice) Process ¶ added in v0.3.0
func (d *TiffDevice) Process(page *Page, w io.Writer) error
Process renders page and writes it to w as a single-page TIFF.
func (*TiffDevice) ProcessDocument ¶ added in v0.3.0
func (d *TiffDevice) ProcessDocument(doc *Document, w io.Writer) error
ProcessDocument renders every page of doc into one multi-page TIFF.
type TilingPattern ¶ added in v0.4.0
type TilingPattern struct {
// contains filtered or unexported fields
}
TilingPattern is a repeating fill (PatternType 1, ISO 32000-1 §8.7.3.1): a small cell of content tiled across whatever shape it fills. Draw the cell once via Canvas() (the full *Page drawing API), optionally adjust the tile spacing with SetStep, then use it as a fill by setting ShapeStyle.FillTiling on any Draw* call. Useful for hatching, textures and repeated motifs. Mirrors the colored (PaintType 1) tiling patterns of Aspose.PDF for .NET.
func (*TilingPattern) Canvas ¶ added in v0.4.0
func (t *TilingPattern) Canvas() *Page
Canvas returns the cell's drawing surface (the full *Page drawing API). Draw everything before the pattern is first used as a fill — its content is frozen at that point.
func (*TilingPattern) SetStep ¶ added in v0.4.0
func (t *TilingPattern) SetStep(xstep, ystep float64)
SetStep sets the horizontal and vertical tile spacing in points. The default is the cell size (tiles touch edge-to-edge); a larger step leaves gaps, a smaller one overlaps. Non-positive values are ignored.
type Type3Font ¶ added in v0.8.0
type Type3Font struct {
// contains filtered or unexported fields
}
Type3Font is a user-defined glyph-stream font. Create with Document.CreateType3Font, add glyphs, then use as TextStyle.Font.
func (*Type3Font) AddGlyph ¶ added in v0.8.0
AddGlyph registers a glyph for r with the given advance width (in 1/1000 em, like all font metrics) and returns its drawing canvas: a detached page covering the em square (x 0..1000, y -300..1000, baseline at y=0) on which the whole drawing API works. Draw before the first AddText using the font — glyph streams are frozen when the font is first used. Errors on a duplicate rune, a non-positive width, a font already frozen, or a full font (255 glyphs).
func (*Type3Font) IsEmbedded ¶ added in v0.8.0
IsEmbedded implements Font (glyph streams are embedded by construction).
type UnderlineAnnotation ¶
type UnderlineAnnotation struct {
// contains filtered or unexported fields
}
UnderlineAnnotation draws a horizontal line under text.
func NewUnderlineAnnotation ¶
func NewUnderlineAnnotation(page *Page, rect Rectangle) *UnderlineAnnotation
NewUnderlineAnnotation builds an unbound underline annotation.
func (*UnderlineAnnotation) AnnotationType ¶
func (a *UnderlineAnnotation) AnnotationType() AnnotationType
func (*UnderlineAnnotation) QuadPoints ¶
func (m *UnderlineAnnotation) QuadPoints() []QuadPoint
QuadPoints returns the array of quads describing the marked region. Returns nil if /QuadPoints is absent or its array length is not a multiple of 8 (malformed).
func (*UnderlineAnnotation) RegenerateAppearance ¶ added in v0.9.0
func (a *UnderlineAnnotation) RegenerateAppearance()
RegenerateAppearance forces /AP/N to be rebuilt from current properties.
func (*UnderlineAnnotation) SetColor ¶
func (m *UnderlineAnnotation) SetColor(c *Color)
SetColor writes /C and redraws the appearance in the new colour.
func (*UnderlineAnnotation) SetQuadPoints ¶
func (m *UnderlineAnnotation) SetQuadPoints(qp []QuadPoint)
SetQuadPoints writes /QuadPoints. nil or empty slice removes the entry.
type ValidationIssue ¶
type ValidationIssue struct {
Code string // e.g. "INVALID_HEADER", "XREF_ERROR", "OBJECT_ERROR", "PAGE_TREE_ERROR", "ENCRYPTED"
Message string
}
ValidationIssue describes a single problem found in a PDF file.
type ValidationOptions ¶ added in v0.10.0
type ValidationOptions struct {
// Revocation selects how far to go in establishing revocation status.
Revocation RevocationCheck
// Fetcher supplies revocation material; nil uses the built-in HTTP client.
Fetcher RevocationFetcher
// Timeout bounds each network request; zero means 10 seconds.
Timeout time.Duration
}
ValidationOptions configures signature verification. The zero value checks no revocation, so existing calls behave exactly as before. Mirrors the intent of Aspose.PDF for .NET's ValidationOptions / OcspSettings.
type ValidationReport ¶
type ValidationReport struct {
// Valid is true when no issues were found.
Valid bool
Issues []ValidationIssue
}
ValidationReport is returned by Validate and summarises the structural integrity of a PDF.
func Validate ¶
func Validate(inputPath string) (*ValidationReport, error)
Validate checks a PDF file for structural integrity. It verifies the file header, cross-reference table, all indirect objects, and the page tree. Encrypted documents are flagged with an ENCRYPTED issue but are not treated as invalid.
Scope: this is a structural-integrity check (is the file parseable and internally consistent), NOT a standards-conformance check. It does not validate PDF/A or PDF/UA. This differs from Aspose.PDF for .NET's Document.Validate, which checks PDF/A and PDF/UA compliance and writes an XML report; the corresponding capability here is intentionally narrower.
A non-nil error is returned only for I/O failures (file not found, etc.). PDF-level problems are reported inside ValidationReport.Issues.
Example:
report, err := asposepdf.Validate("document.pdf")
if err != nil {
log.Fatal(err)
}
if !report.Valid {
for _, issue := range report.Issues {
fmt.Println(issue.Code, issue.Message)
}
}
Example ¶
Validate the structural integrity of a PDF file.
package main
import (
"fmt"
"log"
pdf "github.com/aspose-pdf-foss/aspose-pdf-foss-for-go"
)
func main() {
report, err := pdf.Validate("testdata/4pages.pdf")
if err != nil {
log.Fatal(err)
}
fmt.Println("valid:", report.Valid, "issues:", len(report.Issues))
}
Output: valid: true issues: 0
type WidgetAnnotation ¶
type WidgetAnnotation struct {
// contains filtered or unexported fields
}
WidgetAnnotation is the read-only view of a form widget annotation surfaced through AnnotationCollection. Form fields continue to be mutated via the Form API — a WidgetAnnotation only exposes the base Annotation surface (Rect, Color, Title, Contents, PageIndex).
func (*WidgetAnnotation) AnnotationType ¶
func (a *WidgetAnnotation) AnnotationType() AnnotationType
func (*WidgetAnnotation) Color ¶
func (b *WidgetAnnotation) Color() *Color
Color returns the /C array as an RGB Color. Returns nil if /C is absent.
func (*WidgetAnnotation) Contents ¶
func (b *WidgetAnnotation) Contents() string
Contents returns /Contents (the annotation body text).
func (*WidgetAnnotation) Flatten ¶ added in v0.3.0
func (b *WidgetAnnotation) Flatten() error
Flatten bakes this annotation's normal appearance (/AP/N, honoring the /AS state) into its page's content stream at the annotation's /Rect, then removes the annotation. The annotation handle is dangling afterwards.
An annotation with no normal appearance (e.g. a sticky-note Text annotation, which viewers render as an icon) is simply removed — nothing is drawn.
Mirrors Aspose.PDF for .NET's Annotation.Flatten. For form-field widgets prefer (*Form).Flatten, which also clears the /AcroForm entry.
func (*WidgetAnnotation) PageIndex ¶
func (b *WidgetAnnotation) PageIndex() int
PageIndex returns the 1-based index of the page this annotation lives on. 0 if the annotation is not yet attached or its /P doesn't resolve.
func (*WidgetAnnotation) Rect ¶
func (b *WidgetAnnotation) Rect() Rectangle
Rect returns the annotation rectangle. Empty Rectangle if /Rect is missing or malformed.
func (*WidgetAnnotation) SetColor ¶
func (b *WidgetAnnotation) SetColor(c *Color)
SetColor writes /C as an RGB array; nil removes the entry.
func (*WidgetAnnotation) SetContents ¶
func (b *WidgetAnnotation) SetContents(s string)
SetContents writes /Contents (the annotation body text); empty string removes the entry.
func (*WidgetAnnotation) SetRect ¶
func (b *WidgetAnnotation) SetRect(r Rectangle)
SetRect writes the annotation rectangle.
type XForm ¶ added in v0.4.0
type XForm struct {
// contains filtered or unexported fields
}
XForm is a reusable Form XObject (ISO 32000-1 §8.10) — a self-contained content stream (with its own resources) that can be placed on any number of pages and positions with a single Do invocation. Draw into it once via its Canvas (the full *Page drawing API: AddText, Draw*, AddImage, AddTable, …), then place it with Page.AddForm. Ideal for page templates, shared headers/footers and watermarks. Mirrors the intent of Aspose.PDF for .NET's XForm.
type XMPMetadata ¶ added in v0.3.0
type XMPMetadata struct {
Title string
Authors []string
Description string
Keywords []string
CreatorTool string
Producer string
CreateDate string
ModifyDate string
MetadataDate string
Custom []XMPProperty
}
XMPMetadata is the document's XMP packet modelled as common schema fields plus a list of arbitrary Custom properties. Empty fields are omitted when written. Dates are ISO 8601 strings (e.g. "2026-05-29T12:00:00Z") to round-trip losslessly.
Field → XMP property mapping:
- Title → dc:title (language alternative, x-default)
- Authors → dc:creator (ordered rdf:Seq)
- Description → dc:description (language alternative, x-default)
- Keywords → dc:subject (unordered rdf:Bag)
- CreatorTool → xmp:CreatorTool
- CreateDate → xmp:CreateDate
- ModifyDate → xmp:ModifyDate
- MetadataDate → xmp:MetadataDate
- Producer → pdf:Producer
func (XMPMetadata) IsEmpty ¶ added in v0.3.0
func (m XMPMetadata) IsEmpty() bool
IsEmpty reports whether the XMP metadata carries no information.
type XMPProperty ¶ added in v0.3.0
type XMPProperty struct {
Namespace string // namespace URI, e.g. "http://ns.adobe.com/xap/1.0/mm/"
Prefix string // namespace prefix used in the serialised packet, e.g. "xmpMM"
Name string // local property name, e.g. "DocumentID"
Value string // property value
}
XMPProperty is a single simple (string-valued) XMP property in an arbitrary namespace. Used for properties outside the common Dublin Core / XMP Basic / PDF schemas modelled directly on XMPMetadata.
type XlsxRecognitionMode ¶ added in v0.8.0
type XlsxRecognitionMode int
XlsxRecognitionMode selects what lands in the workbook.
const ( // XlsxTablesOnly (default): every detected table, stacked on a single // "Tables" worksheet in document order — a "Page N" caption above the // first table of each page, one blank row between tables. Tables // continuing across consecutive pages with the same column signature // are stitched into one (the repeated header row is dropped). XlsxTablesOnly XlsxRecognitionMode = iota // XlsxFullPage: one worksheet per source page carrying ALL page text — // layout lines become rows, wide intra-line gaps split cells, detected // tables keep their exact logical grid. XlsxFullPage )
type XlsxSaveOptions ¶ added in v0.8.0
type XlsxSaveOptions struct {
// Pages is a 1-based subset (in the given order); nil = all pages.
Pages []int
// Mode selects the recognition mode (default XlsxTablesOnly).
Mode XlsxRecognitionMode
// NoStyles suppresses fills, fonts, alignment and column widths.
NoStyles bool
// NoImages skips images (FullPage mode anchors page images on the
// sheet; TablesOnly never carries images).
NoImages bool
}
XlsxSaveOptions configures SaveXlsx / WriteXlsx.
Source Files
¶
- alt_text.go
- annotation.go
- annotation_action.go
- annotation_caret.go
- annotation_drawing.go
- annotation_fileattachment.go
- annotation_freetext.go
- annotation_link.go
- annotation_markup.go
- annotation_poly.go
- annotation_redact.go
- annotation_stamp.go
- annotation_text.go
- appearance.go
- appearance_barcode.go
- appearance_builder.go
- appearance_caret.go
- appearance_freetext.go
- appearance_markup.go
- appearance_poly.go
- appearance_redact.go
- appearance_sign.go
- appearance_stamp.go
- appearance_widget.go
- arabic_joining.go
- arabic_shape.go
- associated_files.go
- barcode.go
- barcode_code128.go
- barcode_pdf417.go
- barcode_pdf417_tables.go
- barcode_qr.go
- barcode_qr_gf256.go
- barcode_qr_tables.go
- bidi.go
- bmp.go
- ccitt.go
- ccitt_tables.go
- cff.go
- cmap.go
- cmap_cid.go
- cmap_cid_data.go
- cmyk_lut.go
- collection.go
- color.go
- combining.go
- comparison.go
- comparison_diff.go
- comparison_graphical.go
- comparison_markup.go
- comparison_output.go
- comparison_output_html.go
- comparison_output_json.go
- comparison_output_markdown.go
- comparison_output_pdf.go
- comparison_sidebyside.go
- comparison_tokens.go
- content_append.go
- content_parser.go
- crl.go
- decrypt.go
- decrypt_aes.go
- decrypt_aes256.go
- doc.go
- document.go
- document_new.go
- document_pages.go
- docx_parts.go
- docx_textbox.go
- docx_write.go
- dss.go
- einvoice.go
- einvoice_xmp.go
- embedded_files.go
- encoding.go
- encrypt.go
- encrypt_aes.go
- encrypt_aes256.go
- epub_write.go
- flatten.go
- flatten_transparency.go
- flow.go
- flow_box.go
- flow_doc.go
- flow_float.go
- flow_runs.go
- flow_vector.go
- font.go
- font_api.go
- font_byname.go
- font_embed.go
- font_metrics.go
- font_subset.go
- font_unembed.go
- form.go
- form_button.go
- form_fdf.go
- form_fields.go
- form_fields_extra.go
- form_json.go
- form_style.go
- form_xfdf.go
- form_xobject.go
- grayscale.go
- html_export.go
- html_export_flow.go
- html_export_fonts.go
- html_export_forms.go
- html_export_nav.go
- html_export_svg.go
- icc.go
- image.go
- image_add.go
- image_convert.go
- image_decode.go
- image_inline.go
- image_inline_write.go
- image_optimize.go
- image_remove.go
- image_replace.go
- imposition.go
- io.go
- javascript.go
- jbig2.go
- jbig2_generic.go
- jbig2_halftone.go
- jbig2_huffman.go
- jbig2_huffsym.go
- jbig2_hufftext.go
- jbig2_mmr.go
- jbig2_mq.go
- jbig2_refine.go
- jbig2_symbol.go
- jbig2_tables.go
- jbig2_text.go
- jpx.go
- jpx_dwt.go
- jpx_tagtree.go
- jpx_tier1.go
- jpx_tier2.go
- lexer.go
- linearize.go
- linearize_assemble.go
- linearize_emit.go
- linearize_hint.go
- lzw.go
- markdown.go
- markdown_ast.go
- markdown_export.go
- markdown_parse_block.go
- markdown_parse_inline.go
- markdown_refdef.go
- metadata.go
- named_destinations.go
- named_destinations_parse.go
- named_destinations_write.go
- normalize_data.go
- objstm_write.go
- ocsp.go
- open_action.go
- opentype.go
- optimize.go
- optional_content.go
- outline.go
- outline_destination.go
- outline_parse.go
- outline_write.go
- page.go
- page_labels.go
- page_range.go
- paragraph.go
- parser.go
- pdfa_convert.go
- pdfa_fonts.go
- pkcs7_sign.go
- pkcs7_timestamp.go
- pkcs7_verify.go
- pubsec.go
- raster.go
- raster_path.go
- raster_stroke.go
- rectangle.go
- redact_apply.go
- redact_apply_annot.go
- redact_apply_image.go
- redact_apply_path.go
- redact_apply_pattern.go
- redact_apply_text.go
- render.go
- render_annotations.go
- render_blend.go
- render_clip.go
- render_colorspace.go
- render_device.go
- render_dingbats.go
- render_document.go
- render_fontrepo.go
- render_function_ps.go
- render_glyph.go
- render_group.go
- render_gstate.go
- render_image.go
- render_imagemask.go
- render_oc.go
- render_shading.go
- render_softmask.go
- render_std14.go
- render_text.go
- render_tiling.go
- render_type3.go
- repair.go
- replace.go
- revocation.go
- sanitize.go
- shape.go
- sign.go
- sign_incremental.go
- sign_verify.go
- stamp.go
- stamp_pdfpage.go
- svg.go
- svg_attrs.go
- svg_clip.go
- svg_css.go
- svg_export.go
- svg_filter.go
- svg_gradient.go
- svg_image.go
- svg_marker.go
- svg_mask.go
- svg_named_colors.go
- svg_parse.go
- svg_parse_clip.go
- svg_parse_filter.go
- svg_parse_gradient.go
- svg_parse_image.go
- svg_parse_marker.go
- svg_parse_mask.go
- svg_parse_text.go
- svg_parse_use.go
- svg_path.go
- svg_render.go
- svg_render_filter.go
- svg_render_gradient.go
- svg_render_image.go
- svg_render_marker.go
- svg_render_mask.go
- svg_render_text.go
- svg_text.go
- svg_transform.go
- svg_types.go
- svg_use.go
- svg_viewbox.go
- table.go
- table_detect.go
- table_detect_lattice.go
- table_detect_rules.go
- table_detect_stream.go
- table_image.go
- table_render.go
- tagged.go
- tagged_list.go
- tagged_table.go
- text.go
- text_add.go
- text_addtextat.go
- text_layout.go
- text_search.go
- text_shape.go
- tiff.go
- toc.go
- ttf.go
- type1.go
- type1_charstring.go
- type3_font.go
- types.go
- validate.go
- validate_pdfa.go
- validate_pdfua.go
- vector.go
- vector_draw.go
- vector_emit.go
- vector_gradient.go
- vector_tiling.go
- writer.go
- xlsx_parts.go
- xlsx_write.go
- xmp.go
- xref.go
- xref_reconstruct.go
Directories
¶
| Path | Synopsis |
|---|---|
|
_examples
|
|
|
acroform_build
command
Builds a single-page A4 PDF with a title, a paragraph of body text, and an AcroForm containing one field of each supported type.
|
Builds a single-page A4 PDF with a title, a paragraph of body text, and an AcroForm containing one field of each supported type. |
|
acroform_read
command
Reads every form field from a PDF and emits a JSON dump to stdout.
|
Reads every form field from a PDF and emits a JSON dump to stdout. |
|
ai_alt_text
command
ai_alt_text fills missing alternate text on the figures of a tagged PDF using a vision model, then saves the more-accessible document.
|
ai_alt_text fills missing alternate text on the figures of a tagged PDF using a vision model, then saves the more-accessible document. |
|
ai_chat
command
ai_chat opens an interactive Q&A session about a PDF using an OpenAI-compatible model: type a question, get an answer grounded in the document; the conversation keeps its history.
|
ai_chat opens an interactive Q&A session about a PDF using an OpenAI-compatible model: type a question, get an answer grounded in the document; the conversation keeps its history. |
|
ai_make_searchable
command
ai_make_searchable OCRs a scanned PDF with a vision-capable model and writes an invisible text layer over each scanned page, so the output is selectable and Ctrl+F-searchable while looking pixel-identical.
|
ai_make_searchable OCRs a scanned PDF with a vision-capable model and writes an invisible text layer over each scanned page, so the output is selectable and Ctrl+F-searchable while looking pixel-identical. |
|
ai_summary
command
ai_summary summarizes a PDF with an OpenAI-compatible model and saves the summary as both text output and a PDF next to the input.
|
ai_summary summarizes a PDF with an OpenAI-compatible model and saves the summary as both text output and a PDF next to the input. |
|
barcode_verify
command
barcode_verify renders BarcodeField symbols of every symbology to PNGs (through the real field/appearance/rasterizer pipeline) plus a manifest.json of what each should decode to, for tools/validate_barcodes.py to check with a third-party decoder.
|
barcode_verify renders BarcodeField symbols of every symbology to PNGs (through the real field/appearance/rasterizer pipeline) plus a manifest.json of what each should decode to, for tools/validate_barcodes.py to check with a third-party decoder. |
|
blank_with_images
command
|
|
|
embed_font
command
|
|
|
feature_showcase
command
Feature Showcase — a small "annual report"-style document that exercises every major Aspose.PDF for Go feature inside a single narrative.
|
Feature Showcase — a small "annual report"-style document that exercises every major Aspose.PDF for Go feature inside a single narrative. |
|
markdown_to_pdf
command
markdown_to_pdf converts a Markdown file (CommonMark + GFM tables, strikethrough, task lists, autolinks) to a paginated PDF, plus a PNG preview of page 1.
|
markdown_to_pdf converts a Markdown file (CommonMark + GFM tables, strikethrough, task lists, autolinks) to a paginated PDF, plus a PNG preview of page 1. |
|
metadata
command
|
|
|
openall
command
Diagnostic: open every PDF in a folder with the library and report any failures.
|
Diagnostic: open every PDF in a folder with the library and report any failures. |
|
pdf_to_markdown
command
pdf_to_markdown converts a PDF to GFM Markdown.
|
pdf_to_markdown converts a PDF to GFM Markdown. |
|
render
command
render rasterizes every page of a PDF to a PNG under result_files/render/, and writes the whole document as one multi-page TIFF (document.tiff).
|
render rasterizes every page of a PDF to a PNG under result_files/render/, and writes the whole document as one multi-page TIFF (document.tiff). |
|
set_password
command
|
|
|
showcase_preview
command
Regenerates docs/feature_showcase-preview.png — the clickable preview shown in the README — as a 2×2 montage of representative pages from docs/feature_showcase.pdf.
|
Regenerates docs/feature_showcase-preview.png — the clickable preview shown in the README — as a 2×2 montage of representative pages from docs/feature_showcase.pdf. |
|
text_extraction
command
|
|
|
textsearch
command
textsearch opens a real PDF, searches it for a query string, and prints the matches (text + page + bounding rectangle) as JSON.
|
textsearch opens a real PDF, searches it for a query string, and prints the matches (text + page + bounding rectangle) as JSON. |
|
toc
command
Builds a small multi-section report, adds outline bookmarks, then generates a linked table of contents from those bookmarks.
|
Builds a small multi-section report, adds outline bookmarks, then generates a linked table of contents from those bookmarks. |
|
visualtest
command
visualtest renders a slice of PDFs from a corpus folder to multi-page TIFFs for eyeballing the renderer's output against a reference viewer (Acrobat).
|
visualtest renders a slice of PDFs from a corpus folder to multi-page TIFFs for eyeballing the renderer's output against a reference viewer (Acrobat). |
|
Package ai provides AI-powered document operations — summarization, OCR of scanned pages, and a hidden-text-layer "make searchable" pipeline — built on the asposepdf core.
|
Package ai provides AI-powered document operations — summarization, OCR of scanned pages, and a hidden-text-layer "make searchable" pipeline — built on the asposepdf core. |

