gopdf

package module
v0.0.0-...-73f35b6 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: MIT Imports: 41 Imported by: 0

README

# GoPDF2

Go Reference Version

English | 中文

GoPDF2 is a Go library for generating PDF documents. Forked from gopdf, it adds HTML rendering support, the ability to open and modify existing PDFs, and other enhancements.

Requires Go 1.13+.

Features

  • Unicode subfont embedding (Chinese, Japanese, Korean, etc.) with automatic subsetting to minimize file size
  • Open and modify existing PDFs via OpenPDF — import all pages, overlay new content (text, images, HTML, drawings), and save
  • HTML-to-PDF rendering via InsertHTMLBox — supports <b>, <i>, <u>, <p>, <h1><h6>, <font>, <span style>, <img>, <ul>/<ol>, <hr>, <center>, <a>, <blockquote>, and more
  • Watermark — text and image watermarks with opacity, rotation, and tiling via AddWatermarkText / AddWatermarkImage
  • PDF annotations — sticky notes, highlights, underlines, strikeouts, squares, circles, and free text via AddAnnotation
  • Page manipulation — extract pages (ExtractPages), merge PDFs (MergePages), delete pages (DeletePage / DeletePages), copy pages (CopyPage), move pages (MovePage)
  • Page inspection — query page sizes (GetPageSize, GetAllPageSizes), source PDF page count (GetSourcePDFPageCount)
  • Page crop box — define the visible area of a page via SetPageCropBox / GetPageCropBox / ClearPageCropBox
  • Page rotation — set display rotation for pages via SetPageRotation / GetPageRotation
  • Page reordering — rearrange pages via SelectPages, SelectPagesFromFile, SelectPagesFromBytes
  • Embedded files — attach files to PDF via AddEmbeddedFile (shown in viewer's attachment panel)
  • Extended paper sizes — A0–A10, B0–B10, letter, legal, tabloid, ledger with landscape variants via PaperSize(name)
  • Geometry utilitiesRectFrom with Contains/Intersects/Union, Matrix for 2D transforms, Distance
  • Content element CRUD — list, query, delete, add, modify, and reposition individual content elements (text, images, lines, rectangles, ovals, etc.) on any page via GetPageElements, DeleteElement, ModifyTextElement, ModifyElementPosition, InsertLineElement, InsertRectElement, ClearPage, and more
  • PDF version control — set output PDF version (1.4–2.0) via SetPDFVersion / GetPDFVersion
  • Garbage collection — remove null/deleted objects and compact the document via GarbageCollect
  • Page labels — define custom page numbering (Roman, alphabetic, decimal with prefixes) via SetPageLabels
  • Typed object IDsObjID wrapper for type-safe PDF object references
  • Incremental save — write only modified objects via IncrementalSave for fast saves on large documents
  • XMP metadata — embed full XMP metadata streams (Dublin Core, PDF/A, etc.) via SetXMPMetadata
  • Document cloning — deep copy a GoPdf instance via Clone for independent modifications
  • Document scrubbing — remove sensitive metadata, XMP, embedded files, page labels via Scrub
  • Optional Content Groups (Layers) — add PDF layers for selective visibility via AddOCG / GetOCGs
  • Page layout & page mode — control viewer display via SetPageLayout / SetPageMode
  • Document statistics — inspect document structure via GetDocumentStats / GetFonts
  • TOC / Bookmarks — read and write hierarchical outline trees via GetTOC / SetTOC
  • Text extraction — extract text with positions from existing PDFs via ExtractTextFromPage / ExtractPageText
  • Image extraction — extract images with metadata from existing PDFs via ExtractImagesFromPage / ExtractImagesFromAllPages
  • Form fields (AcroForm) — add interactive form fields (text, checkbox, dropdown, radio, button, signature) via AddFormField / AddTextField / AddCheckbox / AddDropdown
  • Digital signatures — sign PDFs with PKCS#7 and verify signatures via SignPDF / VerifySignature
  • Draw lines, ovals, rectangles (with rounded corners), curves, polygons, polylines, sectors
  • Draw images (JPEG, PNG) with mask, crop, rotation, and transparency
  • Password protection
  • Font kerning
  • Import existing PDF pages
  • Table layout
  • Header / footer callbacks
  • Trim-box support
  • Placeholder text (fill-in-later pattern)

Installation

go get -u github.com/VantageDataChat/GoPDF2

Quick Start

Print Text

package main

import (
    "log"
    "github.com/VantageDataChat/GoPDF2"
)

func main() {
    pdf := gopdf.GoPdf{}
    pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
    pdf.AddPage()

    if err := pdf.AddTTFFont("myfont", "path/to/font.ttf"); err != nil {
        log.Fatal(err)
    }
    if err := pdf.SetFont("myfont", "", 14); err != nil {
        log.Fatal(err)
    }

    pdf.Cell(nil, "Hello, World!")
    pdf.WritePdf("hello.pdf")
}

InsertHTMLBox — Render HTML into PDF

The signature:

func (gp *GoPdf) InsertHTMLBox(x, y, w, h float64, htmlStr string, opt HTMLBoxOption) (float64, error)

Example:

package main

import (
    "log"
    "github.com/VantageDataChat/GoPDF2"
)

func main() {
    pdf := gopdf.GoPdf{}
    pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
    pdf.AddPage()

    // Load fonts — only glyphs actually used will be embedded (subset)
    if err := pdf.AddTTFFont("regular", "NotoSansSC-Regular.ttf"); err != nil {
        log.Fatal(err)
    }
    if err := pdf.AddTTFFontWithOption("bold", "NotoSansSC-Bold.ttf", gopdf.TtfOption{Style: gopdf.Bold}); err != nil {
        log.Fatal(err)
    }

    html := `
    <h2>GoPDF2 HTML Rendering</h2>
    <p>Supports <b>bold</b>, <i>italic</i>, <u>underline</u> and
       <font color="#e74c3c">colored text</font>.</p>
    <ul>
        <li>Auto line wrapping</li>
        <li>Ordered/unordered lists</li>
        <li>Image insertion</li>
    </ul>
    <hr/>
    <p style="font-size:10pt; color:gray">
        Font subsetting — only characters actually used are embedded.
    </p>`

    endY, err := pdf.InsertHTMLBox(40, 40, 515, 750, html, gopdf.HTMLBoxOption{
        DefaultFontFamily: "regular",
        DefaultFontSize:   12,
        BoldFontFamily:    "bold",
    })
    if err != nil {
        log.Fatal(err)
    }
    _ = endY // Y position after rendered content

    pdf.WritePdf("html_example.pdf")
}
HTMLBoxOption
Field Type Description
DefaultFontFamily string Font family when HTML does not specify one (required)
DefaultFontSize float64 Default font size in points (default 12)
DefaultColor [3]uint8 Default text color {R, G, B}
LineSpacing float64 Extra line spacing in document units
BoldFontFamily string Font family for <b> / <strong>
ItalicFontFamily string Font family for <i> / <em>
BoldItalicFontFamily string Font family for bold+italic
Supported HTML Tags
Tag Effect
<b>, <strong> Bold
<i>, <em> Italic
<u> Underline
<br> Line break
<p>, <div> Paragraph
<h1><h6> Headings
<font color="..." size="..." face="..."> Font styling
<span style="..."> Inline CSS (color, font-size, font-family, font-weight, font-style, text-decoration, text-align)
<img src="..." width="..." height="..."> Image (local file path)
<ul>, <ol>, <li> Lists
<hr> Horizontal rule
<center> Centered text
<a href="..."> Link (blue underlined text)
<blockquote> Indented block
<sub>, <sup> Subscript / superscript

Font Subsetting & File Size

GoPDF2 uses font subsetting by default. When you call AddTTFFont, the full TTF is parsed, but only the glyphs for characters actually used in the document are embedded in the output PDF. This is especially important for CJK fonts which can be 10-20 MB — the resulting PDF will only contain the few KB needed for the characters you used.

No extra configuration is needed; subsetting is automatic.

Text Color

// RGB
pdf.SetTextColor(156, 197, 140)
pdf.Cell(nil, "colored text")

// CMYK
pdf.SetTextColorCMYK(0, 6, 14, 0)
pdf.Cell(nil, "CMYK text")

Image

pdf.Image("gopher.jpg", 200, 50, nil)
pdf.SetXY(30, 40)
pdf.Text("Link to example.com")
pdf.AddExternalLink("http://example.com/", 27.5, 28, 125, 15)
pdf.AddHeader(func() {
    pdf.SetY(5)
    pdf.Cell(nil, "header")
})
pdf.AddFooter(func() {
    pdf.SetY(825)
    pdf.Cell(nil, "footer")
})

Drawing

// Line
pdf.SetLineWidth(2)
pdf.SetLineType("dashed")
pdf.Line(10, 30, 585, 30)

// Oval
pdf.Oval(100, 200, 500, 500)

// Polygon
pdf.SetStrokeColor(255, 0, 0)
pdf.SetFillColor(0, 255, 0)
pdf.Polygon([]gopdf.Point{{X: 10, Y: 30}, {X: 585, Y: 200}, {X: 585, Y: 250}}, "DF")

// Rounded rectangle
pdf.Rectangle(196.6, 336.8, 398.3, 379.3, "DF", 3, 10)

// Polyline (open path, not closed)
pdf.SetStrokeColor(0, 0, 255)
pdf.Polyline([]gopdf.Point{{X: 10, Y: 400}, {X: 100, Y: 350}, {X: 200, Y: 420}, {X: 300, Y: 380}})

// Sector (pie/fan shape)
pdf.SetFillColor(255, 128, 0)
pdf.Sector(300, 500, 80, 0, 90, "FD")

Rotation

pdf.Rotate(270.0, 100.0, 100.0)
pdf.Text("rotated")
pdf.RotateReset()

Transparency

pdf.SetTransparency(gopdf.Transparency{Alpha: 0.5, BlendModeType: ""})

Password Protection

pdf.Start(gopdf.Config{
    PageSize: *gopdf.PageSizeA4,
    Protection: gopdf.PDFProtectionConfig{
        UseProtection: true,
        Permissions:   gopdf.PermissionsPrint | gopdf.PermissionsCopy | gopdf.PermissionsModify,
        OwnerPass:     []byte("owner"),
        UserPass:      []byte("user"),
    },
})

Import Existing PDF

tpl := pdf.ImportPage("existing.pdf", 1, "/MediaBox")
pdf.UseImportedTemplate(tpl, 50, 100, 400, 0)

Open and Modify Existing PDF

OpenPDF loads an existing PDF so you can draw new content on top of every page:

pdf := gopdf.GoPdf{}
err := pdf.OpenPDF("input.pdf", nil)
if err != nil {
    log.Fatal(err)
}

pdf.AddTTFFont("myfont", "font.ttf")
pdf.SetFont("myfont", "", 14)

// Draw on page 1
pdf.SetPage(1)
pdf.SetXY(100, 100)
pdf.Cell(nil, "Watermark text")

// Draw on page 2
pdf.SetPage(2)
pdf.SetXY(200, 200)
pdf.Image("stamp.png", 200, 200, nil)

pdf.WritePdf("output.pdf")

Also available as OpenPDFFromBytes(data, opt) and OpenPDFFromStream(rs, opt).

Table

table := pdf.NewTableLayout(10, 10, 25, 5)
table.AddColumn("CODE", 50, "left")
table.AddColumn("DESCRIPTION", 200, "left")
table.AddRow([]string{"001", "Product A"})
table.DrawTable()

Placeholder Text

pdf.PlaceHolderText("total", 30)
// ... after all pages created ...
pdf.FillInPlaceHoldText("total", "5", gopdf.Left)

Watermark

Add text or image watermarks to PDF pages:

// Single centered text watermark
pdf.SetPage(1)
pdf.AddWatermarkText(gopdf.WatermarkOption{
    Text:       "CONFIDENTIAL",
    FontFamily: "myfont",
    FontSize:   48,
    Opacity:    0.3,
    Angle:      45,
    Color:      [3]uint8{200, 200, 200},
})

// Tiled text watermark across the page
pdf.AddWatermarkText(gopdf.WatermarkOption{
    Text:       "DRAFT",
    FontFamily: "myfont",
    Repeat:     true,
})

// Apply text watermark to all pages
pdf.AddWatermarkTextAllPages(gopdf.WatermarkOption{
    Text:       "SAMPLE",
    FontFamily: "myfont",
})

// Image watermark (centered, 30% opacity)
pdf.AddWatermarkImage("logo.png", 0.3, 200, 200, 0)

Annotations

Add PDF annotations (sticky notes, highlights, shapes, free text):

// Sticky note
pdf.AddTextAnnotation(100, 100, "Reviewer", "Please check this section.")

// Highlight
pdf.AddHighlightAnnotation(50, 50, 200, 20, [3]uint8{255, 255, 0})

// Free text directly on the page
pdf.AddFreeTextAnnotation(100, 200, 250, 30, "Important note", 14)

// Full control via AddAnnotation
pdf.AddAnnotation(gopdf.AnnotationOption{
    Type:    gopdf.AnnotSquare,
    X:       50,
    Y:       300,
    W:       100,
    H:       50,
    Color:   [3]uint8{0, 0, 255},
    Content: "Review area",
})

Page Manipulation

Extract, merge, delete, and copy pages:

// Extract specific pages from a PDF
newPdf, _ := gopdf.ExtractPages("input.pdf", []int{1, 3, 5}, nil)
newPdf.WritePdf("pages_1_3_5.pdf")

// Merge multiple PDFs
merged, _ := gopdf.MergePages([]string{"doc1.pdf", "doc2.pdf"}, nil)
merged.WritePdf("merged.pdf")

// Delete a page (1-based)
pdf.DeletePage(2)

// Batch delete multiple pages
pdf.DeletePages([]int{2, 4, 6})

// Move a page to a new position
pdf.MovePage(3, 1) // move page 3 to become page 1

// Copy a page to the end
newPageNo, _ := pdf.CopyPage(1)

Page Inspection

Query page sizes and metadata:

// Get page size of a specific page
w, h, _ := pdf.GetPageSize(1)

// Get all page sizes
sizes := pdf.GetAllPageSizes()

// Get page count from a source PDF without importing
count, _ := gopdf.GetSourcePDFPageCount("input.pdf")

// Get page sizes from a source PDF
pageSizes, _ := gopdf.GetSourcePDFPageSizes("input.pdf")

Paper Sizes

Use predefined paper sizes by name:

// Look up paper size by name (case-insensitive)
size := gopdf.PaperSize("a5")
pdf.Start(gopdf.Config{PageSize: *size})

// Landscape variant
sizeL := gopdf.PaperSize("a4-l")

// Available: a0–a10, b0–b10, letter, legal, tabloid, ledger,
// statement, executive, folio, quarto (append "-l" for landscape)
names := gopdf.PaperSizeNames()

Page Rotation

Set display rotation for pages (does not modify content):

pdf.SetPageRotation(1, 90)   // rotate page 1 by 90° clockwise
pdf.SetPageRotation(2, 180)  // rotate page 2 by 180°

angle, _ := pdf.GetPageRotation(1) // returns 90

Page CropBox

Define the visible area of a page (content outside is clipped but not removed):

// Set crop box on page 1 — only the defined area is visible
pdf.SetPageCropBox(1, gopdf.Box{Left: 50, Top: 50, Right: 545, Bottom: 792})

// Get the current crop box
box, _ := pdf.GetPageCropBox(1)

// Remove crop box, restoring full MediaBox visibility
pdf.ClearPageCropBox(1)

Page Reordering

Rearrange, duplicate, or subset pages:

// Reverse page order of current document
newPdf, _ := pdf.SelectPages([]int{3, 2, 1})
newPdf.WritePdf("reversed.pdf")

// Select specific pages from a file
newPdf, _ = gopdf.SelectPagesFromFile("input.pdf", []int{1, 3, 5}, nil)

// Duplicate a page
newPdf, _ = pdf.SelectPages([]int{1, 1, 1})

Embedded Files

Attach files to the PDF (shown in viewer's attachment panel):

data, _ := os.ReadFile("report.csv")
pdf.AddEmbeddedFile(gopdf.EmbeddedFile{
    Name:        "report.csv",
    Content:     data,
    MimeType:    "text/csv",
    Description: "Monthly report data",
})

Content Element CRUD

List, query, delete, modify, and add individual content elements on any page:

// List all elements on page 1
elements, _ := pdf.GetPageElements(1)
for _, e := range elements {
    fmt.Printf("[%d] %s at (%.1f, %.1f)\n", e.Index, e.Type, e.X, e.Y)
}

// Get only text elements
texts, _ := pdf.GetPageElementsByType(1, gopdf.ElementText)

// Delete a specific element by index
pdf.DeleteElement(1, 0)

// Delete all lines from a page
removed, _ := pdf.DeleteElementsByType(1, gopdf.ElementLine)

// Delete elements within a rectangular area
pdf.DeleteElementsInRect(1, 0, 0, 100, 100)

// Clear all content from a page
pdf.ClearPage(1)

// Modify text content
pdf.ModifyTextElement(1, 0, "New text")

// Move an element to a new position
pdf.ModifyElementPosition(1, 0, 200, 300)

// Insert new elements on an existing page
pdf.InsertLineElement(1, 10, 400, 500, 400)
pdf.InsertRectElement(1, 50, 420, 200, 50, "DF")
pdf.InsertOvalElement(1, 300, 420, 450, 470)

PDF Version Control

Set the output PDF version:

pdf.SetPDFVersion(gopdf.PDFVersion20) // output PDF 2.0
v := pdf.GetPDFVersion()              // returns PDFVersion20

Garbage Collection

Remove null/deleted objects to reduce file size:

pdf.DeletePage(2)
removed := pdf.GarbageCollect(gopdf.GCCompact)
fmt.Printf("Removed %d unused objects\n", removed)

Page Labels

Define custom page numbering displayed in PDF viewers:

pdf.SetPageLabels([]gopdf.PageLabel{
    {PageIndex: 0, Style: gopdf.PageLabelRomanLower, Start: 1},  // i, ii, iii
    {PageIndex: 3, Style: gopdf.PageLabelDecimal, Start: 1},     // 1, 2, 3, ...
    {PageIndex: 10, Style: gopdf.PageLabelAlphaUpper, Prefix: "Appendix ", Start: 1},
})

XMP Metadata

Embed rich XMP metadata (Dublin Core, PDF/A conformance, etc.):

pdf.SetXMPMetadata(gopdf.XMPMetadata{
    Title:       "Annual Report 2025",
    Creator:     []string{"John Doe"},
    Description: "Company annual report",
    Subject:     []string{"finance", "report"},
    CreatorTool: "GoPDF2",
    Producer:    "GoPDF2",
    CreateDate:  time.Now(),
    ModifyDate:  time.Now(),
    PDFAPart:    1,
    PDFAConformance: "B",
})

Incremental Save

Save only modified objects for fast updates on large documents:

originalData, _ := os.ReadFile("input.pdf")
pdf := gopdf.GoPdf{}
pdf.OpenPDFFromBytes(originalData, nil)
pdf.SetPage(1)
pdf.SetXY(100, 100)
pdf.Text("Added text")

result, _ := pdf.IncrementalSave(originalData, nil)
os.WriteFile("output.pdf", result, 0644)

Document Cloning

Deep copy a document for independent modifications:

clone, _ := pdf.Clone()
clone.SetPage(1)
clone.SetXY(100, 100)
clone.Text("Only in clone")
clone.WritePdf("clone.pdf")

Document Scrubbing

Remove sensitive metadata and attachments from a PDF:

pdf.Scrub(gopdf.DefaultScrubOption())
pdf.GarbageCollect(gopdf.GCCompact)
pdf.WritePdf("scrubbed.pdf")

// Selective scrubbing
pdf.Scrub(gopdf.ScrubOption{
    Metadata:    true,
    XMLMetadata: true,
})

Optional Content Groups (Layers)

Add PDF layers for selective visibility:

watermark := pdf.AddOCG(gopdf.OCG{
    Name:   "Watermark",
    Intent: gopdf.OCGIntentView,
    On:     true,
})

draft := pdf.AddOCG(gopdf.OCG{
    Name:   "Draft Notes",
    Intent: gopdf.OCGIntentDesign,
    On:     false,
})

layers := pdf.GetOCGs()

Page Layout & Page Mode

Control how the PDF viewer displays the document:

// Set page layout
pdf.SetPageLayout(gopdf.PageLayoutTwoColumnLeft)
layout := pdf.GetPageLayout()

// Set page mode (which panel opens)
pdf.SetPageMode(gopdf.PageModeUseOutlines) // show bookmarks panel
mode := pdf.GetPageMode()

Document Statistics

Inspect document structure:

stats := pdf.GetDocumentStats()
fmt.Printf("Pages: %d, Fonts: %d, Images: %d\n",
    stats.PageCount, stats.FontCount, stats.ImageCount)

fonts := pdf.GetFonts()
for _, f := range fonts {
    fmt.Printf("Font: %s, Embedded: %v\n", f.Family, f.IsEmbedded)
}

TOC / Bookmarks

Read and write hierarchical outline trees:

// Set a hierarchical TOC
pdf.SetTOC([]gopdf.TOCItem{
    {Level: 1, Title: "Chapter 1", PageNo: 1},
    {Level: 2, Title: "Section 1.1", PageNo: 1, Y: 200},
    {Level: 2, Title: "Section 1.2", PageNo: 2},
    {Level: 1, Title: "Chapter 2", PageNo: 3},
})

// Read back the TOC
toc := pdf.GetTOC()
for _, item := range toc {
    fmt.Printf("L%d: %s -> page %d\n", item.Level, item.Title, item.PageNo)
}

API Reference

See docs/API.md (English) or docs/API_zh.md (中文).

GoPDF2 vs PyMuPDF

See docs/COMPARISON.md (English) or docs/COMPARISON_zh.md (中文) for a detailed feature comparison.

Changelog

See CHANGELOG.md for version history.

License

MIT

Documentation

Index

Examples

Constants

View Source
const (
	UnitUnset = iota // No units were set, when conversion is called on nothing will happen
	UnitPT           // Points
	UnitMM           // Millimeters
	UnitCM           // Centimeters
	UnitIN           // Inches
	UnitPX           // Pixels

)

The units that can be used in the document

View Source
const (
	Unit_Unset = UnitUnset // No units were set, when conversion is called on nothing will happen
	Unit_PT    = UnitPT    // Points
	Unit_MM    = UnitMM    // Millimeters
	Unit_CM    = UnitCM    // Centimeters
	Unit_IN    = UnitIN    // Inches
	Unit_PX    = UnitPX    // Pixels
)

The units that can be used in the document (for backward compatibility) Deprecated: Use UnitUnset,UnitPT,UnitMM,UnitCM,UnitIN instead

View Source
const (
	//PermissionsPrint setProtection print
	PermissionsPrint = 4
	//PermissionsModify setProtection modify
	PermissionsModify = 8
	//PermissionsCopy setProtection copy
	PermissionsCopy = 16
	//PermissionsAnnotForms setProtection  annot-forms
	PermissionsAnnotForms = 32
)
View Source
const (
	SMaskAlphaSubtype      = "/Alpha"
	SMaskLuminositySubtype = "/Luminosity"
)
View Source
const AllBorders = 15 //001111

AllBorders allborders

View Source
const Bold = 2 //000010

Bold - font style bold

View Source
const Bottom = 1 //000001

Bottom bottom

View Source
const Center = 16 //010000

Center center

View Source
const ContentTypeCell = 0

ContentTypeCell cell

View Source
const ContentTypeText = 1

ContentTypeText text

View Source
const DefaultAplhaValue = 1
View Source
const (
	DeviceGray = "DeviceGray"
)
View Source
const Italic = 1 //000001

Italic - font style italic

View Source
const Left = 8 //001000

Left left

View Source
const Middle = 32 //100000

Middle middle

View Source
const Regular = 0 //000000

Regular - font style regular

View Source
const Right = 2 //000010

Right right

View Source
const Top = 4 //000100

Top top

View Source
const Underline = 4 //000100

Underline - font style underline

View Source
const Version = "1.0.0"

Version is the current version of the GoPDF2 library.

Variables

View Source
var (
	ALEF_HAMZA_ABOVE = Harf{
		Unicode:   '\u0623',
		Isolated:  '\ufe83',
		Beginning: '\u0623',
		Middle:    '\ufe84',
		Final:     '\ufe84'}

	ALEF = Harf{
		Unicode:   '\u0627',
		Isolated:  '\ufe8d',
		Beginning: '\u0627',
		Middle:    '\ufe8e',
		Final:     '\ufe8e'}

	ALEF_MADDA_ABOVE = Harf{
		Unicode:   '\u0622',
		Isolated:  '\ufe81',
		Beginning: '\u0622',
		Middle:    '\ufe82',
		Final:     '\ufe82'}

	HAMZA = Harf{
		Unicode:   '\u0621',
		Isolated:  '\ufe80',
		Beginning: '\u0621',
		Middle:    '\u0621',
		Final:     '\u0621'}

	WAW_HAMZA_ABOVE = Harf{
		Unicode:   '\u0624',
		Isolated:  '\ufe85',
		Beginning: '\u0624',
		Middle:    '\ufe86',
		Final:     '\ufe86'}

	ALEF_HAMZA_BELOW = Harf{
		Unicode:   '\u0625',
		Isolated:  '\ufe87',
		Beginning: '\u0625',
		Middle:    '\ufe88',
		Final:     '\ufe88'}

	YEH_HAMZA_ABOVE = Harf{
		Unicode:   '\u0626',
		Isolated:  '\ufe89',
		Beginning: '\ufe8b',
		Middle:    '\ufe8c',
		Final:     '\ufe8a'}

	BEH = Harf{
		Unicode:   '\u0628',
		Isolated:  '\ufe8f',
		Beginning: '\ufe91',
		Middle:    '\ufe92',
		Final:     '\ufe90'}

	PEH = Harf{
		Unicode:   '\u067e',
		Isolated:  '\ufb56',
		Beginning: '\ufb58',
		Middle:    '\ufb59',
		Final:     '\ufb57'}

	TEH = Harf{
		Unicode:   '\u062A',
		Isolated:  '\ufe95',
		Beginning: '\ufe97',
		Middle:    '\ufe98',
		Final:     '\ufe96'}

	TEH_MARBUTA = Harf{
		Unicode:   '\u0629',
		Isolated:  '\ufe93',
		Beginning: '\u0629',
		Middle:    '\u0629',
		Final:     '\ufe94'}

	THEH = Harf{
		Unicode:   '\u062b',
		Isolated:  '\ufe99',
		Beginning: '\ufe9b',
		Middle:    '\ufe9c',
		Final:     '\ufe9a'}

	JEEM = Harf{
		Unicode:   '\u062c',
		Isolated:  '\ufe9d',
		Beginning: '\ufe9f',
		Middle:    '\ufea0',
		Final:     '\ufe9e'} // ـج

	TCHEH = Harf{
		Unicode:   '\u0686',
		Isolated:  '\ufb7a',
		Beginning: '\ufb7c',
		Middle:    '\ufb7d',
		Final:     '\ufb7b'}

	HAH = Harf{
		Unicode:   '\u062d',
		Isolated:  '\ufea1',
		Beginning: '\ufea3',
		Middle:    '\ufea4',
		Final:     '\ufea2'}

	KHAH = Harf{
		Unicode:   '\u062e',
		Isolated:  '\ufea5',
		Beginning: '\ufea7',
		Middle:    '\ufea8',
		Final:     '\ufea6'}

	DAL = Harf{
		Unicode:   '\u062f',
		Isolated:  '\ufea9',
		Beginning: '\u062f',
		Middle:    '\ufeaa',
		Final:     '\ufeaa'}

	THAL = Harf{
		Unicode:   '\u0630',
		Isolated:  '\ufeab',
		Beginning: '\u0630',
		Middle:    '\ufeac',
		Final:     '\ufeac'}

	REH = Harf{
		Unicode:   '\u0631',
		Isolated:  '\ufead',
		Beginning: '\u0631',
		Middle:    '\ufeae',
		Final:     '\ufeae'}

	JEH = Harf{
		Unicode:   '\u0698',
		Isolated:  '\ufb8a',
		Beginning: '\u0698',
		Middle:    '\ufb8b',
		Final:     '\ufb8b',
	}

	ZAIN = Harf{
		Unicode:   '\u0632',
		Isolated:  '\ufeaf',
		Beginning: '\u0632',
		Middle:    '\ufeb0',
		Final:     '\ufeb0'}

	SEEN = Harf{
		Unicode:   '\u0633',
		Isolated:  '\ufeb1',
		Beginning: '\ufeb3',
		Middle:    '\ufeb4',
		Final:     '\ufeb2'}

	SHEEN = Harf{
		Unicode:   '\u0634',
		Isolated:  '\ufeb5',
		Beginning: '\ufeb7',
		Middle:    '\ufeb8',
		Final:     '\ufeb6'}

	SAD = Harf{
		Unicode:   '\u0635',
		Isolated:  '\ufeb9',
		Beginning: '\ufebb',
		Middle:    '\ufebc',
		Final:     '\ufeba'}

	DAD = Harf{
		Unicode:   '\u0636',
		Isolated:  '\ufebd',
		Beginning: '\ufebf',
		Middle:    '\ufec0',
		Final:     '\ufebe'}

	TAH = Harf{
		Unicode:   '\u0637',
		Isolated:  '\ufec1',
		Beginning: '\ufec3',
		Middle:    '\ufec4',
		Final:     '\ufec2'}

	ZAH = Harf{
		Unicode:   '\u0638',
		Isolated:  '\ufec5',
		Beginning: '\ufec7',
		Middle:    '\ufec8',
		Final:     '\ufec6'}

	AIN = Harf{
		Unicode:   '\u0639',
		Isolated:  '\ufec9',
		Beginning: '\ufecb',
		Middle:    '\ufecc',
		Final:     '\ufeca'}

	GHAIN = Harf{
		Unicode:   '\u063a',
		Isolated:  '\ufecd',
		Beginning: '\ufecf',
		Middle:    '\ufed0',
		Final:     '\ufece'}

	FEH = Harf{
		Unicode:   '\u0641',
		Isolated:  '\ufed1',
		Beginning: '\ufed3',
		Middle:    '\ufed4',
		Final:     '\ufed2'}

	QAF = Harf{
		Unicode:   '\u0642',
		Isolated:  '\ufed5',
		Beginning: '\ufed7',
		Middle:    '\ufed8',
		Final:     '\ufed6'}

	KAF = Harf{
		Unicode:   '\u0643',
		Isolated:  '\ufed9',
		Beginning: '\ufedb',
		Middle:    '\ufedc',
		Final:     '\ufeda'}

	KEHEH = Harf{
		Unicode:   '\u06a9',
		Isolated:  '\ufb8e',
		Beginning: '\ufb90',
		Middle:    '\ufb91',
		Final:     '\ufb8f',
	}

	GAF = Harf{
		Unicode:   '\u06af',
		Isolated:  '\ufb92',
		Beginning: '\ufb94',
		Middle:    '\ufb95',
		Final:     '\ufb93'}

	LAM = Harf{
		Unicode:   '\u0644',
		Isolated:  '\ufedd',
		Beginning: '\ufedf',
		Middle:    '\ufee0',
		Final:     '\ufede'}

	MEEM = Harf{
		Unicode:   '\u0645',
		Isolated:  '\ufee1',
		Beginning: '\ufee3',
		Middle:    '\ufee4',
		Final:     '\ufee2'}

	NOON = Harf{
		Unicode:   '\u0646',
		Isolated:  '\ufee5',
		Beginning: '\ufee7',
		Middle:    '\ufee8',
		Final:     '\ufee6'}

	HEH = Harf{
		Unicode:   '\u0647',
		Isolated:  '\ufee9',
		Beginning: '\ufeeb',
		Middle:    '\ufeec',
		Final:     '\ufeea'}

	WAW = Harf{
		Unicode:   '\u0648',
		Isolated:  '\ufeed',
		Beginning: '\u0648',
		Middle:    '\ufeee',
		Final:     '\ufeee'}

	YEH = Harf{
		Unicode:   '\u06cc',
		Isolated:  '\ufbfc',
		Beginning: '\ufbfe',
		Middle:    '\ufbff',
		Final:     '\ufbfd'}

	ARABICYEH = Harf{
		Unicode:   '\u064a',
		Isolated:  '\ufef1',
		Beginning: '\ufef3',
		Middle:    '\ufef4',
		Final:     '\ufef2'}

	ALEF_MAKSURA = Harf{
		Unicode:   '\u0649',
		Isolated:  '\ufeef',
		Beginning: '\u0649',
		Middle:    '\ufef0',
		Final:     '\ufef0'}

	TATWEEL = Harf{
		Unicode:   '\u0640',
		Isolated:  '\u0640',
		Beginning: '\u0640',
		Middle:    '\u0640',
		Final:     '\u0640'}

	LAM_ALEF = Harf{
		Unicode:   '\ufefb',
		Isolated:  '\ufefb',
		Beginning: '\ufefb',
		Middle:    '\ufefc',
		Final:     '\ufefc'}

	LAM_ALEF_HAMZA_ABOVE = Harf{
		Unicode:   '\ufef7',
		Isolated:  '\ufef7',
		Beginning: '\ufef7',
		Middle:    '\ufef8',
		Final:     '\ufef8'}
)

Arabic Alphabet using the new Harf type.

View Source
var (
	ErrBookmarkNotFound   = errors.New("bookmark not found")
	ErrBookmarkOutOfRange = errors.New("bookmark index out of range")
)
View Source
var (
	ErrElementIndexOutOfRange = errors.New("element index out of range")
	ErrElementTypeMismatch    = errors.New("element type mismatch")
	ErrContentObjNotFound     = errors.New("content object not found for page")
)
View Source
var (
	ErrPageOutOfRange = errors.New("page number out of range")
	ErrNoPages        = errors.New("document has no pages")
)
View Source
var (
	PageSizeA6  = &Rect{W: 298, H: 420, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA7  = &Rect{W: 210, H: 298, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA8  = &Rect{W: 148, H: 210, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA9  = &Rect{W: 105, H: 148, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA10 = &Rect{W: 74, H: 105, unitOverride: defaultUnitConfig{Unit: UnitPT}}
)

ISO A-series (portrait)

View Source
var (
	PageSizeA0Landscape  = &Rect{W: 3371, H: 2384, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA1Landscape  = &Rect{W: 2384, H: 1685, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA2Landscape  = &Rect{W: 1684, H: 1190, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA5Landscape  = &Rect{W: 595, H: 420, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA6Landscape  = &Rect{W: 420, H: 298, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA7Landscape  = &Rect{W: 298, H: 210, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA8Landscape  = &Rect{W: 210, H: 148, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA9Landscape  = &Rect{W: 148, H: 105, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeA10Landscape = &Rect{W: 105, H: 74, unitOverride: defaultUnitConfig{Unit: UnitPT}}
)

ISO A-series landscape

View Source
var (
	PageSizeB0 = &Rect{W: 2835, H: 4008, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeB1 = &Rect{W: 2004, H: 2835, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeB2 = &Rect{W: 1417, H: 2004, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeB3 = &Rect{W: 1001, H: 1417, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	// B4 and B5 already defined in page_sizes.go
	PageSizeB6  = &Rect{W: 363, H: 516, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeB7  = &Rect{W: 258, H: 363, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeB8  = &Rect{W: 181, H: 258, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeB9  = &Rect{W: 127, H: 181, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeB10 = &Rect{W: 91, H: 127, unitOverride: defaultUnitConfig{Unit: UnitPT}}
)

ISO B-series

View Source
var (
	PageSizeLetterLandscape = &Rect{W: 792, H: 612, unitOverride: defaultUnitConfig{Unit: UnitPT}}
	PageSizeLegalLandscape  = &Rect{W: 1008, H: 612, unitOverride: defaultUnitConfig{Unit: UnitPT}}
)

US sizes

View Source
var (
	ErrEncryptedPDF      = errors.New("PDF is encrypted; call OpenPDF with Password option")
	ErrInvalidPassword   = errors.New("invalid password")
	ErrUnsupportedCrypto = errors.New("unsupported encryption version (only V1/V2 R2/R3 supported)")
)
View Source
var (
	ErrSVGParseFailed = errors.New("failed to parse SVG")
	ErrSVGEmpty       = errors.New("SVG contains no renderable elements")
)
View Source
var (
	// DefaultBreakOption will cause the text to break mid-word without any separator suffixes.
	DefaultBreakOption = BreakOption{
		Mode:           BreakModeStrict,
		BreakIndicator: 0,
		Separator:      "",
	}
)
View Source
var EntrySelectors = []int{
	0, 0, 1, 1, 2, 2,
	2, 2, 3, 3, 3, 3,
	3, 3, 3, 3, 4, 4,
	4, 4, 4, 4, 4, 4,
	4, 4, 4, 4, 4, 4, 4,
}

EntrySelectors entry selectors

View Source
var ErrAnnotationNotFound = errors.New("annotation not found at specified index")
View Source
var ErrCharNotFound = errors.New("char not found")

ErrCharNotFound char not found

View Source
var ErrContentTypeNotFound = errors.New("contentType not found")
View Source
var ErrEmbeddedFileNotFound = errors.New("embedded file not found")

ErrEmbeddedFileNotFound is returned when the specified embedded file name does not exist.

View Source
var ErrEmptyString = errors.New("empty string")
View Source
var ErrExistsColorSpace = errors.New("color space already exists")
View Source
var ErrFontNotFound = errors.New("font not found")

ErrFontNotFound occurs when the specified font family is not found in the container.

View Source
var ErrGlyphNotFound = errors.New("glyph not found")

ErrGlyphNotFound font file not contain glyph

View Source
var ErrInvalidRectangleCoordinates = errors.New("Invalid coordinates for the rectangle")
View Source
var ErrInvalidRectangleRadius = errors.New("Radius length cannot exceed rectangle height or width")
View Source
var ErrInvalidRotation = errors.New("rotation must be a multiple of 90 degrees (0, 90, 180, 270)")

ErrInvalidRotation is returned when a rotation angle is not a multiple of 90.

View Source
var ErrInvalidTOCLevel = errorf("invalid TOC level: first item must be level 1, and levels may increase by at most 1")

ErrInvalidTOCLevel is returned when TOC items have invalid hierarchy levels.

View Source
var ErrMissingColorSpace = errors.New("color space not found")
View Source
var ErrMissingFontFamily = errors.New("font family not found")
View Source
var ErrNotSupportShortIndexYet = errors.New("not support none short index yet")

ErrNotSupportShortIndexYet not support none short index yet

View Source
var ErrUndefinedCacheContentImage = errors.New("cacheContentImage is undefined")
View Source
var PageSize10x14 = &Rect{W: 720, H: 1008, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSize10x14 page format

View Source
var PageSizeA0 = &Rect{W: 2384, H: 3371, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA0 page format

View Source
var PageSizeA1 = &Rect{W: 1685, H: 2384, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA1 page format

View Source
var PageSizeA2 = &Rect{W: 1190, H: 1684, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA2 page format

View Source
var PageSizeA3 = &Rect{W: 842, H: 1190, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA3 page format

View Source
var PageSizeA3Landscape = &Rect{W: 1190, H: 842, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA3Landscape page format

View Source
var PageSizeA4 = &Rect{W: 595, H: 842, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA4 page format

View Source
var PageSizeA4Landscape = &Rect{W: 842, H: 595, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA4Landscape page format

View Source
var PageSizeA4Small = &Rect{W: 595, H: 842, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA4Small page format

View Source
var PageSizeA5 = &Rect{W: 420, H: 595, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeA5 page format

View Source
var PageSizeB4 = &Rect{W: 729, H: 1032, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeB4 page format

View Source
var PageSizeB5 = &Rect{W: 516, H: 729, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeB5 page format

View Source
var PageSizeExecutive = &Rect{W: 540, H: 720, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeExecutive page format

View Source
var PageSizeFolio = &Rect{W: 612, H: 936, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeFolio page format

View Source
var PageSizeLedger = &Rect{W: 1224, H: 792, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeLedger page format

View Source
var PageSizeLegal = &Rect{W: 612, H: 1008, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeLegal page format

View Source
var PageSizeLetter = &Rect{W: 612, H: 792, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeLetter page format

View Source
var PageSizeLetterSmall = &Rect{W: 612, H: 792, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeLetterSmall page format

View Source
var PageSizeQuarto = &Rect{W: 610, H: 780, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeQuarto page format

View Source
var PageSizeStatement = &Rect{W: 396, H: 612, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeStatement page format

View Source
var PageSizeTabloid = &Rect{W: 792, H: 1224, unitOverride: defaultUnitConfig{Unit: UnitPT}}

PageSizeTabloid page format

Functions

func CheckSum

func CheckSum(data []byte) uint

CheckSum check sum

func CleanContentStreams

func CleanContentStreams(pdfData []byte) ([]byte, error)

CleanContentStreams optimizes all content streams in the given PDF data by removing redundant operators, consolidating state changes, and normalizing whitespace. Returns the cleaned PDF data.

This is a standalone function that operates on raw PDF bytes, similar to RecompressImages.

Example:

data, _ := os.ReadFile("input.pdf")
cleaned, err := gopdf.CleanContentStreams(data)
os.WriteFile("output.pdf", cleaned, 0644)

func ContentObjCalTextHeight

func ContentObjCalTextHeight(fontsize int) float64

ContentObjCalTextHeight : calculates height of text.

func ContentObjCalTextHeightPrecise

func ContentObjCalTextHeightPrecise(fontsize float64) float64

ContentObjCalTextHeightPrecise : like ContentObjCalTextHeight, but fontsize float64

func ConvertColorspace

func ConvertColorspace(pdfData []byte, opt ConvertColorspaceOption) ([]byte, error)

ConvertColorspace converts all color operators in the PDF content streams to the specified target colorspace. Returns the modified PDF data.

This converts color-setting operators (rg, RG, k, K, g, G) in content streams. It does NOT convert image colorspaces — use RecompressImages for that.

Example:

data, _ := os.ReadFile("input.pdf")
gray, err := gopdf.ConvertColorspace(data, gopdf.ConvertColorspaceOption{
    Target: gopdf.ColorspaceGray,
})
os.WriteFile("grayscale.pdf", gray, 0644)

func CopyObject

func CopyObject(pdfData []byte, objNum int) ([]byte, int, error)

CopyObject duplicates a PDF object and returns the modified PDF data along with the new object number.

Example:

newData, newObjNum, err := gopdf.CopyObject(data, 5)

func CreateEmbeddedFontSubsetName

func CreateEmbeddedFontSubsetName(name string) string

CreateEmbeddedFontSubsetName create Embedded font (subset font) name

func DefaultOnGlyphNotFoundSubstitute

func DefaultOnGlyphNotFoundSubstitute(r rune) rune

func DesignUnitsToPdf

func DesignUnitsToPdf(val int, unitsPerEm uint) int

DesignUnitsToPdf convert unit

func Distance

func Distance(p1, p2 Point) float64

Distance returns the Euclidean distance between two points.

func ExtractAllPagesText

func ExtractAllPagesText(pdfData []byte) (result string, retErr error)

ExtractAllPagesText extracts plain text from all pages of a PDF, returning a single string with page breaks. Uses ledongthuc/pdf for robust parsing of diverse PDF formats.

Example:

data, _ := os.ReadFile("input.pdf")
text, _ := gopdf.ExtractAllPagesText(data)
fmt.Println(text)

func ExtractFontsFromAllPages

func ExtractFontsFromAllPages(pdfData []byte) (map[int][]ExtractedFont, error)

ExtractFontsFromAllPages extracts font information from all pages.

func ExtractImagesFromAllPages

func ExtractImagesFromAllPages(pdfData []byte) (map[int][]ExtractedImage, error)

ExtractImagesFromAllPages extracts images from all pages.

func ExtractPageText

func ExtractPageText(pdfData []byte, pageIndex int) (string, error)

ExtractPageText extracts all text from a page as a single string. Convenience wrapper around ExtractTextFromPage.

func ExtractTextFormatted

func ExtractTextFormatted(pdfData []byte, pageIndex int, format TextExtractionFormat) (interface{}, error)

ExtractTextFormatted extracts text from a page in the specified format.

Supported formats:

  • FormatText: plain text string
  • FormatBlocks: []TextBlock
  • FormatWords: []TextWord
  • FormatHTML: HTML string
  • FormatJSON: JSON string

Example:

data, _ := os.ReadFile("input.pdf")
html, _ := gopdf.ExtractTextFormatted(data, 0, gopdf.FormatHTML)
fmt.Println(html.(string))

func ExtractTextFromAllPages

func ExtractTextFromAllPages(pdfData []byte) (map[int][]ExtractedText, error)

ExtractTextFromAllPages extracts text from all pages.

func FontConvertHelperCw2Str

func FontConvertHelperCw2Str(cw FontCw) string

FontConvertHelperCw2Str converts main ASCII characters of a FontCW to a string.

func FontConvertHelper_Cw2Str

func FontConvertHelper_Cw2Str(cw FontCw) string

FontConvertHelper_Cw2Str converts main ASCII characters of a FontCW to a string. (for backward compatibility) Deprecated: Use FontConvertHelperCw2Str(cw FontCw) instead

func FormatFloatTrim

func FormatFloatTrim(floatval float64) (formatted string)

FormatFloatTrim converts a float64 into a string, like Sprintf("%.3f") but with trailing zeroes (and possibly ".") removed

Example
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.0))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.01))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.001))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.0001))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(10.00001))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.99999))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.9999))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.999))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.99))
fmt.Printf("/F1 %s Tf\n", FormatFloatTrim(9.9))
Output:

/F1 10 Tf
/F1 10 Tf
/F1 10.01 Tf
/F1 10.001 Tf
/F1 10 Tf
/F1 10 Tf
/F1 10 Tf
/F1 10 Tf
/F1 9.999 Tf
/F1 9.99 Tf
/F1 9.9 Tf

func GetBuffer

func GetBuffer() *bytes.Buffer

GetBuffer fetches a buffer from the pool

func GetDictKey

func GetDictKey(pdfData []byte, objNum int, key string) (string, error)

GetDictKey reads a dictionary key value from a PDF object. Returns the raw value string, or empty string if not found.

Example:

val, err := gopdf.GetDictKey(data, 5, "/Type")
// val might be "/Page"

func GetPlainTextReader

func GetPlainTextReader(pdfData []byte) (io.Reader, error)

GetPlainTextReader returns an io.Reader that yields all plain text from the PDF. This is a convenience wrapper around ledongthuc/pdf's Reader.GetPlainText().

func GetSourcePDFPageCount

func GetSourcePDFPageCount(pdfPath string) (int, error)

GetSourcePDFPageCount returns the number of pages in a source PDF file without importing it.

func GetSourcePDFPageCountFromBytes

func GetSourcePDFPageCountFromBytes(pdfData []byte) (int, error)

GetSourcePDFPageCountFromBytes returns the number of pages in a source PDF from a byte slice without importing it.

func GetSourcePDFPageCountV2

func GetSourcePDFPageCountV2(pdfData []byte) (n int, retErr error)

GetSourcePDFPageCountV2 returns the page count using ledongthuc/pdf, which handles more PDF formats than gofpdi.

func GetSourcePDFPageSizes

func GetSourcePDFPageSizes(pdfPath string) (map[int]PageInfo, error)

GetSourcePDFPageSizes returns the page sizes of all pages in a source PDF file. The returned map is keyed by 1-based page number.

func GetSourcePDFPageSizesFromBytes

func GetSourcePDFPageSizesFromBytes(pdfData []byte) (map[int]PageInfo, error)

GetSourcePDFPageSizesFromBytes returns the page sizes from a PDF byte slice.

func GetStream

func GetStream(pdfData []byte, objNum int) ([]byte, error)

GetStream reads the stream data from a PDF object. Returns nil if the object has no stream.

Example:

stream, err := gopdf.GetStream(data, 10)

func GetTrailer

func GetTrailer(pdfData []byte) (string, error)

GetTrailer returns the PDF trailer dictionary as a string.

Example:

trailer, err := gopdf.GetTrailer(data)
fmt.Println(trailer)

func ImgReactagleToWH

func ImgReactagleToWH(imageRect image.Rectangle) (float64, float64)

ImgReactagleToWH Rectangle to W and H

func IsFormPDF

func IsFormPDF(pdfData []byte) bool

IsFormPDF detects whether the given PDF data contains form fields (AcroForm). This is a standalone function that operates on raw PDF bytes.

Example:

data, _ := os.ReadFile("input.pdf")
if gopdf.IsFormPDF(data) {
    fmt.Println("This PDF contains form fields")
}

func LoadCertificateChainFromPEM

func LoadCertificateChainFromPEM(chainPath string) ([]*x509.Certificate, error)

LoadCertificateChainFromPEM loads a chain of certificates from a PEM file.

func LoadCertificateFromPEM

func LoadCertificateFromPEM(certPath string) (*x509.Certificate, error)

LoadCertificateFromPEM loads an X.509 certificate from a PEM file.

func LoadPrivateKeyFromPEM

func LoadPrivateKeyFromPEM(keyPath string) (crypto.Signer, error)

LoadPrivateKeyFromPEM loads a private key (RSA or ECDSA) from a PEM file.

func PaperSizeNames

func PaperSizeNames() []string

PaperSizeNames returns all supported paper size names.

func ParseCertificateChainPEM

func ParseCertificateChainPEM(data []byte) ([]*x509.Certificate, error)

ParseCertificateChainPEM parses a chain of certificates from PEM-encoded data.

func ParseCertificatePEM

func ParseCertificatePEM(data []byte) (*x509.Certificate, error)

ParseCertificatePEM parses an X.509 certificate from PEM-encoded data.

func ParsePrivateKeyPEM

func ParsePrivateKeyPEM(data []byte) (crypto.Signer, error)

ParsePrivateKeyPEM parses a private key from PEM-encoded data. Supports RSA, ECDSA, and PKCS#8 encoded keys.

func PointsToUnits

func PointsToUnits(t int, u float64) float64

PointsToUnits converts points to the provided units

func PointsToUnitsVar

func PointsToUnitsVar(t int, u ...*float64)

PointsToUnitsVar converts points to the provided units for all variables supplied

func PutBuffer

func PutBuffer(buf *bytes.Buffer)

PutBuffer returns a buffer to the pool

func ReadShortFromByte

func ReadShortFromByte(data []byte, offset int) (int64, int)

ReadShortFromByte read short from byte array

func ReadUShortFromByte

func ReadUShortFromByte(data []byte, offset int) (uint64, int)

ReadUShortFromByte read ushort from byte array

func RecompressImages

func RecompressImages(pdfData []byte, opt RecompressOption) ([]byte, error)

RecompressImages recompresses all images in the given PDF data and returns the modified PDF data.

Example:

data, _ := os.ReadFile("input.pdf")
smaller, err := gopdf.RecompressImages(data, gopdf.RecompressOption{
    Format:      "jpeg",
    JPEGQuality: 60,
})
os.WriteFile("output.pdf", smaller, 0644)

func RedactText

func RedactText(pdfData []byte, searchText string, opts *RedactionOptions) ([]byte, int, error)

RedactText searches for text on all pages and applies redaction to matching areas. This is a convenience method that combines SearchText + AddRedactAnnotation + ApplyRedactions.

Example:

data, _ := os.ReadFile("input.pdf")
newData, count, err := gopdf.RedactText(data, "[email]", nil)

func RenderAllPagesToImages

func RenderAllPagesToImages(pdfData []byte, opt RenderOption) ([]image.Image, error)

RenderAllPagesToImages renders all pages to images.

func RenderPageToImage

func RenderPageToImage(pdfData []byte, pageIndex int, opt RenderOption) (image.Image, error)

RenderPageToImage renders a page from raw PDF data to an image.Image. The pageIndex is 0-based. This provides basic rendering of text placeholders, lines, rectangles, and images embedded in the PDF.

Note: This is a lightweight pure-Go renderer. For full-fidelity rendering (fonts, complex paths, transparency), a C-based engine like MuPDF is needed. This renderer is suitable for thumbnails, previews, and simple PDFs.

Example:

data, _ := os.ReadFile("input.pdf")
img, err := gopdf.RenderPageToImage(data, 0, gopdf.RenderOption{DPI: 150})
f, _ := os.Create("page0.png")
png.Encode(f, img)

func Reverse

func Reverse(s string) string

func RotatePageInPDF

func RotatePageInPDF(pdfData []byte, pageIndex int, degrees float64) ([]byte, error)

RotatePageInPDF rotates a page in existing PDF data. pageIndex is 0-based, degrees is clockwise rotation.

func ScalePageInPDF

func ScalePageInPDF(pdfData []byte, pageIndex int, sx, sy float64) ([]byte, error)

ScalePageInPDF scales a page in existing PDF data. pageIndex is 0-based. Returns the modified PDF data.

Example:

data, _ := os.ReadFile("input.pdf")
scaled, _ := gopdf.ScalePageInPDF(data, 0, 0.5, 0.5)
os.WriteFile("output.pdf", scaled, 0644)

func SetDictKey

func SetDictKey(pdfData []byte, objNum int, key, value string) ([]byte, error)

SetDictKey sets or updates a dictionary key in a PDF object. Returns the modified PDF data.

Example:

updated, err := gopdf.SetDictKey(data, 5, "/MediaBox", "[0 0 595 842]")

func SetStream

func SetStream(pdfData []byte, objNum int, streamData []byte) ([]byte, error)

SetStream replaces the stream data in a PDF object. The /Length key in the dictionary is automatically updated.

Example:

updated, err := gopdf.SetStream(data, 10, []byte("BT /F1 12 Tf 100 700 Td (Hello) Tj ET"))

func StrHelperGetStringWidth

func StrHelperGetStringWidth(str string, fontSize int, ifont IFont) float64

StrHelperGetStringWidth get string width

func StrHelperGetStringWidthPrecise

func StrHelperGetStringWidthPrecise(str string, fontSize float64, ifont IFont) float64

StrHelperGetStringWidthPrecise get string width with real number fontSize

func ToArabic

func ToArabic(text string) string

func ToByte

func ToByte(chr string) byte

ToByte returns the first byte of a string.

func TransformPageInPDF

func TransformPageInPDF(pdfData []byte, pageIndex int, opts PageTransformOptions) ([]byte, error)

TransformPageInPDF applies a transformation to a page in existing PDF data.

func UnitsToPoints

func UnitsToPoints(t int, u float64) float64

UnitsToPoints converts units of the provided type to points

func UnitsToPointsVar

func UnitsToPointsVar(t int, u ...*float64)

UnitsToPointsVar converts units of the provided type to points for all variables supplied

func UpdateObject

func UpdateObject(pdfData []byte, objNum int, newContent string) ([]byte, error)

UpdateObject replaces the content of a PDF object and returns the modified PDF. newContent should be the full object body (dictionary + optional stream).

Example:

updated, err := gopdf.UpdateObject(data, 5, "<< /Type /Page /MediaBox [0 0 612 792] >>")

func WriteBytes

func WriteBytes(w io.Writer, data []byte, offset int, count int) error

WriteBytes writes []byte value to w io.Writer

func WriteTag

func WriteTag(w io.Writer, tag string) error

WriteTag writes string value to w io.Writer

func WriteUInt16

func WriteUInt16(w io.Writer, v uint) error

WriteUInt16 writes a 16-bit unsigned integer value to w io.Writer

func WriteUInt32

func WriteUInt32(w io.Writer, v uint) error

WriteUInt32 writes a 32-bit unsigned integer value to w io.Writer

Types

type AESEncryptionConfig

type AESEncryptionConfig struct {
	// Method selects the encryption algorithm.
	Method EncryptionMethod
	// UserPassword is the password required to open the document.
	UserPassword string
	// OwnerPassword is the password for full access. If empty, a random one is generated.
	OwnerPassword string
	// Permissions is a bitmask of allowed operations (PermissionsPrint, etc.).
	Permissions int
}

AESEncryptionConfig configures AES-based PDF encryption.

type AnnotationInfo

type AnnotationInfo struct {
	// Index is the position of this annotation in the page's annotation list.
	Index int
	// Type is the annotation type.
	Type AnnotationType
	// Option is the original annotation option (if available).
	Option AnnotationOption
}

AnnotationInfo holds information about an existing annotation on a page.

type AnnotationOption

type AnnotationOption struct {
	// Type is the annotation type.
	Type AnnotationType

	// Rect defines the annotation rectangle [x, y, w, h] in document units.
	// x, y is the top-left corner.
	X, Y, W, H float64

	// Title is the annotation title (author name for sticky notes).
	Title string

	// Content is the annotation text content.
	Content string

	// Color is the annotation color in RGB. Default: yellow (255, 255, 0).
	Color [3]uint8

	// Opacity is the annotation opacity (0.0 to 1.0). Default: 1.0.
	Opacity float64

	// Open determines if a text annotation popup is initially open.
	Open bool

	// CreationDate is the annotation creation date. Default: now.
	CreationDate time.Time

	// FontSize is used for FreeText annotations. Default: 12.
	FontSize float64

	// InkList contains stroke paths for Ink annotations.
	// Each element is a slice of Points representing one stroke.
	InkList [][]Point

	// Vertices contains points for Polyline and Polygon annotations.
	Vertices []Point

	// LineStart and LineEnd define endpoints for Line annotations.
	LineStart, LineEnd Point

	// LineEndingStyles defines the start and end styles for Line annotations.
	// Default: [None, None].
	LineEndingStyles [2]LineEndingStyle

	// Stamp is the stamp name for Stamp annotations. Default: "Draft".
	Stamp StampName

	// InteriorColor is the fill color for closed shapes (Square, Circle, Polygon).
	// If nil (zero value), no interior color is applied.
	InteriorColor *[3]uint8

	// BorderWidth is the annotation border width. Default: 1.
	BorderWidth float64

	// FileName is the file name for FileAttachment annotations.
	FileName string

	// FileData is the file content for FileAttachment annotations.
	FileData []byte

	// OverlayText is the text displayed over a Redact annotation area.
	OverlayText string
}

AnnotationOption configures a PDF annotation.

type AnnotationType

type AnnotationType int

AnnotationType represents the type of PDF annotation.

const (
	// AnnotText is a sticky note annotation (appears as an icon).
	AnnotText AnnotationType = iota
	// AnnotHighlight highlights existing text on the page.
	AnnotHighlight
	// AnnotUnderline underlines existing text on the page.
	AnnotUnderline
	// AnnotStrikeOut strikes out existing text on the page.
	AnnotStrikeOut
	// AnnotSquare draws a rectangle annotation.
	AnnotSquare
	// AnnotCircle draws a circle/ellipse annotation.
	AnnotCircle
	// AnnotFreeText places text directly on the page.
	AnnotFreeText
	// AnnotInk is a freehand drawing annotation (ink strokes).
	AnnotInk
	// AnnotPolyline draws connected line segments (open path).
	AnnotPolyline
	// AnnotPolygon draws a closed polygon shape.
	AnnotPolygon
	// AnnotLine draws a single line between two endpoints.
	AnnotLine
	// AnnotStamp places a predefined stamp (e.g. "Approved", "Draft").
	AnnotStamp
	// AnnotSquiggly applies a wavy underline to text.
	AnnotSquiggly
	// AnnotCaret marks an insertion point in text.
	AnnotCaret
	// AnnotFileAttachment attaches a file to the annotation.
	AnnotFileAttachment
	// AnnotRedact marks an area for redaction (content removal).
	AnnotRedact
)

type BlendModeType

type BlendModeType string
const (
	Hue             BlendModeType = "/Hue"
	Color           BlendModeType = "/Color"
	NormalBlendMode BlendModeType = "/Normal"
	Darken          BlendModeType = "/Darken"
	Screen          BlendModeType = "/Screen"
	Overlay         BlendModeType = "/Overlay"
	Lighten         BlendModeType = "/Lighten"
	Multiply        BlendModeType = "/Multiply"
	Exclusion       BlendModeType = "/Exclusion"
	ColorBurn       BlendModeType = "/ColorBurn"
	HardLight       BlendModeType = "/HardLight"
	SoftLight       BlendModeType = "/SoftLight"
	Difference      BlendModeType = "/Difference"
	Saturation      BlendModeType = "/Saturation"
	Luminosity      BlendModeType = "/Luminosity"
	ColorDodge      BlendModeType = "/ColorDodge"
)

type BookmarkStyle

type BookmarkStyle struct {
	// Bold makes the bookmark title bold.
	Bold bool
	// Italic makes the bookmark title italic.
	Italic bool
	// Color is the bookmark text color [R, G, B] (0.0-1.0). Zero value = default (black).
	Color [3]float64
	// Collapsed controls whether child bookmarks are initially hidden.
	Collapsed bool
}

BookmarkStyle defines visual styling for a bookmark entry.

type BorderStyle

type BorderStyle struct {
	Top      bool     // Whether to draw the top border
	Left     bool     // Whether to draw the left border
	Right    bool     // Whether to draw the right border
	Bottom   bool     // Whether to draw the bottom border
	Width    float64  // Width of the border line
	RGBColor RGBColor // Color of the border
}

Defines the border style for a cell or table

type Box

type Box struct {
	Left, Top, Right, Bottom float64
	// contains filtered or unexported fields
}

func (*Box) UnitsToPoints

func (box *Box) UnitsToPoints(t int) (b *Box)

UnitsToPoints converts the box coordinates to Points. When this is called it is assumed the values of the box are in Units

type BreakMode

type BreakMode int

BreakMode type for text break modes.

const (
	// BreakModeStrict causes the text-line to break immediately in case the current character would not fit into
	// the processed text-line. The separator (if provided) will be attached accordingly as a line suffix
	// to stay within the defined width.
	BreakModeStrict BreakMode = iota

	// BreakModeIndicatorSensitive will try to break the current line based on the last index of a provided
	// BreakIndicator. If no indicator sensitive break can be performed a strict break will be performed,
	// potentially working with the given separator as a suffix.
	BreakModeIndicatorSensitive
)

type BreakOption

type BreakOption struct {
	// Mode defines the mode which should be used
	Mode BreakMode
	// BreakIndicator is taken into account when using indicator sensitive mode to avoid mid-word line breaks
	BreakIndicator rune
	// Separator will act as a suffix for mid-word breaks when using strict mode
	Separator string
}

BreakOption allows to configure the behavior of splitting or breaking larger texts via SplitTextWithOption.

func (BreakOption) HasSeparator

func (bo BreakOption) HasSeparator() bool

type Buff

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

Buff for pdf content

func (*Buff) Bytes

func (b *Buff) Bytes() []byte

Bytes : get bytes

func (*Buff) Len

func (b *Buff) Len() int

Len : len of buffer

func (*Buff) Position

func (b *Buff) Position() int

Position : get current position

func (*Buff) SetPosition

func (b *Buff) SetPosition(pos int)

SetPosition : set current position

func (*Buff) Write

func (b *Buff) Write(p []byte) (int, error)

Write : write []byte to buffer

type CIDFontObj

type CIDFontObj struct {
	PtrToSubsetFontObj *SubsetFontObj
	// contains filtered or unexported fields
}

CIDFontObj is a CID-keyed font. cf. https://www.adobe.com/content/dam/acom/en/devnet/font/pdfs/5014.CIDFont_Spec.pdf

func (*CIDFontObj) SetIndexObjSubfontDescriptor

func (ci *CIDFontObj) SetIndexObjSubfontDescriptor(index int)

SetIndexObjSubfontDescriptor set indexObjSubfontDescriptor

func (*CIDFontObj) SetPtrToSubsetFontObj

func (ci *CIDFontObj) SetPtrToSubsetFontObj(ptr *SubsetFontObj)

SetPtrToSubsetFontObj set PtrToSubsetFontObj

type CacheContent

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

CacheContent Export cacheContent

func (*CacheContent) Setup

func (c *CacheContent) Setup(rectangle *Rect,
	textColor ICacheColorText,
	grayFill float64,
	fontCountIndex int,
	fontSize float64,
	fontStyle int,
	charSpacing float64,
	setXCount int,
	x, y float64,
	fontSubset *SubsetFontObj,
	pageheight float64,
	contentType int,
	cellOpt CellOption,
	lineWidth float64,
)

Setup setup all information for cacheContent

func (*CacheContent) WriteTextToContent

func (c *CacheContent) WriteTextToContent(text string)

WriteTextToContent write text to content

type CatalogObj

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

CatalogObj : catalog dictionary

func (*CatalogObj) SetIndexObjAcroForm

func (c *CatalogObj) SetIndexObjAcroForm(index int)

SetIndexObjAcroForm sets the AcroForm object reference.

func (*CatalogObj) SetIndexObjMarkInfo

func (c *CatalogObj) SetIndexObjMarkInfo(index int)

SetIndexObjMarkInfo sets the MarkInfo object reference.

func (*CatalogObj) SetIndexObjMetadata

func (c *CatalogObj) SetIndexObjMetadata(index int)

SetIndexObjMetadata sets the XMP Metadata stream object reference.

func (*CatalogObj) SetIndexObjNames

func (c *CatalogObj) SetIndexObjNames(index int)

SetIndexObjNames sets the Names dictionary object reference.

func (*CatalogObj) SetIndexObjOCProperties

func (c *CatalogObj) SetIndexObjOCProperties(index int)

SetIndexObjOCProperties sets the OCProperties object reference.

func (*CatalogObj) SetIndexObjOutlines

func (c *CatalogObj) SetIndexObjOutlines(index int)

func (*CatalogObj) SetIndexObjPageLabels

func (c *CatalogObj) SetIndexObjPageLabels(index int)

SetIndexObjPageLabels sets the PageLabels object reference.

type CellOption

type CellOption struct {
	Align                  int //Allows to align the text. Possible values are: Left,Center,Right,Top,Bottom,Middle
	Border                 int //Indicates if borders must be drawn around the cell. Possible values are: Left, Top, Right, Bottom, ALL
	Float                  int //Indicates where the current position should go after the call. Possible values are: Right, Bottom
	Transparency           *Transparency
	CoefUnderlinePosition  float64
	CoefLineHeight         float64
	CoefUnderlineThickness float64
	BreakOption            *BreakOption
	// contains filtered or unexported fields
}

CellOption cell option

type CellStyle

type CellStyle struct {
	BorderStyle BorderStyle // Border style for the cell
	FillColor   RGBColor    // Background color of the cell
	TextColor   RGBColor    // Color of the text in the cell
	Font        string      // Font name for the cell text
	FontSize    float64     // Font size for the cell text
}

Defines the style for a cell, including border, fill, text, and font properties

type ColorSpaceObj

type ColorSpaceObj struct {
	CountOfSpaceColor int
	Name              string
	// contains filtered or unexported fields
}

func (*ColorSpaceObj) SetColorCMYK

func (cs *ColorSpaceObj) SetColorCMYK(c, m, y, k uint8)

func (*ColorSpaceObj) SetColorRBG

func (cs *ColorSpaceObj) SetColorRBG(r, g, b uint8)

type ColorSpaces

type ColorSpaces string

type ColorspaceTarget

type ColorspaceTarget int

ColorspaceTarget specifies the target colorspace for conversion.

const (
	// ColorspaceGray converts to DeviceGray.
	ColorspaceGray ColorspaceTarget = iota
	// ColorspaceCMYK converts to DeviceCMYK.
	ColorspaceCMYK
	// ColorspaceRGB converts to DeviceRGB.
	ColorspaceRGB
)

type Config

type Config struct {
	Unit int // The unit type to use when composing the document.
	//Value that use to convert units to points.
	//If this variable is not 0. This value will be used to calculate the unit conversion instead of the existing const value in the system.
	//And if this variable is not 0. Value ​​in Config.Unit will not be used.
	ConversionForUnit float64
	TrimBox           Box                 // The default trim box for all pages in the document
	PageSize          Rect                // The default page size for all pages in the document
	K                 float64             // Not sure
	Protection        PDFProtectionConfig // Protection settings
}

Config static config

type ContentElement

type ContentElement struct {
	// Index is the 0-based position in the page's content cache array.
	Index int
	// Type is the element type.
	Type ContentElementType
	// X is the X coordinate (for elements that have one).
	X float64
	// Y is the Y coordinate (for elements that have one).
	Y float64
	// X2 is the second X coordinate (for lines, ovals).
	X2 float64
	// Y2 is the second Y coordinate (for lines, ovals).
	Y2 float64
	// Width is the width (for rectangles, images).
	Width float64
	// Height is the height (for rectangles, images).
	Height float64
	// Text is the text content (for text elements only).
	Text string
	// FontSize is the font size (for text elements only).
	FontSize float64
}

ContentElement is a public descriptor for a single content element on a page. It exposes the element's type, position, dimensions, and (for text) the string content. The Index field is the 0-based position in the page's content stream cache.

type ContentElementType

type ContentElementType int

ContentElementType identifies the type of a content element.

const (
	// ElementText represents a text element.
	ElementText ContentElementType = iota
	// ElementImage represents an image element.
	ElementImage
	// ElementLine represents a line element.
	ElementLine
	// ElementRectangle represents a rectangle element.
	ElementRectangle
	// ElementOval represents an oval/ellipse element.
	ElementOval
	// ElementPolygon represents a polygon element.
	ElementPolygon
	// ElementCurve represents a Bézier curve element.
	ElementCurve
	// ElementPolyline represents a polyline (open path) element.
	ElementPolyline
	// ElementSector represents a sector (pie/fan shape) element.
	ElementSector
	// ElementImportedTemplate represents an imported PDF template.
	ElementImportedTemplate
	// ElementLineWidth represents a line width setting.
	ElementLineWidth
	// ElementLineType represents a line type setting.
	ElementLineType
	// ElementCustomLineType represents a custom dash pattern.
	ElementCustomLineType
	// ElementGray represents a grayscale fill/stroke setting.
	ElementGray
	// ElementColorRGB represents an RGB color setting.
	ElementColorRGB
	// ElementColorCMYK represents a CMYK color setting.
	ElementColorCMYK
	// ElementColorSpace represents a color space setting.
	ElementColorSpace
	// ElementRotate represents a rotation transform.
	ElementRotate
	// ElementClipPolygon represents a clipping path.
	ElementClipPolygon
	// ElementSaveGState represents a graphics state save (q).
	ElementSaveGState
	// ElementRestoreGState represents a graphics state restore (Q).
	ElementRestoreGState
	// ElementUnknown represents an unrecognized element type.
	ElementUnknown
)

func (ContentElementType) String

func (t ContentElementType) String() string

String returns a human-readable name for the element type.

type ContentObj

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

ContentObj content object

func (*ContentObj) AppendStreamClipPolygon

func (c *ContentObj) AppendStreamClipPolygon(points []Point)

AppendStreamClipPolygon sets a clipping path from polygon points.

func (*ContentObj) AppendStreamCurve

func (c *ContentObj) AppendStreamCurve(x0 float64, y0 float64, x1 float64, y1 float64, x2 float64, y2 float64, x3 float64, y3 float64, style string)

AppendStreamCurve draw curve

  • x0, y0: Start point
  • x1, y1: Control point 1
  • x2, y2: Control point 2
  • x3, y3: End point
  • style: Style of rectangule (draw and/or fill: D, F, DF, FD) D or empty string: draw. This is the default value. F: fill DF or FD: draw and fill

func (*ContentObj) AppendStreamImage

func (c *ContentObj) AppendStreamImage(index int, opts ImageOptions)

AppendStreamImage append image

func (*ContentObj) AppendStreamImportedTemplate

func (c *ContentObj) AppendStreamImportedTemplate(tplName string, scaleX float64, scaleY float64, tX float64, tY float64)

AppendStreamImportedTemplate append imported template

func (*ContentObj) AppendStreamLine

func (c *ContentObj) AppendStreamLine(x1 float64, y1 float64, x2 float64, y2 float64, lineOpts lineOptions)

AppendStreamLine append line

func (*ContentObj) AppendStreamOval

func (c *ContentObj) AppendStreamOval(x1 float64, y1 float64, x2 float64, y2 float64)

AppendStreamOval append oval

func (*ContentObj) AppendStreamPolygon

func (c *ContentObj) AppendStreamPolygon(points []Point, style string, opts polygonOptions)

AppendStreamPolygon append polygon

func (*ContentObj) AppendStreamPolyline

func (c *ContentObj) AppendStreamPolyline(points []Point, opts polylineOptions)

AppendStreamPolyline appends a polyline (open path, stroke only).

func (*ContentObj) AppendStreamRectangle

func (c *ContentObj) AppendStreamRectangle(opts DrawableRectOptions)

func (*ContentObj) AppendStreamRestoreGraphicsState

func (c *ContentObj) AppendStreamRestoreGraphicsState()

AppendStreamRestoreGraphicsState restores the graphics state (Q operator).

func (*ContentObj) AppendStreamSaveGraphicsState

func (c *ContentObj) AppendStreamSaveGraphicsState()

AppendStreamSaveGraphicsState saves the current graphics state (q operator).

func (*ContentObj) AppendStreamSector

func (c *ContentObj) AppendStreamSector(cx, cy, r, startDeg, endDeg float64, style string, opts sectorOptions)

AppendStreamSector appends a sector (pie/fan shape).

func (*ContentObj) AppendStreamSetColorFill

func (c *ContentObj) AppendStreamSetColorFill(r uint8, g uint8, b uint8)

AppendStreamSetColorFill set the color fill

func (*ContentObj) AppendStreamSetColorFillCMYK

func (c *ContentObj) AppendStreamSetColorFillCMYK(cy, m, y, k uint8)

AppendStreamSetColorFillCMYK set the color fill in CMYK color mode

func (*ContentObj) AppendStreamSetColorStroke

func (c *ContentObj) AppendStreamSetColorStroke(r uint8, g uint8, b uint8)

AppendStreamSetColorStroke set the color stroke

func (*ContentObj) AppendStreamSetColorStrokeCMYK

func (c *ContentObj) AppendStreamSetColorStrokeCMYK(cy, m, y, k uint8)

AppendStreamSetColorStrokeCMYK set the color stroke in CMYK color mode

func (*ContentObj) AppendStreamSetCustomLineType

func (c *ContentObj) AppendStreamSetCustomLineType(a []float64, p float64)

AppendStreamSetCustomLineType : set a custom line type

func (*ContentObj) AppendStreamSetGrayFill

func (c *ContentObj) AppendStreamSetGrayFill(w float64)

AppendStreamSetGrayFill set the grayscale fills

func (*ContentObj) AppendStreamSetGrayStroke

func (c *ContentObj) AppendStreamSetGrayStroke(w float64)

AppendStreamSetGrayStroke set the grayscale stroke

func (*ContentObj) AppendStreamSetLineType

func (c *ContentObj) AppendStreamSetLineType(t string)

AppendStreamSetLineType : Set linetype [solid, dashed, dotted]

func (*ContentObj) AppendStreamSetLineWidth

func (c *ContentObj) AppendStreamSetLineWidth(w float64)

AppendStreamSetLineWidth : set line width

func (*ContentObj) AppendStreamSubsetFont

func (c *ContentObj) AppendStreamSubsetFont(rectangle *Rect, text string, cellOpt CellOption) error

AppendStreamSubsetFont add stream of text

func (*ContentObj) AppendStreamText

func (c *ContentObj) AppendStreamText(text string) error

AppendStreamText append text

func (*ContentObj) GetCacheContentImage

func (c *ContentObj) GetCacheContentImage(index int, opts ImageOptions) *cacheContentImage

type ConvertColorspaceOption

type ConvertColorspaceOption struct {
	// Target is the target colorspace.
	Target ColorspaceTarget
}

ConvertColorspaceOption configures colorspace conversion.

type CropOptions

type CropOptions struct {
	X      float64
	Y      float64
	Width  float64
	Height float64
}

type Current

type Current struct {
	X float64
	Y float64

	//font
	IndexOfFontObj int
	CountOfFont    int
	CountOfL       int

	FontSize      float64
	FontStyle     int // Regular|Bold|Italic|Underline
	FontFontCount int
	FontType      int // CURRENT_FONT_TYPE_IFONT or  CURRENT_FONT_TYPE_SUBSET

	IndexOfColorSpaceObj int
	CountOfColorSpace    int

	CharSpacing float64

	FontISubset *SubsetFontObj // FontType == CURRENT_FONT_TYPE_SUBSET

	//page
	IndexOfPageObj int

	//img
	CountOfImg int
	//cache of image in pdf file
	ImgCaches map[int]ImageCache
	// contains filtered or unexported fields
}

Current current state

type DeviceRGBObj

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

DeviceRGBObj DeviceRGB

type DiffType

type DiffType int

DiffType represents the type of difference found between two PDFs.

const (
	// DiffPageCount indicates different number of pages.
	DiffPageCount DiffType = iota
	// DiffPageSize indicates different page dimensions.
	DiffPageSize
	// DiffTextContent indicates different text content on a page.
	DiffTextContent
	// DiffTextAdded indicates text present in doc2 but not doc1.
	DiffTextAdded
	// DiffTextRemoved indicates text present in doc1 but not doc2.
	DiffTextRemoved
	// DiffTextMoved indicates text that moved position between docs.
	DiffTextMoved
	// DiffImageCount indicates different number of images on a page.
	DiffImageCount
	// DiffFontDifference indicates different fonts used.
	DiffFontDifference
	// DiffMetadata indicates different document metadata.
	DiffMetadata
	// DiffAnnotation indicates different annotations.
	DiffAnnotation
)

func (DiffType) String

func (d DiffType) String() string

String returns a human-readable name for the diff type.

type DocumentStats

type DocumentStats struct {
	// PageCount is the total number of pages.
	PageCount int
	// ObjectCount is the total number of PDF objects.
	ObjectCount int
	// LiveObjectCount is the number of non-null objects.
	LiveObjectCount int
	// FontCount is the number of font objects.
	FontCount int
	// ImageCount is the number of image objects.
	ImageCount int
	// ContentStreamCount is the number of content stream objects.
	ContentStreamCount int
	// HasOutlines indicates whether the document has bookmarks.
	HasOutlines bool
	// HasEmbeddedFiles indicates whether the document has attachments.
	HasEmbeddedFiles bool
	// HasXMPMetadata indicates whether XMP metadata is set.
	HasXMPMetadata bool
	// HasPageLabels indicates whether page labels are defined.
	HasPageLabels bool
	// HasOCGs indicates whether optional content groups are defined.
	HasOCGs bool
	// PDFVersion is the configured PDF version.
	PDFVersion PDFVersion
}

DocumentStats contains summary statistics about the PDF document.

type DrawableRectOptions

type DrawableRectOptions struct {
	Rect
	X            float64
	Y            float64
	PaintStyle   PaintStyle
	Transparency *Transparency
	// contains filtered or unexported fields
}

type EmbedFontObj

type EmbedFontObj struct {
	Data string
	// contains filtered or unexported fields
}

EmbedFontObj is an embedded font object.

func (*EmbedFontObj) SetFont

func (e *EmbedFontObj) SetFont(font IFont, zfontpath string)

SetFont sets the font of an embedded font object.

type EmbeddedFile

type EmbeddedFile struct {
	Name        string    // Display name of the file
	Content     []byte    // File content
	MimeType    string    // MIME type (e.g. "application/pdf", "text/plain")
	Description string    // Optional description
	ModDate     time.Time // Modification date (default: now)
}

EmbeddedFile represents a file to be embedded in the PDF.

type EmbeddedFileInfo

type EmbeddedFileInfo struct {
	Name        string
	MimeType    string
	Description string
	Size        int       // uncompressed size in bytes
	ModDate     time.Time // modification date
}

EmbeddedFileInfo contains metadata about an embedded file.

type EncodingObj

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

EncodingObj is a font object.

func (*EncodingObj) GetFont

func (e *EncodingObj) GetFont() IFont

GetFont gets the font from an encoding object.

func (*EncodingObj) SetFont

func (e *EncodingObj) SetFont(font IFont)

SetFont sets the font of an encoding object.

type EncryptionMethod

type EncryptionMethod int

EncryptionMethod represents the PDF encryption algorithm.

const (
	// EncryptRC4V1 is 40-bit RC4 encryption (PDF 1.1+).
	EncryptRC4V1 EncryptionMethod = iota
	// EncryptRC4V2 is up to 128-bit RC4 encryption (PDF 1.4+).
	EncryptRC4V2
	// EncryptAES128 is 128-bit AES encryption (PDF 1.6+).
	EncryptAES128
	// EncryptAES256 is 256-bit AES encryption (PDF 2.0+).
	EncryptAES256
)

type EncryptionObj

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

EncryptionObj encryption object res

type ExtGS

type ExtGS struct {
	Index int
}

ExtGS is ???

type ExtGState

type ExtGState struct {
	Index int

	CA         *float64
	BM         *BlendModeType
	SMaskIndex *int
	// contains filtered or unexported fields
}

TODO: add all fields https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf 8.4.5 page 128

func GetCachedExtGState

func GetCachedExtGState(opts ExtGStateOptions, gp *GoPdf) (ExtGState, error)

type ExtGStateOptions

type ExtGStateOptions struct {
	StrokingCA    *float64
	NonStrokingCa *float64
	BlendMode     *BlendModeType
	SMaskIndex    *int
}

func (ExtGStateOptions) GetId

func (extOpt ExtGStateOptions) GetId() string

type ExtGStatesMap

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

func NewExtGStatesMap

func NewExtGStatesMap() ExtGStatesMap

func (*ExtGStatesMap) Find

func (extm *ExtGStatesMap) Find(extGState ExtGStateOptions) (ExtGState, bool)

func (*ExtGStatesMap) Save

func (tm *ExtGStatesMap) Save(id string, extGState ExtGState) ExtGState

type ExtractedFont

type ExtractedFont struct {
	// Name is the font resource name (e.g., "F1").
	Name string
	// BaseFont is the PostScript font name (e.g., "Helvetica", "TimesNewRoman").
	BaseFont string
	// Subtype is the font type (e.g., "Type1", "TrueType", "Type0").
	Subtype string
	// Encoding is the font encoding (e.g., "WinAnsiEncoding", "Identity-H").
	Encoding string
	// ObjNum is the PDF object number of the font.
	ObjNum int
	// IsEmbedded indicates whether the font data is embedded in the PDF.
	IsEmbedded bool
	// Data is the raw font data (if embedded and extractable). May be nil.
	Data []byte
}

ExtractedFont holds information about a font found in a PDF.

func ExtractFontsFromPage

func ExtractFontsFromPage(pdfData []byte, pageIndex int) ([]ExtractedFont, error)

ExtractFontsFromPage extracts font information from a specific page (0-based).

Example:

data, _ := os.ReadFile("input.pdf")
fonts, _ := gopdf.ExtractFontsFromPage(data, 0)
for _, f := range fonts {
    fmt.Printf("%s: %s (%s) embedded=%v\n", f.Name, f.BaseFont, f.Subtype, f.IsEmbedded)
}

type ExtractedImage

type ExtractedImage struct {
	// Name is the XObject resource name (e.g. "/Im1").
	Name string
	// Width is the image width in pixels.
	Width int
	// Height is the image height in pixels.
	Height int
	// BitsPerComponent is the bits per color component.
	BitsPerComponent int
	// ColorSpace is the color space name.
	ColorSpace string
	// Filter is the compression filter.
	Filter string
	// Data is the raw (possibly compressed) image data.
	Data []byte
	// ObjNum is the PDF object number.
	ObjNum int
	// X, Y are the position on the page (from the CTM).
	X float64
	// Y position on the page.
	Y float64
	// DisplayWidth is the rendered width on the page.
	DisplayWidth float64
	// DisplayHeight is the rendered height on the page.
	DisplayHeight float64
}

ExtractedImage represents an image found on a PDF page.

func ExtractImagesFromPage

func ExtractImagesFromPage(pdfData []byte, pageIndex int) ([]ExtractedImage, error)

ExtractImagesFromPage extracts image metadata and data from a specific page (0-based) of the given PDF data.

Example:

data, _ := os.ReadFile("input.pdf")
images, _ := gopdf.ExtractImagesFromPage(data, 0)
for _, img := range images {
    fmt.Printf("%s: %dx%d %s\n", img.Name, img.Width, img.Height, img.ColorSpace)
}

func (*ExtractedImage) GetImageFormat

func (img *ExtractedImage) GetImageFormat() string

GetImageFormat returns the likely image format based on the filter.

type ExtractedLink struct {
	// PageIndex is the 0-based page index.
	PageIndex int
	// Rect is the link rectangle [x1, y1, x2, y2] in PDF coordinates.
	Rect [4]float64
	// URI is the external URL (if any).
	URI string
	// Destination is the internal destination (if any).
	Destination string
	// IsExternal is true for URI links.
	IsExternal bool
}

ExtractedLink represents a link extracted from an existing PDF.

func ExtractLinks(pdfData []byte) ([]ExtractedLink, error)

ExtractLinks extracts all links from all pages of the given PDF data.

Example:

data, _ := os.ReadFile("input.pdf")
links, _ := gopdf.ExtractLinks(data)
for _, l := range links {
    fmt.Printf("Page %d: %s\n", l.PageIndex, l.URI)
}

func ExtractLinksFromPage

func ExtractLinksFromPage(pdfData []byte, pageIndex int) ([]ExtractedLink, error)

ExtractLinksFromPage extracts links from a specific page (0-based).

type ExtractedText

type ExtractedText struct {
	// Text is the extracted text string.
	Text string
	// X is the horizontal position.
	X float64
	// Y is the vertical position.
	Y float64
	// FontName is the PDF font resource name (e.g. "/F1").
	FontName string
	// FontSize is the font size in points.
	FontSize float64
}

ExtractedText represents a piece of text extracted from a PDF page.

func ExtractTextFromPage

func ExtractTextFromPage(pdfData []byte, pageIndex int) ([]ExtractedText, error)

ExtractTextFromPage extracts text from a specific page (0-based) of the given PDF data. Returns a list of ExtractedText items with position, font, and text content.

This is a pure-Go PDF content stream parser that handles the most common text operators: BT/ET, Tf, Td, TD, Tm, T*, Tj, TJ, ', ".

Example:

data, _ := os.ReadFile("input.pdf")
texts, _ := gopdf.ExtractTextFromPage(data, 0)
for _, t := range texts {
    fmt.Printf("(%0.f,%0.f) %s\n", t.X, t.Y, t.Text)
}

type FontContainer

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

FontContainer manages a collection of fonts.

func (*FontContainer) AddTTFFont

func (fc *FontContainer) AddTTFFont(family string, ttfpath string) error

AddTTFFont adds a font by the specified TTF file path.

Example
fontContainer := &gopdf.FontContainer{}
err := fontContainer.AddTTFFont("LiberationSerif-Regular", "path/to/LiberationSerif-Regular.ttf")
if err != nil {
	// handle error
}
pdf := &gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
err = pdf.AddTTFFontFromFontContainer("LiberationSerif-Regular", fontContainer)
if err != nil {
	// handle error
}

func (*FontContainer) AddTTFFontByReader

func (fc *FontContainer) AddTTFFontByReader(family string, rd io.Reader) error

AddTTFFontByReader adds font by reader.

Example
ttf, err := os.Open("path/to/LiberationSerif-Regular.ttf")
if err != nil {
	// handle error
}
defer ttf.Close()

fontContainer := &gopdf.FontContainer{}
err = fontContainer.AddTTFFontByReader("LiberationSerif-Regular", ttf)
if err != nil {
	// handle error
}
pdf := &gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
err = pdf.AddTTFFontFromFontContainer("LiberationSerif-Regular", fontContainer)
if err != nil {
	// handle error
}

func (*FontContainer) AddTTFFontByReaderWithOption

func (fc *FontContainer) AddTTFFontByReaderWithOption(family string, rd io.Reader, option TtfOption) error

AddTTFFontByReaderWithOption adds font by reader with option.

Example
ttf, err := os.Open("path/to/LiberationSerif-Regular.ttf")
if err != nil {
	// handle error
}
defer ttf.Close()

fontContainer := &gopdf.FontContainer{}
err = fontContainer.AddTTFFontByReaderWithOption("LiberationSerif-Regular", ttf, gopdf.TtfOption{})
if err != nil {
	// handle error
}
pdf := &gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
err = pdf.AddTTFFontFromFontContainer("LiberationSerif-Regular", fontContainer)
if err != nil {
	// handle error
}

func (*FontContainer) AddTTFFontData

func (fc *FontContainer) AddTTFFontData(family string, fontData []byte) error

AddTTFFontData adds font by data.

Example
ttf, err := os.Open("path/to/LiberationSerif-Regular.ttf")
if err != nil {
	// handle error
}
defer ttf.Close()

fontData, err := io.ReadAll(ttf)
if err != nil {
	// handle error
}

fontContainer := &gopdf.FontContainer{}
err = fontContainer.AddTTFFontData("LiberationSerif-Regular", fontData)
if err != nil {
	// handle error
}
pdf := &gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
err = pdf.AddTTFFontFromFontContainer("LiberationSerif-Regular", fontContainer)
if err != nil {
	// handle error
}

func (*FontContainer) AddTTFFontDataWithOption

func (fc *FontContainer) AddTTFFontDataWithOption(family string, fontData []byte, option TtfOption) error

AddTTFFontDataWithOption adds font by data with option.

Example
ttf, err := os.Open("path/to/LiberationSerif-Regular.ttf")
if err != nil {
	// handle error
}
defer ttf.Close()

fontData, err := io.ReadAll(ttf)
if err != nil {
	// handle error
}

fontContainer := &gopdf.FontContainer{}
err = fontContainer.AddTTFFontDataWithOption("LiberationSerif-Regular", fontData, gopdf.TtfOption{})
if err != nil {
	// handle error
}
pdf := &gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
err = pdf.AddTTFFontFromFontContainer("LiberationSerif-Regular", fontContainer)
if err != nil {
	// handle error
}

func (*FontContainer) AddTTFFontWithOption

func (fc *FontContainer) AddTTFFontWithOption(family string, ttfpath string, option TtfOption) error

AddTTFFontWithOption adds a font by the specified TTF file path with options.

Example
fontContainer := &gopdf.FontContainer{}
err := fontContainer.AddTTFFontWithOption(
	"LiberationSerif-Regular",
	"path/to/LiberationSerif-Regular.ttf",
	gopdf.TtfOption{})
if err != nil {
	// handle error
}
pdf := &gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
err = pdf.AddTTFFontFromFontContainer("LiberationSerif-Regular", fontContainer)
if err != nil {
	// handle error
}

type FontCw

type FontCw map[byte]int

FontCw maps characters to integers.

type FontDescItem

type FontDescItem struct {
	Key string
	Val string
}

FontDescItem is a (key, value) pair.

type FontDescriptorObj

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

FontDescriptorObj is a font descriptor object.

func (*FontDescriptorObj) GetFont

func (f *FontDescriptorObj) GetFont() IFont

GetFont gets font from descriptor.

func (*FontDescriptorObj) SetFont

func (f *FontDescriptorObj) SetFont(font IFont)

SetFont sets the font in descriptor.

func (*FontDescriptorObj) SetFontFileObjRelate

func (f *FontDescriptorObj) SetFontFileObjRelate(relate string)

SetFontFileObjRelate ???

type FontInfo

type FontInfo struct {
	// Family is the font family name.
	Family string
	// Style is the font style (Regular, Bold, Italic, etc.).
	Style int
	// IsEmbedded indicates whether the font file is embedded.
	IsEmbedded bool
	// Index is the internal object index.
	Index int
}

FontInfo describes a font used in the document.

type FontObj

type FontObj struct {
	Family string
	//Style string
	//Size int
	IsEmbedFont bool

	Font        IFont
	CountOfFont int
	// contains filtered or unexported fields
}

FontObj font obj

func (*FontObj) SetIndexObjEncoding

func (f *FontObj) SetIndexObjEncoding(index int)

SetIndexObjEncoding sets the encoding.

func (*FontObj) SetIndexObjFontDescriptor

func (f *FontObj) SetIndexObjFontDescriptor(index int)

SetIndexObjFontDescriptor sets the font descriptor.

func (*FontObj) SetIndexObjWidth

func (f *FontObj) SetIndexObjWidth(index int)

SetIndexObjWidth sets the width of a font object.

type FormField

type FormField struct {
	// Type is the field type.
	Type FormFieldType
	// Name is the field name (unique identifier).
	Name string
	// X, Y are the top-left corner position.
	X, Y float64
	// W, H are the width and height.
	W, H float64
	// Value is the default value.
	Value string
	// FontFamily is the font family for text fields (must be pre-loaded).
	FontFamily string
	// FontSize is the font size for text fields (default 12).
	FontSize float64
	// Options is a list of choices for Choice fields.
	Options []string
	// MaxLen is the maximum character length for text fields (0 = unlimited).
	MaxLen int
	// Multiline enables multi-line text input.
	Multiline bool
	// ReadOnly makes the field non-editable.
	ReadOnly bool
	// Required marks the field as required.
	Required bool
	// Color is the text color [R, G, B] (0-255).
	Color [3]uint8
	// BorderColor is the border color [R, G, B] (0-255).
	BorderColor [3]uint8
	// FillColor is the background fill color [R, G, B] (0-255).
	FillColor [3]uint8
	// HasBorder controls whether a border is drawn.
	HasBorder bool
	// HasFill controls whether a background fill is drawn.
	HasFill bool
	// Checked is the initial state for checkboxes.
	Checked bool
	// contains filtered or unexported fields
}

FormField defines a form field to be added to a PDF page.

type FormFieldType

type FormFieldType int

FormFieldType represents the type of a PDF form field.

const (
	// FormFieldText is a text input field.
	FormFieldText FormFieldType = iota
	// FormFieldCheckbox is a checkbox field.
	FormFieldCheckbox
	// FormFieldRadio is a radio button field.
	FormFieldRadio
	// FormFieldChoice is a dropdown/list field.
	FormFieldChoice
	// FormFieldButton is a push button field.
	FormFieldButton
	// FormFieldSignature is a signature field.
	FormFieldSignature
)

func (FormFieldType) String

func (ft FormFieldType) String() string

String returns the field type name.

type FuncKernOverride

type FuncKernOverride func(
	leftRune rune,
	rightRune rune,
	leftPair uint,
	rightPair uint,
	pairVal int16,
) int16

FuncKernOverride return your custome pair value

type GarbageCollectLevel

type GarbageCollectLevel int

GarbageCollectLevel controls how aggressively unused objects are removed.

const (
	// GCNone performs no garbage collection.
	GCNone GarbageCollectLevel = 0
	// GCCompact removes null/deleted objects and renumbers.
	GCCompact GarbageCollectLevel = 1
	// GCDedup additionally deduplicates identical objects.
	GCDedup GarbageCollectLevel = 2
)

type GoPdf

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

GoPdf : A simple library for generating PDF written in Go lang

func ExtractPages

func ExtractPages(pdfPath string, pages []int, opt *OpenPDFOption) (*GoPdf, error)

ExtractPages creates a new GoPdf document containing only the specified pages from the source PDF data. Pages are 1-based.

This is useful for splitting a PDF into smaller documents.

Example:

newPdf, err := gopdf.ExtractPages("input.pdf", []int{1, 3, 5}, nil)
if err != nil { log.Fatal(err) }
newPdf.WritePdf("pages_1_3_5.pdf")

func ExtractPagesFromBytes

func ExtractPagesFromBytes(pdfData []byte, pages []int, opt *OpenPDFOption) (*GoPdf, error)

ExtractPagesFromBytes is like ExtractPages but reads from a byte slice.

func MergePages

func MergePages(pdfPaths []string, opt *OpenPDFOption) (*GoPdf, error)

MergePages merges multiple PDF files into a single document. Each source PDF's pages are appended in order.

Example:

merged, err := gopdf.MergePages([]string{"doc1.pdf", "doc2.pdf", "doc3.pdf"}, nil)
if err != nil { log.Fatal(err) }
merged.WritePdf("merged.pdf")

func MergePagesFromBytes

func MergePagesFromBytes(pdfDataSlices [][]byte, opt *OpenPDFOption) (*GoPdf, error)

MergePagesFromBytes merges multiple PDF byte slices into a single document.

func SelectPagesFromBytes

func SelectPagesFromBytes(pdfData []byte, pages []int, opt *OpenPDFOption) (*GoPdf, error)

SelectPagesFromBytes creates a new GoPdf with pages from PDF bytes rearranged in the specified order.

func SelectPagesFromFile

func SelectPagesFromFile(pdfPath string, pages []int, opt *OpenPDFOption) (*GoPdf, error)

SelectPagesFromFile creates a new GoPdf with pages from a PDF file rearranged in the specified order. Pages are 1-based and may be repeated.

Example:

newPdf, err := gopdf.SelectPagesFromFile("input.pdf", []int{3, 1, 2}, nil)
newPdf.WritePdf("reordered.pdf")

func (*GoPdf) AddAnnotation

func (gp *GoPdf) AddAnnotation(opt AnnotationOption)

AddAnnotation adds an annotation to the current page.

Supported annotation types:

  • AnnotText: Sticky note (comment icon)
  • AnnotHighlight: Highlight markup
  • AnnotUnderline: Underline markup
  • AnnotStrikeOut: Strikeout markup
  • AnnotSquare: Rectangle shape
  • AnnotCircle: Circle/ellipse shape
  • AnnotFreeText: Text directly on the page
  • AnnotInk: Freehand drawing
  • AnnotPolyline: Connected line segments
  • AnnotPolygon: Closed polygon shape
  • AnnotLine: Single line with endpoints
  • AnnotStamp: Predefined stamp
  • AnnotSquiggly: Wavy underline
  • AnnotCaret: Insertion point marker
  • AnnotFileAttachment: File attachment
  • AnnotRedact: Redaction marker

Example:

pdf.AddAnnotation(gopdf.AnnotationOption{
    Type:    gopdf.AnnotText,
    X:       100,
    Y:       100,
    W:       24,
    H:       24,
    Title:   "Reviewer",
    Content: "Please check this section.",
    Color:   [3]uint8{255, 255, 0},
})

func (*GoPdf) AddCaretAnnotation

func (gp *GoPdf) AddCaretAnnotation(x, y, w, h float64, content string)

AddCaretAnnotation adds a caret (insertion point) annotation.

func (*GoPdf) AddCheckbox

func (gp *GoPdf) AddCheckbox(name string, x, y, size float64, checked bool) error

AddCheckbox is a convenience method for adding a checkbox field.

func (*GoPdf) AddColorSpaceCMYK

func (gp *GoPdf) AddColorSpaceCMYK(name string, c, m, y, k uint8) error

func (*GoPdf) AddColorSpaceRGB

func (gp *GoPdf) AddColorSpaceRGB(name string, r, g, b uint8) error

func (*GoPdf) AddDropdown

func (gp *GoPdf) AddDropdown(name string, x, y, w, h float64, options []string) error

AddDropdown is a convenience method for adding a dropdown choice field.

func (*GoPdf) AddEmbeddedFile

func (gp *GoPdf) AddEmbeddedFile(ef EmbeddedFile) error

AddEmbeddedFile attaches a file to the PDF document. The file will appear in the PDF viewer's attachment panel.

Example:

data, _ := os.ReadFile("report.csv")
pdf.AddEmbeddedFile(gopdf.EmbeddedFile{
    Name:     "report.csv",
    Content:  data,
    MimeType: "text/csv",
})
func (gp *GoPdf) AddExternalLink(url string, x, y, w, h float64)

AddExternalLink adds a new external link.

func (*GoPdf) AddFileAttachmentAnnotation

func (gp *GoPdf) AddFileAttachmentAnnotation(x, y float64, fileName string, fileData []byte, content string)

AddFileAttachmentAnnotation adds a file attachment annotation.

func (*GoPdf) AddFooter

func (gp *GoPdf) AddFooter(f func())

AddFooter - add a footer function, if present this will be automatically called by AddPage()

func (*GoPdf) AddFormField

func (gp *GoPdf) AddFormField(field FormField) error

AddFormField adds a form field (widget) to the current page. The field will appear as an interactive form element in PDF viewers.

For text fields, set FontFamily to a pre-loaded font name. If FontFamily is empty, the standard Helvetica font is used.

Example:

pdf.AddFormField(gopdf.FormField{
    Type:      gopdf.FormFieldText,
    Name:      "username",
    X:         50,
    Y:         100,
    W:         200,
    H:         25,
    Value:     "Enter name",
    FontSize:  12,
    HasBorder: true,
    BorderColor: [3]uint8{0, 0, 0},
})

func (*GoPdf) AddFreeTextAnnotation

func (gp *GoPdf) AddFreeTextAnnotation(x, y, w, h float64, text string, fontSize float64)

AddFreeTextAnnotation is a convenience method for adding text directly on the page.

func (*GoPdf) AddHeader

func (gp *GoPdf) AddHeader(f func())

AddHeader - add a header function, if present this will be automatically called by AddPage()

func (*GoPdf) AddHighlightAnnotation

func (gp *GoPdf) AddHighlightAnnotation(x, y, w, h float64, color [3]uint8)

AddHighlightAnnotation is a convenience method for highlighting a rectangular area.

func (*GoPdf) AddInkAnnotation

func (gp *GoPdf) AddInkAnnotation(x, y, w, h float64, strokes [][]Point, color [3]uint8)

AddInkAnnotation adds a freehand ink annotation with one or more strokes.

func (gp *GoPdf) AddInternalLink(anchor string, x, y, w, h float64)

AddInternalLink adds a new internal link.

func (*GoPdf) AddLayerConfig

func (gp *GoPdf) AddLayerConfig(config LayerConfig)

AddLayerConfig adds an alternate layer configuration to the document. Alternate configurations allow PDF viewers to switch between different layer visibility presets.

Example:

pdf.AddLayerConfig(gopdf.LayerConfig{
    Name:    "Print Version",
    OnOCGs:  []gopdf.OCG{contentLayer},
    OffOCGs: []gopdf.OCG{draftLayer},
})

func (*GoPdf) AddLineAnnotation

func (gp *GoPdf) AddLineAnnotation(start, end Point, color [3]uint8)

AddLineAnnotation adds a line annotation between two points.

func (*GoPdf) AddOCG

func (gp *GoPdf) AddOCG(ocg OCG) OCG

AddOCG adds an Optional Content Group (layer) to the document. Returns the OCG for use with SetContentOCG.

Example:

watermarkLayer := pdf.AddOCG(gopdf.OCG{
    Name:   "Watermark",
    Intent: gopdf.OCGIntentView,
    On:     true,
})
draftLayer := pdf.AddOCG(gopdf.OCG{
    Name:   "Draft Notes",
    Intent: gopdf.OCGIntentDesign,
    On:     false,
})

func (*GoPdf) AddOCMD

func (gp *GoPdf) AddOCMD(ocmd OCMD) OCMD

AddOCMD adds an Optional Content Membership Dictionary to the document. An OCMD combines multiple OCGs with a visibility policy.

Example:

ocmd := pdf.AddOCMD(gopdf.OCMD{
    OCGs:   []gopdf.OCG{layer1, layer2},
    Policy: gopdf.OCGVisibilityAllOn,
})

func (*GoPdf) AddOutline

func (gp *GoPdf) AddOutline(title string)

func (*GoPdf) AddOutlineWithPosition

func (gp *GoPdf) AddOutlineWithPosition(title string) *OutlineObj

AddOutlineWithPosition add an outline with position

func (*GoPdf) AddPage

func (gp *GoPdf) AddPage()

AddPage : add new page

func (*GoPdf) AddPageWithOption

func (gp *GoPdf) AddPageWithOption(opt PageOption)

AddPageWithOption : add new page with option

func (*GoPdf) AddPolygonAnnotation

func (gp *GoPdf) AddPolygonAnnotation(x, y, w, h float64, vertices []Point, color [3]uint8)

AddPolygonAnnotation adds a closed polygon annotation.

func (*GoPdf) AddPolylineAnnotation

func (gp *GoPdf) AddPolylineAnnotation(x, y, w, h float64, vertices []Point, color [3]uint8)

AddPolylineAnnotation adds a polyline (open path) annotation.

func (*GoPdf) AddRedactAnnotation

func (gp *GoPdf) AddRedactAnnotation(x, y, w, h float64, overlayText string)

AddRedactAnnotation adds a redaction annotation marking an area for content removal. Call ApplyRedactions() to permanently remove the content.

func (*GoPdf) AddSignatureField

func (gp *GoPdf) AddSignatureField(name string, x, y, w, h float64) error

AddSignatureField adds an empty (unsigned) signature field to the current page. This can be used to create a signature placeholder that can be signed later.

func (*GoPdf) AddSquigglyAnnotation

func (gp *GoPdf) AddSquigglyAnnotation(x, y, w, h float64, color [3]uint8)

AddSquigglyAnnotation adds a wavy underline annotation.

func (*GoPdf) AddStampAnnotation

func (gp *GoPdf) AddStampAnnotation(x, y, w, h float64, stamp StampName)

AddStampAnnotation adds a stamp annotation (e.g. "Approved", "Draft").

func (*GoPdf) AddTTFFont

func (gp *GoPdf) AddTTFFont(family string, ttfpath string) error

AddTTFFont : add font file

func (*GoPdf) AddTTFFontByReader

func (gp *GoPdf) AddTTFFontByReader(family string, rd io.Reader) error

AddTTFFontByReader adds font file by reader.

func (*GoPdf) AddTTFFontByReaderWithOption

func (gp *GoPdf) AddTTFFontByReaderWithOption(family string, rd io.Reader, option TtfOption) error

AddTTFFontByReaderWithOption adds font file by reader with option.

func (*GoPdf) AddTTFFontData

func (gp *GoPdf) AddTTFFontData(family string, fontData []byte) error

AddTTFFontByReader adds font data by reader.

func (*GoPdf) AddTTFFontDataWithOption

func (gp *GoPdf) AddTTFFontDataWithOption(family string, fontData []byte, option TtfOption) error

AddTTFFontDataWithOption adds font data with option.

func (*GoPdf) AddTTFFontFromFontContainer

func (gp *GoPdf) AddTTFFontFromFontContainer(family string, container *FontContainer) error

AddTTFFontFromFontContainer adds a font from a FontContainer

Example
fontContainer := &gopdf.FontContainer{}
err := fontContainer.AddTTFFontWithOption(
	"LiberationSerif-Regular",
	"path/to/LiberationSerif-Regular.ttf",
	gopdf.TtfOption{})
if err != nil {
	// handle error
}
pdf := &gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
err = pdf.AddTTFFontFromFontContainer("LiberationSerif-Regular", fontContainer)
if err != nil {
	// handle error
}

func (*GoPdf) AddTTFFontWithOption

func (gp *GoPdf) AddTTFFontWithOption(family string, ttfpath string, option TtfOption) error

AddTTFFontWithOption : add font file

func (*GoPdf) AddTextAnnotation

func (gp *GoPdf) AddTextAnnotation(x, y float64, title, content string)

AddTextAnnotation is a convenience method for adding a sticky note annotation.

func (*GoPdf) AddTextField

func (gp *GoPdf) AddTextField(name string, x, y, w, h float64) error

AddTextField is a convenience method for adding a text input field.

func (*GoPdf) AddWatermarkImage

func (gp *GoPdf) AddWatermarkImage(imgPath string, opacity float64, imgW, imgH float64, angle float64) error

AddWatermarkImage adds an image watermark to the current page. The image is placed at the center of the page with the specified opacity.

Parameters:

  • imgPath: path to the image file (JPEG or PNG)
  • opacity: transparency level (0.0 = invisible, 1.0 = opaque)
  • imgW, imgH: desired width and height of the watermark image in document units. If both are 0, the image is placed at its natural size.
  • angle: rotation angle in degrees (0 = no rotation)

func (*GoPdf) AddWatermarkImageAllPages

func (gp *GoPdf) AddWatermarkImageAllPages(imgPath string, opacity float64, imgW, imgH float64, angle float64) error

AddWatermarkImageAllPages adds an image watermark to all pages in the document.

func (*GoPdf) AddWatermarkText

func (gp *GoPdf) AddWatermarkText(opt WatermarkOption) error

AddWatermarkText adds a text watermark to the current page. The watermark is rendered with the specified font, color, opacity, and rotation. If Repeat is true, the watermark is tiled across the entire page.

Example:

pdf.SetPage(1)
pdf.AddWatermarkText(WatermarkOption{
    Text:       "CONFIDENTIAL",
    FontFamily: "myfont",
    FontSize:   48,
    Opacity:    0.3,
    Angle:      45,
})

func (*GoPdf) AddWatermarkTextAllPages

func (gp *GoPdf) AddWatermarkTextAllPages(opt WatermarkOption) error

AddWatermarkTextAllPages adds a text watermark to all pages in the document.

func (*GoPdf) ApplyRedactions

func (gp *GoPdf) ApplyRedactions() int

ApplyRedactions removes all redaction annotations from the current page. In a full implementation this would also remove the underlying content; currently it removes the redact annotation markers so they no longer appear.

func (*GoPdf) ApplyRedactionsEnhanced

func (gp *GoPdf) ApplyRedactionsEnhanced(opts RedactionOptions) int

ApplyRedactionsEnhanced applies redaction annotations on the current page with enhanced options including content removal and custom fill colors.

Unlike the basic ApplyRedactions which only removes annotation markers, this method can also remove the underlying content within the redacted areas and draw a filled rectangle with optional overlay text.

Example:

pdf.AddRedactAnnotation(100, 100, 200, 20, "REDACTED")
pdf.ApplyRedactionsEnhanced(gopdf.RedactionOptions{
    FillColor:               [3]uint8{0, 0, 0},
    OverlayText:             "REDACTED",
    OverlayFontSize:         10,
    OverlayColor:            [3]uint8{255, 255, 255},
    RemoveUnderlyingContent: true,
})

func (*GoPdf) ApplyRedactionsEnhancedOnPage

func (gp *GoPdf) ApplyRedactionsEnhancedOnPage(pageNo int, opts RedactionOptions) int

ApplyRedactionsEnhancedOnPage applies enhanced redactions on a specific page (1-indexed).

func (*GoPdf) ApplyRedactionsOnPage

func (gp *GoPdf) ApplyRedactionsOnPage(pageIndex int) int

ApplyRedactionsOnPage applies redactions on the specified page (1-indexed).

func (*GoPdf) BakeAnnotations

func (gp *GoPdf) BakeAnnotations()

BakeAnnotations flattens all annotations and form fields into the page content streams, making them non-interactive. This is similar to PyMuPDF's bake() function.

After baking, form fields become static content and can no longer be edited.

Example:

pdf.BakeAnnotations()
pdf.WritePdf("baked.pdf")

func (*GoPdf) Br

func (gp *GoPdf) Br(h float64)

Br : new line

func (*GoPdf) CatalogObjID

func (gp *GoPdf) CatalogObjID() ObjID

CatalogObjID returns the ObjID of the catalog object.

func (*GoPdf) Cell

func (gp *GoPdf) Cell(rectangle *Rect, text string) error

Cell : create cell of text ( use current x,y is upper-left corner of cell) Note that this has no effect on Rect.H pdf (now). Fix later :-)

func (*GoPdf) CellWithOption

func (gp *GoPdf) CellWithOption(rectangle *Rect, text string, opt CellOption) error

CellWithOption create cell of text ( use current x,y is upper-left corner of cell)

func (*GoPdf) ClearPage

func (gp *GoPdf) ClearPage(pageNo int) error

ClearPage removes all content elements from a page, leaving it blank.

Example:

pdf.ClearPage(1) // clear all content from page 1

func (*GoPdf) ClearPageCropBox

func (gp *GoPdf) ClearPageCropBox(pageNo int) error

ClearPageCropBox removes the CropBox from a page, restoring the full MediaBox as the visible area. pageNo is 1-based.

func (*GoPdf) ClearTransparency

func (gp *GoPdf) ClearTransparency()

func (*GoPdf) ClipPolygon

func (gp *GoPdf) ClipPolygon(points []Point)

ClipPolygon sets a clipping path from polygon points.

func (*GoPdf) Clone

func (gp *GoPdf) Clone() (*GoPdf, error)

Clone creates a deep copy of the GoPdf instance by serializing and re-importing the document. The cloned document is independent — changes to the clone do not affect the original, and vice versa.

This is useful for creating variants of a document (e.g. different watermarks or stamps) without re-generating from scratch.

Note: Header/footer callback functions are NOT cloned (they are set to nil). Font data, images, and all page content are fully duplicated.

Example:

original := &gopdf.GoPdf{}
original.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
original.AddPage()
// ... build document ...

clone, err := original.Clone()
if err != nil { log.Fatal(err) }
// clone is a fully independent copy
clone.SetPage(1)
clone.SetXY(100, 100)
clone.Text("Only in clone")
clone.WritePdf("clone.pdf")

func (*GoPdf) Close

func (gp *GoPdf) Close() error

Close clears the gopdf buffer.

func (*GoPdf) CopyPage

func (gp *GoPdf) CopyPage(pageNo int) (int, error)

CopyPage duplicates a page and appends it at the end of the document. pageNo is 1-based. The new page is an exact copy of the original. Returns the new page number.

Note: This works best with documents opened via OpenPDF.

func (*GoPdf) Curve

func (gp *GoPdf) Curve(x0 float64, y0 float64, x1 float64, y1 float64, x2 float64, y2 float64, x3 float64, y3 float64, style string)

Curve Draws a Bézier curve (the Bézier curve is tangent to the line between the control points at either end of the curve) Parameters: - x0, y0: Start point - x1, y1: Control point 1 - x2, y2: Control point 2 - x3, y3: End point - style: Style of rectangule (draw and/or fill: D, F, DF, FD)

func (gp *GoPdf) DeleteAllLinks() int

DeleteAllLinks removes all links from the current page. Returns the count removed.

func (*GoPdf) DeleteAllLinksOnPage

func (gp *GoPdf) DeleteAllLinksOnPage(pageNo int) int

DeleteAllLinksOnPage removes all links from the specified page (1-indexed).

func (*GoPdf) DeleteAnnotation

func (gp *GoPdf) DeleteAnnotation(index int) bool

DeleteAnnotation removes the annotation at the given index from the current page. Returns true if the annotation was removed.

func (*GoPdf) DeleteAnnotationOnPage

func (gp *GoPdf) DeleteAnnotationOnPage(pageIndex, annotIndex int) bool

DeleteAnnotationOnPage removes the annotation at the given index from the specified page (1-indexed). Returns true if the annotation was removed.

func (*GoPdf) DeleteBookmark

func (gp *GoPdf) DeleteBookmark(index int) error

DeleteBookmark removes a bookmark at the given 0-based index in the flat TOC list. Child bookmarks are also removed.

Example:

pdf.DeleteBookmark(2) // remove the 3rd bookmark

func (*GoPdf) DeleteElement

func (gp *GoPdf) DeleteElement(pageNo int, elementIndex int) error

DeleteElement removes a single content element by its 0-based index on the given page.

Example:

pdf.DeleteElement(1, 0) // remove first element on page 1

func (*GoPdf) DeleteElementsByType

func (gp *GoPdf) DeleteElementsByType(pageNo int, elemType ContentElementType) (int, error)

DeleteElementsByType removes all elements of the specified type from a page. Returns the number of elements removed.

Example:

n := pdf.DeleteElementsByType(1, gopdf.ElementLine) // remove all lines from page 1

func (*GoPdf) DeleteElementsInRect

func (gp *GoPdf) DeleteElementsInRect(pageNo int, rx, ry, rw, rh float64) (int, error)

DeleteElementsInRect removes all elements whose primary position (X, Y) falls within the given rectangle. Returns the number removed.

Example:

n := pdf.DeleteElementsInRect(1, 0, 0, 100, 100) // remove elements in top-left 100x100 area

func (*GoPdf) DeleteEmbeddedFile

func (gp *GoPdf) DeleteEmbeddedFile(name string) error

DeleteEmbeddedFile removes an embedded file by name.

Example:

err := pdf.DeleteEmbeddedFile("report.csv")

func (*GoPdf) DeleteFormField

func (gp *GoPdf) DeleteFormField(name string) error

DeleteFormField removes a form field by name from the document. Returns an error if the field is not found.

Example:

err := pdf.DeleteFormField("username")

func (*GoPdf) DeleteImageByIndex

func (gp *GoPdf) DeleteImageByIndex(pageNo int, imageIndex int) error

DeleteImageByIndex removes a specific image element from a page. The imageIndex is the 0-based index among image elements only (not all elements).

Example:

// Remove the first image on page 1
err := pdf.DeleteImageByIndex(1, 0)

func (*GoPdf) DeleteImages

func (gp *GoPdf) DeleteImages(pageNo int) (int, error)

DeleteImages removes all image elements from the specified page (1-based). Returns the number of images removed.

Example:

pdf.SetPage(1)
n, err := pdf.DeleteImages(1)
fmt.Printf("Removed %d images\n", n)

func (*GoPdf) DeleteImagesFromAllPages

func (gp *GoPdf) DeleteImagesFromAllPages() (int, error)

DeleteImagesFromAllPages removes all image elements from every page. Returns the total number of images removed.

Example:

total, err := pdf.DeleteImagesFromAllPages()
func (gp *GoPdf) DeleteLink(index int) bool

DeleteLink removes the link at the given index from the current page. Returns true if the link was removed.

func (*GoPdf) DeleteLinkOnPage

func (gp *GoPdf) DeleteLinkOnPage(pageNo, linkIndex int) bool

DeleteLinkOnPage removes the link at the given index from the specified page (1-indexed).

func (*GoPdf) DeletePage

func (gp *GoPdf) DeletePage(pageNo int) error

DeletePage removes a page from the document by its 1-based page number. All subsequent pages are shifted down. The current page is reset to page 1.

Note: This only works for documents created via OpenPDF or built from scratch. The page content is removed from the internal object list.

Example:

pdf.OpenPDF("input.pdf", nil)
pdf.DeletePage(2) // remove page 2
pdf.WritePdf("output.pdf")

func (*GoPdf) DeletePages

func (gp *GoPdf) DeletePages(pages []int) error

DeletePages removes multiple pages from the document in a single operation. Pages are specified as 1-based page numbers. Duplicate page numbers are ignored. Pages are deleted in reverse order to maintain correct numbering.

Example:

pdf.DeletePages([]int{2, 4, 6}) // remove pages 2, 4, and 6

func (*GoPdf) FillInPlaceHoldText

func (gp *GoPdf) FillInPlaceHoldText(placeHolderName string, text string, align int) error

[experimental] fill in text that created by function PlaceHolderText align: Left,Right,Center

func (*GoPdf) FindPagesByLabel

func (gp *GoPdf) FindPagesByLabel(label string) []int

FindPagesByLabel returns the 0-based page indices that match the given label string. This searches through the page label definitions to find pages with matching labels.

Example:

pages := pdf.FindPagesByLabel("iii")  // find page labeled "iii"
pages := pdf.FindPagesByLabel("A-1")  // find page labeled "A-1"

func (*GoPdf) GarbageCollect

func (gp *GoPdf) GarbageCollect(level GarbageCollectLevel) int

GarbageCollect removes unused and deleted objects from the document. This reduces file size by eliminating null placeholders left by DeletePage and other operations.

level controls the aggressiveness:

  • GCNone (0): no-op
  • GCCompact (1): remove null objects, renumber references
  • GCDedup (2): also deduplicate identical stream objects

Returns the number of objects removed.

Example:

pdf.DeletePage(2)
removed := pdf.GarbageCollect(gopdf.GCCompact)
fmt.Printf("Removed %d unused objects\n", removed)

func (*GoPdf) GetAllPageSizes

func (gp *GoPdf) GetAllPageSizes() []PageInfo

GetAllPageSizes returns the sizes of all pages in the document.

func (*GoPdf) GetAnnotations

func (gp *GoPdf) GetAnnotations() []AnnotationInfo

GetAnnotations returns all annotations on the current page.

func (*GoPdf) GetAnnotationsOnPage

func (gp *GoPdf) GetAnnotationsOnPage(pageIndex int) []AnnotationInfo

GetAnnotationsOnPage returns all annotations on the specified page (1-indexed).

func (*GoPdf) GetBytesPdf deprecated

func (gp *GoPdf) GetBytesPdf() []byte

GetBytesPdf returns the PDF content as bytes.

Deprecated: This method calls log.Fatalf on error, which terminates the program. Use GetBytesPdfReturnErr instead.

func (*GoPdf) GetBytesPdfReturnErr

func (gp *GoPdf) GetBytesPdfReturnErr() ([]byte, error)

GetBytesPdfReturnErr : get bytes of pdf file

func (*GoPdf) GetDocumentStats

func (gp *GoPdf) GetDocumentStats() DocumentStats

GetDocumentStats returns summary statistics about the document.

Example:

stats := pdf.GetDocumentStats()
fmt.Printf("Pages: %d, Fonts: %d, Images: %d\n",
    stats.PageCount, stats.FontCount, stats.ImageCount)

func (*GoPdf) GetEmbeddedFile

func (gp *GoPdf) GetEmbeddedFile(name string) ([]byte, error)

GetEmbeddedFile retrieves the content of an embedded file by name.

Example:

data, err := pdf.GetEmbeddedFile("report.csv")

func (*GoPdf) GetEmbeddedFileCount

func (gp *GoPdf) GetEmbeddedFileCount() int

GetEmbeddedFileCount returns the number of embedded files.

Example:

count := pdf.GetEmbeddedFileCount()

func (*GoPdf) GetEmbeddedFileInfo

func (gp *GoPdf) GetEmbeddedFileInfo(name string) (EmbeddedFileInfo, error)

GetEmbeddedFileInfo returns metadata about an embedded file.

Example:

info, err := pdf.GetEmbeddedFileInfo("report.csv")
fmt.Println(info.Size, info.MimeType)

func (*GoPdf) GetEmbeddedFileNames

func (gp *GoPdf) GetEmbeddedFileNames() []string

GetEmbeddedFileNames returns the names of all embedded files.

Example:

names := pdf.GetEmbeddedFileNames()

func (*GoPdf) GetFonts

func (gp *GoPdf) GetFonts() []FontInfo

GetFonts returns information about all fonts in the document.

func (*GoPdf) GetFormFields

func (gp *GoPdf) GetFormFields() []FormField

GetFormFields returns all form fields added to the document.

func (*GoPdf) GetInfo

func (gp *GoPdf) GetInfo() PdfInfo

GetInfo get Document Information Dictionary

func (*GoPdf) GetLayerConfigs

func (gp *GoPdf) GetLayerConfigs() []LayerConfig

GetLayerConfigs returns all alternate layer configurations.

func (*GoPdf) GetLayerUIConfig

func (gp *GoPdf) GetLayerUIConfig() *LayerUIConfig

GetLayerUIConfig returns the current layer UI configuration, or nil if not set.

func (gp *GoPdf) GetLinks() []LinkInfo

GetLinks returns all links on the current page.

Example:

links := pdf.GetLinks()
for _, l := range links {
    fmt.Printf("Link at (%.0f,%.0f): %s\n", l.X, l.Y, l.URL)
}

func (*GoPdf) GetLinksOnPage

func (gp *GoPdf) GetLinksOnPage(pageNo int) []LinkInfo

GetLinksOnPage returns all links on the specified page (1-indexed).

func (*GoPdf) GetLiveObjectCount

func (gp *GoPdf) GetLiveObjectCount() int

GetLiveObjectCount returns the number of non-null PDF objects.

func (*GoPdf) GetMarkInfo

func (gp *GoPdf) GetMarkInfo() *MarkInfo

GetMarkInfo returns the current MarkInfo settings, or nil if not set.

func (*GoPdf) GetNextObjectID

func (gp *GoPdf) GetNextObjectID() int

GetNextObjectID gets the next object ID so that gofpdi knows where to start the object IDs.

func (*GoPdf) GetNumberOfPages

func (gp *GoPdf) GetNumberOfPages() int

GetNumberOfPages gets the number of pages from the PDF.

func (*GoPdf) GetOCGs

func (gp *GoPdf) GetOCGs() []OCG

GetOCGs returns all Optional Content Groups defined in the document.

func (*GoPdf) GetOCMD

func (gp *GoPdf) GetOCMD(ocmd OCMD) (OCMD, error)

GetOCMD returns the OCMD at the given object index, or an error if not found.

func (*GoPdf) GetObjByID

func (gp *GoPdf) GetObjByID(id ObjID) IObj

GetObjByID returns the IObj at the given ObjID. Returns nil if the ObjID is invalid or out of range.

func (*GoPdf) GetObjID

func (gp *GoPdf) GetObjID(index int) ObjID

GetObjID returns the ObjID for the object at the given 0-based index. Returns invalidObjID if the index is out of range.

func (*GoPdf) GetObjType

func (gp *GoPdf) GetObjType(id ObjID) string

GetObjType returns the type string of the object at the given ObjID. Returns "" if the ObjID is invalid.

func (*GoPdf) GetObjectCount

func (gp *GoPdf) GetObjectCount() int

GetObjectCount returns the total number of PDF objects in the document. This includes all objects (pages, fonts, images, etc.).

func (*GoPdf) GetPDFVersion

func (gp *GoPdf) GetPDFVersion() PDFVersion

GetPDFVersion returns the current PDF version setting.

func (*GoPdf) GetPageCropBox

func (gp *GoPdf) GetPageCropBox(pageNo int) (*Box, error)

GetPageCropBox returns the CropBox for a page, or nil if no CropBox is set. pageNo is 1-based.

func (*GoPdf) GetPageElementCount

func (gp *GoPdf) GetPageElementCount(pageNo int) (int, error)

GetPageElementCount returns the number of content elements on a page.

func (*GoPdf) GetPageElements

func (gp *GoPdf) GetPageElements(pageNo int) ([]ContentElement, error)

GetPageElements returns all content elements on the specified page (1-based). Each element includes its type, position, dimensions, and index for further operations.

Example:

elements := pdf.GetPageElements(1)
for _, e := range elements {
    fmt.Printf("[%d] %s at (%.1f, %.1f)\n", e.Index, e.Type, e.X, e.Y)
}

func (*GoPdf) GetPageElementsByType

func (gp *GoPdf) GetPageElementsByType(pageNo int, elemType ContentElementType) ([]ContentElement, error)

GetPageElementsByType returns only elements of the specified type on a page.

func (*GoPdf) GetPageLabels

func (gp *GoPdf) GetPageLabels() []PageLabel

GetPageLabels returns the current page label ranges.

func (*GoPdf) GetPageLayout

func (gp *GoPdf) GetPageLayout() PageLayout

GetPageLayout returns the current page layout setting.

func (*GoPdf) GetPageMode

func (gp *GoPdf) GetPageMode() PageMode

GetPageMode returns the current page mode setting.

func (*GoPdf) GetPageRotation

func (gp *GoPdf) GetPageRotation(pageNo int) (int, error)

GetPageRotation returns the display rotation angle for a page. pageNo is 1-based. Returns 0 if no rotation is set.

func (*GoPdf) GetPageSize

func (gp *GoPdf) GetPageSize(pageNo int) (w, h float64, err error)

GetPageSize returns the size of the specified page (1-based). Returns width and height in document units.

func (*GoPdf) GetPageSizes

func (gp *GoPdf) GetPageSizes(sourceFile string) map[int]map[string]map[string]float64

GetPageSizes gets the sizes of the pages of a pdf file1 Returns a map of available pages and its box sizes starting with the first page at index 1 containing a map of boxes containing a map of size values

func (*GoPdf) GetStreamPageSizes

func (gp *GoPdf) GetStreamPageSizes(sourceStream *io.ReadSeeker) map[int]map[string]map[string]float64

GetStreamPageSizes gets the sizes of the pages using a stream Returns a map of available pages and its box sizes starting with the first page at index 1 containing a map of boxes containing a map of size values

func (*GoPdf) GetTOC

func (gp *GoPdf) GetTOC() []TOCItem

GetTOC returns the table of contents (outline/bookmark tree) as a flat list. Each item includes its hierarchy level, title, target page, and Y position.

This reads the outlines that were added via AddOutline/AddOutlineWithPosition. For imported PDFs, outlines from the source are not preserved by gofpdi, so this returns only outlines added programmatically.

Example:

toc := pdf.GetTOC()
for _, item := range toc {
    fmt.Printf("L%d: %s -> page %d\n", item.Level, item.Title, item.PageNo)
}

func (*GoPdf) GetX

func (gp *GoPdf) GetX() float64

GetX : get current position X

func (*GoPdf) GetXMPMetadata

func (gp *GoPdf) GetXMPMetadata() *XMPMetadata

GetXMPMetadata returns the current XMP metadata, or nil if not set.

func (*GoPdf) GetY

func (gp *GoPdf) GetY() float64

GetY : get current position y

func (*GoPdf) Image

func (gp *GoPdf) Image(picPath string, x float64, y float64, rect *Rect) error

Image : draw image

func (*GoPdf) ImageByHolder

func (gp *GoPdf) ImageByHolder(img ImageHolder, x float64, y float64, rect *Rect) error

ImageByHolder : draw image by ImageHolder

func (*GoPdf) ImageByHolderWithOptions

func (gp *GoPdf) ImageByHolderWithOptions(img ImageHolder, opts ImageOptions) error

func (*GoPdf) ImageFrom

func (gp *GoPdf) ImageFrom(img image.Image, x float64, y float64, rect *Rect) error

func (*GoPdf) ImageFromWithOption

func (gp *GoPdf) ImageFromWithOption(img image.Image, opts ImageFromOption) error

func (*GoPdf) ImageSVG

func (gp *GoPdf) ImageSVG(svgPath string, opt SVGOption) error

ImageSVG inserts an SVG image from a file path into the current page. The SVG is converted to native PDF drawing commands (lines, curves, rectangles, circles, paths) — no rasterization is needed.

Supported SVG elements: rect, circle, ellipse, line, polyline, polygon, path (M, L, C, Q, Z commands), text (basic).

Example:

pdf.AddPage()
err := pdf.ImageSVG("icon.svg", SVGOption{X: 50, Y: 50, Width: 200, Height: 200})

func (*GoPdf) ImageSVGFromBytes

func (gp *GoPdf) ImageSVGFromBytes(svgData []byte, opt SVGOption) error

ImageSVGFromBytes inserts an SVG from raw bytes into the current page.

func (*GoPdf) ImageSVGFromReader

func (gp *GoPdf) ImageSVGFromReader(r io.Reader, opt SVGOption) error

ImageSVGFromReader inserts an SVG from an io.Reader into the current page.

func (*GoPdf) ImportObjects

func (gp *GoPdf) ImportObjects(objs map[int]string, startObjID int)

ImportObjects imports objects from gofpdi into current document.

func (*GoPdf) ImportPage

func (gp *GoPdf) ImportPage(sourceFile string, pageno int, box string) int

ImportPage imports a page and return template id. gofpdi code

func (*GoPdf) ImportPageStream

func (gp *GoPdf) ImportPageStream(sourceStream *io.ReadSeeker, pageno int, box string) int

ImportPageStream imports page using a stream. Return template id after importing. gofpdi code

func (*GoPdf) ImportPagesFromSource

func (gp *GoPdf) ImportPagesFromSource(source interface{}, box string) (retErr error)

ImportPagesFromSource imports pages from a source pdf. The source can be a file path, byte slice, or (*)io.ReadSeeker.

func (*GoPdf) ImportTemplates

func (gp *GoPdf) ImportTemplates(tpls map[string]int)

ImportTemplates names into procset dictionary.

func (*GoPdf) IncrementalSave

func (gp *GoPdf) IncrementalSave(originalData []byte, modifiedIndices []int) ([]byte, error)

IncrementalSave writes only the modified/added objects as an incremental update appended to the original PDF data. This is significantly faster than a full rewrite for large documents where only a few objects changed.

Incremental save preserves the original PDF byte stream and appends a new cross-reference section plus the changed objects. This is the same mechanism used by MuPDF and Adobe Acrobat for "fast save".

originalData is the original PDF bytes (e.g. from OpenPDFFromBytes). modifiedIndices lists the 0-based indices of objects that were modified. If modifiedIndices is nil, all objects are considered modified (full save).

Example:

original, _ := os.ReadFile("input.pdf")
pdf := gopdf.GoPdf{}
pdf.OpenPDFFromBytes(original, nil)
pdf.SetPage(1)
pdf.SetXY(100, 100)
pdf.Text("Added text")
result, _ := pdf.IncrementalSave(original, nil)
os.WriteFile("output.pdf", result, 0644)

func (*GoPdf) InsertElementAt

func (gp *GoPdf) InsertElementAt(pageNo int, elementIndex int, newElement ICacheContent) error

InsertElementAt inserts a new ICacheContent at the specified index position. Elements at and after the index are shifted right.

func (*GoPdf) InsertHTMLBox

func (gp *GoPdf) InsertHTMLBox(x, y, w, h float64, htmlStr string, opt HTMLBoxOption) (float64, error)

InsertHTMLBox renders simplified HTML content into a rectangular area on the PDF.

Supported HTML tags:

  • <b>, <strong>: Bold text
  • <i>, <em>: Italic text
  • <u>: Underlined text
  • <s>, <strike>, <del>: Strikethrough (rendered as underline for simplicity)
  • <br>, <br/>: Line break
  • <p>: Paragraph (adds vertical spacing)
  • <h1> to <h6>: Headings with automatic font sizing
  • <font color="..." size="..." face="...">: Font styling
  • <span style="...">: Inline styling (color, font-size, font-family)
  • <img src="..." width="..." height="...">: Images (src must be a local file path)
  • <hr>: Horizontal rule
  • <center>: Centered text
  • <ul>, <ol>, <li>: Lists (basic bullet/number)
  • <a href="...">: Links (rendered as colored text, link annotation added)
  • <sub>, <sup>: Subscript/superscript (approximated with smaller font)

Parameters:

  • x, y: Top-left corner of the box (in document units)
  • w, h: Width and height of the box (in document units)
  • htmlStr: The HTML string to render
  • opt: Rendering options (font families, default size, colors, etc.)

Returns the Y position after the last rendered content (in document units).

func (*GoPdf) InsertLineElement

func (gp *GoPdf) InsertLineElement(pageNo int, x1, y1, x2, y2 float64) error

InsertLineElement adds a line to an existing page's content stream. Coordinates are in the same units as Line().

Example:

pdf.InsertLineElement(1, 10, 10, 200, 10) // horizontal line on page 1

func (*GoPdf) InsertOvalElement

func (gp *GoPdf) InsertOvalElement(pageNo int, x1, y1, x2, y2 float64) error

InsertOvalElement adds an oval/ellipse to an existing page's content stream.

Example:

pdf.InsertOvalElement(1, 50, 50, 150, 100)

func (*GoPdf) InsertRectElement

func (gp *GoPdf) InsertRectElement(pageNo int, x, y, w, h float64, style string) error

InsertRectElement adds a rectangle to an existing page's content stream. style: "D" (draw/stroke), "F" (fill), "DF"/"FD" (draw and fill).

Example:

pdf.InsertRectElement(1, 50, 50, 100, 80, "D")

func (*GoPdf) IsCurrFontContainGlyph

func (gp *GoPdf) IsCurrFontContainGlyph(r rune) (bool, error)

IsCurrFontContainGlyph defines is current font contains to a glyph r: any rune

func (*GoPdf) IsFitMultiCell

func (gp *GoPdf) IsFitMultiCell(rectangle *Rect, text string) (bool, float64, error)

IsFitMultiCell : check whether the rectangle's area is big enough for the text

func (*GoPdf) IsFitMultiCellWithNewline

func (gp *GoPdf) IsFitMultiCellWithNewline(rectangle *Rect, text string) (bool, float64, error)

IsFitMultiCellWithNewline : similar to IsFitMultiCell, but process char newline as Br

func (*GoPdf) JournalDisable

func (gp *GoPdf) JournalDisable()

JournalDisable disables journalling. Existing journal entries are preserved.

func (*GoPdf) JournalEnable

func (gp *GoPdf) JournalEnable()

JournalEnable enables journalling on the document. Once enabled, operations can be recorded and undone.

Example:

pdf.JournalEnable()
pdf.JournalStartOp("add header")
pdf.AddPage()
pdf.Cell(nil, "Hello")
pdf.JournalEndOp()
pdf.JournalUndo() // reverts the "add header" operation

func (*GoPdf) JournalEndOp

func (gp *GoPdf) JournalEndOp()

JournalEndOp ends the current named operation and saves a snapshot.

func (*GoPdf) JournalGetOperations

func (gp *GoPdf) JournalGetOperations() []string

JournalGetOperations returns the names of all recorded operations.

func (*GoPdf) JournalIsEnabled

func (gp *GoPdf) JournalIsEnabled() bool

JournalIsEnabled returns whether journalling is currently enabled.

func (*GoPdf) JournalLoad

func (gp *GoPdf) JournalLoad(path string) error

JournalLoad loads a journal from a file.

Example:

pdf.JournalEnable()
pdf.JournalLoad("document.journal")

func (*GoPdf) JournalRedo

func (gp *GoPdf) JournalRedo() (string, error)

JournalRedo re-applies the last undone operation. Returns the name of the redone operation, or error if nothing to redo.

func (*GoPdf) JournalSave

func (gp *GoPdf) JournalSave(path string) error

JournalSave saves the journal to a file for later restoration.

Example:

pdf.JournalSave("document.journal")

func (*GoPdf) JournalStartOp

func (gp *GoPdf) JournalStartOp(name string)

JournalStartOp begins a named operation. All changes until JournalEndOp are grouped as a single undoable operation.

Example:

pdf.JournalStartOp("insert table")

func (*GoPdf) JournalUndo

func (gp *GoPdf) JournalUndo() (string, error)

JournalUndo reverts the document to the previous state. Returns the name of the undone operation, or error if nothing to undo.

Example:

name, err := pdf.JournalUndo()
fmt.Printf("Undid: %s\n", name)

func (*GoPdf) KernOverride

func (gp *GoPdf) KernOverride(family string, fn FuncKernOverride) error

KernOverride override kern value

func (*GoPdf) Line

func (gp *GoPdf) Line(x1 float64, y1 float64, x2 float64, y2 float64)

Line : draw line

Usage:
pdf.SetTransparency(gopdf.Transparency{Alpha: 0.5,BlendModeType: gopdf.ColorBurn})
pdf.SetLineType("dotted")
pdf.SetStrokeColor(255, 0, 0)
pdf.SetLineWidth(2)
pdf.Line(10, 30, 585, 30)
pdf.ClearTransparency()

func (*GoPdf) MarginBottom

func (gp *GoPdf) MarginBottom() float64

MarginBottom returns the bottom margin.

func (*GoPdf) MarginLeft

func (gp *GoPdf) MarginLeft() float64

MarginLeft returns the left margin.

func (*GoPdf) MarginRight

func (gp *GoPdf) MarginRight() float64

MarginRight returns the right margin.

func (*GoPdf) MarginTop

func (gp *GoPdf) MarginTop() float64

MarginTop returns the top margin.

func (*GoPdf) Margins

func (gp *GoPdf) Margins() (float64, float64, float64, float64)

Margins gets the current margins, The margins will be converted back to the documents units. Returned values will be in the following order Left, Top, Right, Bottom

func (*GoPdf) MeasureCellHeightByText

func (gp *GoPdf) MeasureCellHeightByText(text string) (float64, error)

MeasureCellHeightByText : measure Height of cell by text (use current font)

func (*GoPdf) MeasureTextWidth

func (gp *GoPdf) MeasureTextWidth(text string) (float64, error)

MeasureTextWidth : measure Width of text (use current font)

func (*GoPdf) ModifyAnnotation

func (gp *GoPdf) ModifyAnnotation(pageIndex, annotIndex int, opt AnnotationOption) error

ModifyAnnotation modifies an existing annotation on the specified page. pageIndex is 0-based, annotIndex is the position in the page's annotation list. Only non-zero fields in the provided option are applied.

Example:

pdf.ModifyAnnotation(0, 0, gopdf.AnnotationOption{
    Content: "Updated note",
    Color:   [3]uint8{255, 0, 0},
})

func (*GoPdf) ModifyBookmark

func (gp *GoPdf) ModifyBookmark(index int, newTitle string) error

ModifyBookmark modifies the title of a bookmark at the given 0-based index in the flat TOC list (as returned by GetTOC).

Example:

pdf.ModifyBookmark(0, "New Chapter Title")

func (*GoPdf) ModifyElementPosition

func (gp *GoPdf) ModifyElementPosition(pageNo int, elementIndex int, x, y float64) error

ModifyElementPosition moves an element to a new (x, y) position. Works for text, image, line (moves start point), rectangle, oval, and polygon elements.

Example:

pdf.ModifyElementPosition(1, 0, 100, 200) // move element to (100, 200)

func (*GoPdf) ModifyFormFieldValue

func (gp *GoPdf) ModifyFormFieldValue(name, value string) error

ModifyFormFieldValue updates the value of an existing form field by name.

Example:

err := pdf.ModifyFormFieldValue("username", "John Doe")

func (*GoPdf) ModifyTextElement

func (gp *GoPdf) ModifyTextElement(pageNo int, elementIndex int, newText string) error

ModifyTextElement changes the text content of a text element at the given index. Returns an error if the element is not a text element.

Example:

pdf.ModifyTextElement(1, 0, "New text content")

func (*GoPdf) MovePage

func (gp *GoPdf) MovePage(from, to int) error

MovePage moves a page from one position to another. Both from and to are 1-based page numbers. The page at position 'from' is removed and re-inserted at position 'to'.

This works by using SelectPages to reorder the page sequence.

Example:

pdf.MovePage(3, 1) // move page 3 to become page 1
pdf.MovePage(1, 5) // move page 1 to position 5

func (*GoPdf) MultiCell

func (gp *GoPdf) MultiCell(rectangle *Rect, text string) error

MultiCell : create of text with line breaks ( use current x,y is upper-left corner of cell)

func (*GoPdf) MultiCellWithOption

func (gp *GoPdf) MultiCellWithOption(rectangle *Rect, text string, opt CellOption) error

MultiCellWithOption create of text with line breaks ( use current x,y is upper-left corner of cell)

func (*GoPdf) NewTableLayout

func (gp *GoPdf) NewTableLayout(startX, startY, rowHeight float64, maxRows int) TableLayout

Creates a new table layout with the given parameters

func (*GoPdf) OpenPDF

func (gp *GoPdf) OpenPDF(pdfPath string, opt *OpenPDFOption) (retErr error)

OpenPDF opens an existing PDF file and imports all pages so that new content can be drawn on top of them. After calling OpenPDF, use SetPage(n) to switch to a specific page (1-based), then use any drawing method (Text, Cell, Image, InsertHTMLBox, Line, etc.) to overlay content. Finally call WritePdf to save.

Example:

pdf := gopdf.GoPdf{}
err := pdf.OpenPDF("input.pdf", nil)
if err != nil { log.Fatal(err) }

pdf.AddTTFFont("myfont", "font.ttf")
pdf.SetFont("myfont", "", 14)

pdf.SetPage(1)
pdf.SetXY(100, 100)
pdf.Cell(nil, "Hello on page 1")

pdf.WritePdf("output.pdf")

func (*GoPdf) OpenPDFFromBytes

func (gp *GoPdf) OpenPDFFromBytes(pdfData []byte, opt *OpenPDFOption) (retErr error)

OpenPDFFromBytes opens an existing PDF from a byte slice.

func (*GoPdf) OpenPDFFromStream

func (gp *GoPdf) OpenPDFFromStream(rs *io.ReadSeeker, opt *OpenPDFOption) (retErr error)

OpenPDFFromStream opens an existing PDF from an io.ReadSeeker.

func (*GoPdf) Oval

func (gp *GoPdf) Oval(x1 float64, y1 float64, x2 float64, y2 float64)

Oval : draw oval

func (*GoPdf) PagesObjID

func (gp *GoPdf) PagesObjID() ObjID

PagesObjID returns the ObjID of the pages object.

func (*GoPdf) PlaceHolderText

func (gp *GoPdf) PlaceHolderText(placeHolderName string, placeHolderWidth float64) error

[experimental] PlaceHolderText Create a text placehold for fillin text later with function FillInPlaceHoldText.

func (*GoPdf) PointsToUnits

func (gp *GoPdf) PointsToUnits(u float64) float64

PointsToUnits converts the points to the documents unit type

func (*GoPdf) PointsToUnitsVar

func (gp *GoPdf) PointsToUnitsVar(u ...*float64)

PointsToUnitsVar converts the points to the documents unit type for all variables passed in

func (*GoPdf) Polygon

func (gp *GoPdf) Polygon(points []Point, style string)

Polygon : draw polygon

  • style: Style of polygon (draw and/or fill: D, F, DF, FD) D or empty string: draw. This is the default value. F: fill DF or FD: draw and fill

Usage:

 pdf.SetStrokeColor(255, 0, 0)
	pdf.SetLineWidth(2)
	pdf.SetFillColor(0, 255, 0)
	pdf.Polygon([]gopdf.Point{{X: 10, Y: 30}, {X: 585, Y: 200}, {X: 585, Y: 250}}, "DF")

func (*GoPdf) Polyline

func (gp *GoPdf) Polyline(points []Point)

Polyline draws an open polyline (connected line segments, not closed). Unlike Polygon, the path is not closed — only stroked.

Usage:

pdf.SetStrokeColor(255, 0, 0)
pdf.SetLineWidth(2)
pdf.Polyline([]gopdf.Point{{X: 10, Y: 30}, {X: 100, Y: 200}, {X: 200, Y: 50}})

func (*GoPdf) Read

func (gp *GoPdf) Read(p []byte) (int, error)

func (*GoPdf) RectFromLowerLeft

func (gp *GoPdf) RectFromLowerLeft(x float64, y float64, wdth float64, hght float64)

RectFromLowerLeft : draw rectangle from lower-left corner (x, y)

func (*GoPdf) RectFromLowerLeftWithOpts

func (gp *GoPdf) RectFromLowerLeftWithOpts(opts DrawableRectOptions) error

func (*GoPdf) RectFromLowerLeftWithStyle

func (gp *GoPdf) RectFromLowerLeftWithStyle(x float64, y float64, wdth float64, hght float64, style string)

RectFromLowerLeftWithStyle : draw rectangle from lower-left corner (x, y)

  • style: Style of rectangule (draw and/or fill: D, F, DF, FD) D or empty string: draw. This is the default value. F: fill DF or FD: draw and fill

func (*GoPdf) RectFromUpperLeft

func (gp *GoPdf) RectFromUpperLeft(x float64, y float64, wdth float64, hght float64)

RectFromUpperLeft : draw rectangle from upper-left corner (x, y)

func (*GoPdf) RectFromUpperLeftWithOpts

func (gp *GoPdf) RectFromUpperLeftWithOpts(opts DrawableRectOptions) error

func (*GoPdf) RectFromUpperLeftWithStyle

func (gp *GoPdf) RectFromUpperLeftWithStyle(x float64, y float64, wdth float64, hght float64, style string)

RectFromUpperLeftWithStyle : draw rectangle from upper-left corner (x, y)

  • style: Style of rectangule (draw and/or fill: D, F, DF, FD) D or empty string: draw. This is the default value. F: fill DF or FD: draw and fill

func (*GoPdf) Rectangle

func (gp *GoPdf) Rectangle(x0 float64, y0 float64, x1 float64, y1 float64, style string, radius float64, radiusPointNum int) error

Rectangle : draw rectangle, and add radius input to make a round corner, it helps to calculate the round corner coordinates and use Polygon functions to draw rectangle

  • style: Style of Rectangle (draw and/or fill: D, F, DF, FD) D or empty string: draw. This is the default value. F: fill DF or FD: draw and fill

Usage:

 pdf.SetStrokeColor(255, 0, 0)
	pdf.SetLineWidth(2)
	pdf.SetFillColor(0, 255, 0)
	pdf.Rectangle(196.6, 336.8, 398.3, 379.3, "DF", 3, 10)

func (*GoPdf) ReplaceElement

func (gp *GoPdf) ReplaceElement(pageNo int, elementIndex int, newElement ICacheContent) error

ReplaceElement replaces the content element at the given index with a new ICacheContent. This is a low-level method for advanced use cases.

func (*GoPdf) RestoreGraphicsState

func (gp *GoPdf) RestoreGraphicsState()

RestoreGraphicsState restores a previously saved graphics state. Clipping paths and transformations are reset to the saved state.

func (*GoPdf) Rotate

func (gp *GoPdf) Rotate(angle, x, y float64)

Rotate rotate text or image angle is angle in degrees. x, y is rotation center

func (*GoPdf) RotateReset

func (gp *GoPdf) RotateReset()

RotateReset reset rotate

func (*GoPdf) SaveGraphicsState

func (gp *GoPdf) SaveGraphicsState()

SaveGraphicsState saves the current graphics state. Use with RestoreGraphicsState to scope clipping paths and transformations.

func (*GoPdf) ScalePage

func (gp *GoPdf) ScalePage(sx, sy float64)

ScalePage scales the content of the current page by the given factors. sx and sy are scale factors (1.0 = no change, 0.5 = half size, 2.0 = double).

Example:

pdf.ScalePage(0.5, 0.5) // scale to 50%

func (*GoPdf) Scrub

func (gp *GoPdf) Scrub(opt ScrubOption)

Scrub removes potentially sensitive data from the PDF document. This is inspired by PyMuPDF's Document.scrub() method.

By default (with DefaultScrubOption), it removes:

  • Standard PDF metadata (author, title, subject, etc.)
  • XMP metadata streams
  • Embedded file attachments
  • Page label definitions

After scrubbing, call GarbageCollect(GCCompact) and save with a new filename to ensure removed data is physically purged.

Example:

pdf.Scrub(gopdf.DefaultScrubOption())
pdf.GarbageCollect(gopdf.GCCompact)
pdf.WritePdf("scrubbed.pdf")

func (*GoPdf) Sector

func (gp *GoPdf) Sector(cx, cy, r, startDeg, endDeg float64, style string)

Sector draws a sector (pie/fan shape) defined by a center point, radius, and start/end angles in degrees (counter-clockwise from the positive X axis).

  • cx, cy: center point
  • r: radius
  • startDeg: start angle in degrees
  • endDeg: end angle in degrees
  • style: Style of sector (draw and/or fill: D, F, DF, FD) D or empty string: draw (stroke). This is the default value. F: fill DF or FD: draw and fill

Usage:

pdf.SetStrokeColor(0, 0, 0)
pdf.SetFillColor(255, 0, 0)
pdf.Sector(200, 300, 80, 0, 90, "FD")

func (*GoPdf) SelectPages

func (gp *GoPdf) SelectPages(pages []int) (*GoPdf, error)

SelectPages rearranges the document to contain only the specified pages in the given order. Pages are 1-based and may be repeated.

This works by exporting the current document to bytes, then re-importing only the selected pages in the specified order.

Example:

// Reverse a 3-page document
newPdf, err := pdf.SelectPages([]int{3, 2, 1})

// Duplicate page 1 three times
newPdf, err := pdf.SelectPages([]int{1, 1, 1})

func (*GoPdf) SetAnchor

func (gp *GoPdf) SetAnchor(name string)

SetAnchor creates a new anchor.

func (*GoPdf) SetBookmarkStyle

func (gp *GoPdf) SetBookmarkStyle(index int, style BookmarkStyle) error

SetBookmarkStyle sets the visual style (color, bold, italic, collapsed) for a bookmark at the given 0-based index.

Example:

pdf.SetBookmarkStyle(0, gopdf.BookmarkStyle{
    Bold:   true,
    Color:  [3]float64{1, 0, 0}, // red
    Collapsed: true,
})

func (*GoPdf) SetCharSpacing

func (gp *GoPdf) SetCharSpacing(charSpacing float64) error

SetCharSpacing : set the character spacing of the currently active font

func (*GoPdf) SetColorSpace

func (gp *GoPdf) SetColorSpace(name string) error

func (*GoPdf) SetCompressLevel

func (gp *GoPdf) SetCompressLevel(level int)

SetCompressLevel : set compress Level for content streams Possible values for level:

-2 HuffmanOnly, -1 DefaultCompression (which is level 6)
 0 No compression,
 1 fastest compression, but not very good ratio
 9 best compression, but slowest

func (*GoPdf) SetCustomLineType

func (gp *GoPdf) SetCustomLineType(dashArray []float64, dashPhase float64)

SetCustomLineType : set custom line type

Usage:
pdf.SetCustomLineType([]float64{0.8, 0.8}, 0)
pdf.Line(50, 200, 550, 200)

func (*GoPdf) SetEncryption

func (gp *GoPdf) SetEncryption(config AESEncryptionConfig) error

SetEncryption configures AES encryption for the document. Supports AES-128 and AES-256 in addition to the existing RC4.

Example:

pdf.SetEncryption(gopdf.AESEncryptionConfig{
    Method:        gopdf.EncryptAES128,
    UserPassword:  "user123",
    OwnerPassword: "owner456",
    Permissions:   gopdf.PermissionsPrint | gopdf.PermissionsCopy,
})

func (*GoPdf) SetFillColor

func (gp *GoPdf) SetFillColor(r uint8, g uint8, b uint8)

SetFillColor set the color for the stroke

func (*GoPdf) SetFillColorCMYK

func (gp *GoPdf) SetFillColorCMYK(c, m, y, k uint8)

SetFillColorCMYK set the color for the fill in CMYK color mode

func (*GoPdf) SetFont

func (gp *GoPdf) SetFont(family string, style string, size interface{}) error

SetFont : set font style support "" or "U" for "B" and "I" should be loaded appropriate fonts with same styles defined size MUST be uint*, int* or float64*

func (*GoPdf) SetFontSize

func (gp *GoPdf) SetFontSize(fontSize float64) error

SetFontSize : set the font size (and only the font size) of the currently active font

func (*GoPdf) SetFontWithStyle

func (gp *GoPdf) SetFontWithStyle(family string, style int, size interface{}) error

SetFontWithStyle : set font style support Regular or Underline for Bold|Italic should be loaded appropriate fonts with same styles defined size MUST be uint*, int* or float64*

func (*GoPdf) SetGrayFill

func (gp *GoPdf) SetGrayFill(grayScale float64)

SetGrayFill set the grayscale for the fill, takes a float64 between 0.0 and 1.0

func (*GoPdf) SetGrayStroke

func (gp *GoPdf) SetGrayStroke(grayScale float64)

SetGrayStroke set the grayscale for the stroke, takes a float64 between 0.0 and 1.0

func (*GoPdf) SetInfo

func (gp *GoPdf) SetInfo(info PdfInfo)

SetInfo set Document Information Dictionary

func (*GoPdf) SetLayerUIConfig

func (gp *GoPdf) SetLayerUIConfig(config LayerUIConfig)

SetLayerUIConfig sets the UI configuration for the layer panel. This controls how layers appear in the PDF viewer's layer panel.

Example:

pdf.SetLayerUIConfig(gopdf.LayerUIConfig{
    Name:      "Default",
    BaseState: "ON",
    Locked:    []gopdf.OCG{watermarkLayer},
})

func (*GoPdf) SetLeftMargin

func (gp *GoPdf) SetLeftMargin(margin float64)

SetLeftMargin sets left margin.

func (*GoPdf) SetLineType

func (gp *GoPdf) SetLineType(linetype string)

SetLineType : set line type ("dashed" ,"dotted")

Usage:
pdf.SetLineType("dashed")
pdf.Line(50, 200, 550, 200)
pdf.SetLineType("dotted")
pdf.Line(50, 400, 550, 400)

func (*GoPdf) SetLineWidth

func (gp *GoPdf) SetLineWidth(width float64)

SetLineWidth : set line width

func (*GoPdf) SetMarginBottom

func (gp *GoPdf) SetMarginBottom(margin float64)

SetMarginBottom set the bottom margin

func (*GoPdf) SetMarginLeft

func (gp *GoPdf) SetMarginLeft(margin float64)

SetMarginLeft sets the left margin

func (*GoPdf) SetMarginRight

func (gp *GoPdf) SetMarginRight(margin float64)

SetMarginRight sets the right margin

func (*GoPdf) SetMarginTop

func (gp *GoPdf) SetMarginTop(margin float64)

SetMarginTop sets the top margin

func (*GoPdf) SetMargins

func (gp *GoPdf) SetMargins(left, top, right, bottom float64)

SetMargins defines the left, top, right and bottom margins. By default, they equal 1 cm. Call this method to change them.

func (*GoPdf) SetMarkInfo

func (gp *GoPdf) SetMarkInfo(info MarkInfo)

SetMarkInfo sets the MarkInfo dictionary in the document catalog. This indicates whether the PDF is a Tagged PDF.

Example:

pdf.SetMarkInfo(gopdf.MarkInfo{Marked: true})

func (*GoPdf) SetNewXY

func (gp *GoPdf) SetNewXY(y float64, x, h float64)

SetNewXY : set current position x and y, and modified y if add a new page. Example: For example, if the page height is set to 841px, MarginTop is 20px, MarginBottom is 10px, and the height of the element to be inserted is 25px, because 10<25, you need to add another page and set y to 20px. Because of AddPage(), X is set to MarginLeft, so you should specify X if needed, or make sure SetX() is after SetNewY().

func (*GoPdf) SetNewY

func (gp *GoPdf) SetNewY(y float64, h float64)

SetNewY : set current position y, and modified y if add a new page. Example: For example, if the page height is set to 841px, MarginTop is 20px, MarginBottom is 10px, and the height of the element(such as text) to be inserted is 25px, because 10<25, you need to add another page and set y to 20px. Because of called AddPage(), X is set to MarginLeft, so you should specify X if needed, or make sure SetX() is after SetNewY(), or using SetNewXY(). SetNewYIfNoOffset is more suitable for scenarios where the offset does not change, such as pdf.Image().

func (*GoPdf) SetNewYIfNoOffset

func (gp *GoPdf) SetNewYIfNoOffset(y float64, h float64)

SetNewYIfNoOffset : set current position y, and modified y if add a new page. Example: For example, if the page height is set to 841px, MarginTop is 20px, MarginBottom is 10px, and the height of the element(such as image) to be inserted is 200px, because 10<200, you need to add another page and set y to 20px. Tips: gp.curr.X and gp.curr.Y do not change when pdf.Image() is called.

func (*GoPdf) SetNoCompression

func (gp *GoPdf) SetNoCompression()

SetNoCompression : compressLevel = 0

func (*GoPdf) SetOCGState

func (gp *GoPdf) SetOCGState(name string, on bool) error

SetOCGState sets the initial visibility state of an existing OCG by name.

Example:

err := pdf.SetOCGState("Watermark", false)

func (*GoPdf) SetOCGStates

func (gp *GoPdf) SetOCGStates(states map[string]bool) error

SetOCGStates sets the visibility state of multiple OCGs at once. The map keys are OCG names and values are the desired visibility states.

Example:

pdf.SetOCGStates(map[string]bool{
    "Watermark":   true,
    "Draft Notes": false,
})

func (*GoPdf) SetPDFVersion

func (gp *GoPdf) SetPDFVersion(v PDFVersion)

SetPDFVersion sets the PDF version for the output document. Default is PDF 1.7. This affects the header and may enable version-specific features.

Example:

pdf.SetPDFVersion(gopdf.PDFVersion20) // output PDF 2.0

func (*GoPdf) SetPage

func (gp *GoPdf) SetPage(pageno int) error

SetPage set current page

func (*GoPdf) SetPageCropBox

func (gp *GoPdf) SetPageCropBox(pageNo int, box Box) error

SetPageCropBox sets the CropBox for a page. The CropBox defines the visible area of the page when displayed or printed. Content outside the CropBox is clipped (hidden) but not removed.

pageNo is 1-based. The box coordinates are in document units:

  • left, top: the lower-left corner of the crop area
  • right, bottom: the upper-right corner of the crop area

In PDF coordinate system, (0,0) is the bottom-left of the page.

Example:

// Crop page 1 to show only the center area
pdf.SetPageCropBox(1, Box{Left: 50, Top: 50, Right: 545, Bottom: 792})

// Remove crop box from page 1
pdf.ClearPageCropBox(1)

func (*GoPdf) SetPageLabels

func (gp *GoPdf) SetPageLabels(labels []PageLabel)

SetPageLabels sets the page label ranges for the document. Page labels define how page numbers are displayed in PDF viewers.

Example:

pdf.SetPageLabels([]gopdf.PageLabel{
    {PageIndex: 0, Style: gopdf.PageLabelRomanLower, Start: 1},  // i, ii, iii (cover pages)
    {PageIndex: 3, Style: gopdf.PageLabelDecimal, Start: 1},     // 1, 2, 3, ... (main content)
    {PageIndex: 10, Style: gopdf.PageLabelAlphaUpper, Prefix: "Appendix ", Start: 1}, // Appendix A, B, ...
})

func (*GoPdf) SetPageLayout

func (gp *GoPdf) SetPageLayout(layout PageLayout)

SetPageLayout sets the page layout for the document. This controls how pages are arranged when the document is opened.

Example:

pdf.SetPageLayout(gopdf.PageLayoutTwoColumnLeft)

func (*GoPdf) SetPageMode

func (gp *GoPdf) SetPageMode(mode PageMode)

SetPageMode sets the page mode for the document. This controls which panel is shown when the document is opened.

Note: If outlines are present, PageMode may be overridden to UseOutlines.

Example:

pdf.SetPageMode(gopdf.PageModeUseThumbs)

func (*GoPdf) SetPageRotation

func (gp *GoPdf) SetPageRotation(pageNo int, angle int) error

SetPageRotation sets the display rotation for a page. pageNo is 1-based. angle must be a multiple of 90 (0, 90, 180, 270). This sets the /Rotate entry in the page dictionary, which tells PDF viewers how to display the page. It does not modify the page content.

Example:

pdf.SetPageRotation(1, 90)  // rotate page 1 by 90 degrees clockwise

func (*GoPdf) SetStrokeColor

func (gp *GoPdf) SetStrokeColor(r uint8, g uint8, b uint8)

SetStrokeColor set the color for the stroke

func (*GoPdf) SetStrokeColorCMYK

func (gp *GoPdf) SetStrokeColorCMYK(c, m, y, k uint8)

SetStrokeColorCMYK set the color for the stroke in CMYK color mode

func (*GoPdf) SetTOC

func (gp *GoPdf) SetTOC(items []TOCItem) error

SetTOC replaces the entire outline tree with the provided TOC items. Each item's Level must be >= 1. The first item must have Level 1. Levels may increase by at most 1 from one item to the next.

Example:

pdf.SetTOC([]gopdf.TOCItem{
    {Level: 1, Title: "Chapter 1", PageNo: 1},
    {Level: 2, Title: "Section 1.1", PageNo: 1, Y: 200},
    {Level: 2, Title: "Section 1.2", PageNo: 2},
    {Level: 1, Title: "Chapter 2", PageNo: 3},
})

func (*GoPdf) SetTextColor

func (gp *GoPdf) SetTextColor(r uint8, g uint8, b uint8)

SetTextColor : function sets the text color

func (*GoPdf) SetTextColorCMYK

func (gp *GoPdf) SetTextColorCMYK(c, m, y, k uint8)

func (*GoPdf) SetTopMargin

func (gp *GoPdf) SetTopMargin(margin float64)

SetTopMargin sets top margin.

func (*GoPdf) SetTransparency

func (gp *GoPdf) SetTransparency(transparency Transparency) error

SetTransparency sets transparency. alpha: value from 0 (transparent) to 1 (opaque) blendMode: blend mode, one of the following:

Normal, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn,
HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity

func (*GoPdf) SetX

func (gp *GoPdf) SetX(x float64)

SetX : set current position X

func (*GoPdf) SetXMPMetadata

func (gp *GoPdf) SetXMPMetadata(meta XMPMetadata)

SetXMPMetadata sets the XMP metadata for the document. The XMP metadata stream will be embedded in the PDF output.

Example:

pdf.SetXMPMetadata(gopdf.XMPMetadata{
    Title:       "Annual Report 2025",
    Creator:     []string{"John Doe", "Jane Smith"},
    Description: "Company annual financial report",
    Subject:     []string{"finance", "annual report"},
    CreatorTool: "GoPDF2",
    Producer:    "GoPDF2",
    CreateDate:  time.Now(),
    ModifyDate:  time.Now(),
})

func (*GoPdf) SetXY

func (gp *GoPdf) SetXY(x, y float64)

SetXY : set current position x and y

func (*GoPdf) SetY

func (gp *GoPdf) SetY(y float64)

SetY : set current position y

func (*GoPdf) SignPDF

func (gp *GoPdf) SignPDF(cfg SignatureConfig, w io.Writer) error

SignPDF digitally signs the PDF document and writes the signed output.

This creates a PKCS#7 detached signature (adbe.pkcs7.detached) embedded in the PDF, compatible with Adobe Reader and other PDF viewers.

The signing process:

  1. Builds the PDF with a placeholder signature dictionary
  2. Computes the byte ranges excluding the signature contents
  3. Signs the byte ranges using PKCS#7
  4. Patches the signature contents into the final output

Example:

cert, _ := gopdf.LoadCertificateFromPEM("cert.pem")
key, _ := gopdf.LoadPrivateKeyFromPEM("key.pem")
pdf.SignPDF(gopdf.SignatureConfig{
    Certificate: cert,
    PrivateKey:  key,
    Reason:      "Document Approval",
    Location:    "Beijing",
}, w)

func (*GoPdf) SignPDFToFile

func (gp *GoPdf) SignPDFToFile(cfg SignatureConfig, path string) error

SignPDFToFile signs the PDF and writes it to a file.

func (*GoPdf) SplitText

func (gp *GoPdf) SplitText(text string, width float64) ([]string, error)

SplitText splits text into multiple lines based on width performing potential mid-word breaks.

func (*GoPdf) SplitTextWithOption

func (gp *GoPdf) SplitTextWithOption(text string, width float64, opt *BreakOption) ([]string, error)

SplitTextWithOption splits a text into multiple lines based on the current font size of the document. BreakOptions allow to define the behavior of the split (strict or sensitive). For more information see BreakOption.

func (*GoPdf) SplitTextWithWordWrap

func (gp *GoPdf) SplitTextWithWordWrap(text string, width float64) ([]string, error)

SplitTextWithWordWrap behaves the same way SplitText does but performs a word-wrap considering spaces in case a text line split would split a word.

func (*GoPdf) Start

func (gp *GoPdf) Start(config Config)

Start : init gopdf

func (*GoPdf) StartWithImporter deprecated

func (gp *GoPdf) StartWithImporter(config Config, importer interface{})

Deprecated: StartWithImporter is no longer needed. Use Start instead. The gofpdi importer has been replaced with a built-in implementation.

func (*GoPdf) SwitchLayer

func (gp *GoPdf) SwitchLayer(name string, exclusive bool) error

SwitchLayer changes the visibility of a layer by name, turning it on and optionally turning off all other layers.

Example:

err := pdf.SwitchLayer("Print Version", true)

func (*GoPdf) Text

func (gp *GoPdf) Text(text string) error

Text write text start at current x,y ( current y is the baseline of text )

func (*GoPdf) TransformPage

func (gp *GoPdf) TransformPage(opts PageTransformOptions)

TransformPage applies a combined transformation to the current page content. IMPORTANT: You must call TransformPageEnd() after drawing content to restore the graphics state. Failing to do so will corrupt the page's graphics state.

Example:

pdf.TransformPage(gopdf.PageTransformOptions{
    ScaleX:    0.8,
    ScaleY:    0.8,
    Rotation:  45,
    UsePageCenter: true,
})
// ... draw content ...
pdf.TransformPageEnd()

func (*GoPdf) TransformPageEnd

func (gp *GoPdf) TransformPageEnd()

TransformPageEnd should be called after TransformPage to restore the graphics state.

func (*GoPdf) UnitsToPoints

func (gp *GoPdf) UnitsToPoints(u float64) float64

UnitsToPoints converts the units to the documents unit type

func (*GoPdf) UnitsToPointsVar

func (gp *GoPdf) UnitsToPointsVar(u ...*float64)

UnitsToPointsVar converts the units to the documents unit type for all variables passed in

func (*GoPdf) UpdateEmbeddedFile

func (gp *GoPdf) UpdateEmbeddedFile(name string, ef EmbeddedFile) error

UpdateEmbeddedFile replaces the content of an existing embedded file.

Example:

err := pdf.UpdateEmbeddedFile("report.csv", gopdf.EmbeddedFile{
    Name:     "report.csv",
    Content:  newData,
    MimeType: "text/csv",
})

func (*GoPdf) UseImportedTemplate

func (gp *GoPdf) UseImportedTemplate(tplid int, x float64, y float64, w float64, h float64)

UseImportedTemplate draws an imported PDF page.

func (*GoPdf) Write deprecated

func (gp *GoPdf) Write(w io.Writer) error

Write streams the pdf as it is compiled to an io.Writer

Deprecated: use the WriteTo method instead.

func (*GoPdf) WriteIncrementalPdf

func (gp *GoPdf) WriteIncrementalPdf(pdfPath string, originalData []byte, modifiedIndices []int) error

WriteIncrementalPdf writes the document as an incremental update to a file. originalData is the original PDF bytes. If modifiedIndices is nil, all objects are written.

func (*GoPdf) WritePdf

func (gp *GoPdf) WritePdf(pdfPath string) error

WritePdf : write pdf file

func (*GoPdf) WriteTo

func (gp *GoPdf) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements the io.WriterTo interface and can be used to stream the PDF as it is compiled to an io.Writer.

type HTMLBoxOption

type HTMLBoxOption struct {
	// DefaultFontFamily is the font family used when no font is specified in HTML.
	// This font must already be added to the GoPdf instance via AddTTFFont.
	DefaultFontFamily string

	// DefaultFontSize is the default font size in points.
	DefaultFontSize float64

	// DefaultColor is the default text color (r, g, b).
	DefaultColor [3]uint8

	// LineSpacing is extra spacing between lines (in document units). Default is 0.
	LineSpacing float64

	// BoldFontFamily is the font family to use for bold text.
	// If empty, the default family is used (bold may not render if the font doesn't support it).
	BoldFontFamily string

	// ItalicFontFamily is the font family to use for italic text.
	ItalicFontFamily string

	// BoldItalicFontFamily is the font family to use for bold+italic text.
	BoldItalicFontFamily string
}

HTMLBoxOption configures the behavior of InsertHTMLBox.

type Harf

type Harf struct {
	Unicode, Isolated, Beginning, Middle, Final rune
}

Harf is the Arabic meaning of Letter, Harf holds the Arabic character with its different representation forms (glyphs).

type ICacheColorText

type ICacheColorText interface {
	ICacheContent
	// contains filtered or unexported methods
}

type ICacheContent

type ICacheContent interface {
	// contains filtered or unexported methods
}

func NewCacheContentRectangle

func NewCacheContentRectangle(pageHeight float64, rectOpts DrawableRectOptions) ICacheContent

type IFont

type IFont interface {
	Init()
	GetType() string
	GetName() string
	GetDesc() []FontDescItem
	GetUp() int
	GetUt() int
	GetCw() FontCw
	GetEnc() string
	GetDiff() string
	GetOriginalsize() int

	SetFamily(family string)
	GetFamily() string
}

IFont represents a font interface.

type IObj

type IObj interface {
	// contains filtered or unexported methods
}

IObj inteface for all pdf object

type ImageCache

type ImageCache struct {
	Path  string //ID or Path
	Index int
	Rect  *Rect
}

ImageCache is metadata for caching images.

type ImageFromOption

type ImageFromOption struct {
	Format string //jpeg,png
	X      float64
	Y      float64
	Rect   *Rect
}

type ImageHolder

type ImageHolder interface {
	ID() string
	io.Reader
}

ImageHolder hold image data

func ImageHolderByBytes

func ImageHolderByBytes(b []byte) (ImageHolder, error)

ImageHolderByBytes create ImageHolder by []byte

func ImageHolderByPath

func ImageHolderByPath(path string) (ImageHolder, error)

ImageHolderByPath create ImageHolder by image path

func ImageHolderByReader

func ImageHolderByReader(r io.Reader) (ImageHolder, error)

ImageHolderByReader create ImageHolder by io.Reader

type ImageObj

type ImageObj struct {
	//imagepath string
	IsMask       bool
	SplittedMask bool
	// contains filtered or unexported fields
}

ImageObj image object

func (*ImageObj) GetRect deprecated

func (i *ImageObj) GetRect() *Rect

GetRect get rect of img

Deprecated: This method calls log.Fatalf on error, which terminates the program. Use getRect() internally or handle the error appropriately.

func (*ImageObj) Parse

func (i *ImageObj) Parse() error

Parse parse img

func (*ImageObj) SetImage

func (i *ImageObj) SetImage(r io.Reader) error

SetImage set image

func (*ImageObj) SetImagePath

func (i *ImageObj) SetImagePath(path string) error

SetImagePath set image path

type ImageOptions

type ImageOptions struct {
	DegreeAngle    float64
	VerticalFlip   bool
	HorizontalFlip bool
	X              float64
	Y              float64
	Rect           *Rect
	Mask           *MaskOptions
	Crop           *CropOptions
	Transparency   *Transparency
	// contains filtered or unexported fields
}

type ImportedObj

type ImportedObj struct {
	Data string
}

ImportedObj : imported object

type Journal

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

Journal manages undo/redo operations for a GoPdf document.

type LayerConfig

type LayerConfig struct {
	// Name is the display name of this configuration.
	Name string
	// Creator is an optional creator string.
	Creator string
	// OnOCGs lists OCGs that should be ON in this configuration.
	OnOCGs []OCG
	// OffOCGs lists OCGs that should be OFF in this configuration.
	OffOCGs []OCG
	// Order defines the display order of OCGs in the layer panel.
	// If nil, all document OCGs are listed in document order.
	Order []OCG
}

LayerConfig represents a named layer configuration. Alternate configurations allow switching between different layer visibility presets.

type LayerUIConfig

type LayerUIConfig struct {
	// Name is the display name shown in the layer panel.
	Name string
	// Creator is an optional creator string.
	Creator string
	// BaseState is the default visibility state: "ON", "OFF", or "Unchanged".
	BaseState string
	// Locked lists OCGs that cannot be toggled by the user.
	Locked []OCG
}

LayerUIConfig represents the UI configuration for the layer panel.

type LineEndingStyle

type LineEndingStyle string

LineEndingStyle represents PDF line ending styles.

const (
	LineEndNone         LineEndingStyle = "None"
	LineEndSquare       LineEndingStyle = "Square"
	LineEndCircle       LineEndingStyle = "Circle"
	LineEndDiamond      LineEndingStyle = "Diamond"
	LineEndOpenArrow    LineEndingStyle = "OpenArrow"
	LineEndClosedArrow  LineEndingStyle = "ClosedArrow"
	LineEndButt         LineEndingStyle = "Butt"
	LineEndROpenArrow   LineEndingStyle = "ROpenArrow"
	LineEndRClosedArrow LineEndingStyle = "RClosedArrow"
	LineEndSlash        LineEndingStyle = "Slash"
)

type LinkInfo

type LinkInfo struct {
	// Index is the position of this link in the page's link list.
	Index int
	// X, Y, W, H define the link rectangle in document units.
	X, Y, W, H float64
	// URL is the external URL (empty for internal links).
	URL string
	// Anchor is the internal anchor name (empty for external links).
	Anchor string
	// IsExternal is true for external URL links, false for internal anchors.
	IsExternal bool
}

LinkInfo represents a link found on a PDF page.

type MapOfCharacterToGlyphIndex

type MapOfCharacterToGlyphIndex struct {
	Keys []rune
	Vals []uint
	// contains filtered or unexported fields
}

MapOfCharacterToGlyphIndex map of CharacterToGlyphIndex

func NewMapOfCharacterToGlyphIndex

func NewMapOfCharacterToGlyphIndex() *MapOfCharacterToGlyphIndex

NewMapOfCharacterToGlyphIndex new CharacterToGlyphIndex

func (*MapOfCharacterToGlyphIndex) AllKeys

func (m *MapOfCharacterToGlyphIndex) AllKeys() []rune

AllKeys get keys

func (*MapOfCharacterToGlyphIndex) AllVals

func (m *MapOfCharacterToGlyphIndex) AllVals() []uint

AllVals get all values

func (*MapOfCharacterToGlyphIndex) Index

func (m *MapOfCharacterToGlyphIndex) Index(k rune) (int, bool)

Index get index by key

func (*MapOfCharacterToGlyphIndex) KeyExists

func (m *MapOfCharacterToGlyphIndex) KeyExists(k rune) bool

KeyExists key is exists?

func (*MapOfCharacterToGlyphIndex) Set

func (m *MapOfCharacterToGlyphIndex) Set(k rune, v uint)

Set set key and value to map

func (*MapOfCharacterToGlyphIndex) Val

Val get value by Key

type Margins

type Margins struct {
	Left, Top, Right, Bottom float64
}

Margins type.

type MarkInfo

type MarkInfo struct {
	// Marked indicates whether the document conforms to Tagged PDF conventions.
	Marked bool
	// UserProperties indicates whether the document contains user properties.
	UserProperties bool
	// Suspects indicates whether the document contains suspects (tag structure may be incorrect).
	Suspects bool
}

MarkInfo represents the PDF MarkInfo dictionary, which indicates whether the document conforms to Tagged PDF conventions.

type MaskOptions

type MaskOptions struct {
	ImageOptions
	BBox   *[4]float64
	Holder ImageHolder
}

type Matrix

type Matrix struct {
	A, B, C, D, E, F float64
}

Matrix represents a 2D affine transformation matrix [a b c d e f]. The transformation is:

x' = a*x + c*y + e
y' = b*x + d*y + f

func IdentityMatrix

func IdentityMatrix() Matrix

IdentityMatrix returns the identity transformation matrix.

func ParseMatrix

func ParseMatrix(s string) (Matrix, error)

ParseMatrix parses a matrix from a PDF content stream "a b c d e f" format. Handles cases where negative numbers may not have spaces before them (e.g., "1 0 0 1-10 20").

func RotateMatrix

func RotateMatrix(degrees float64) Matrix

RotateMatrix returns a rotation matrix for the given angle in degrees.

func ScaleMatrix

func ScaleMatrix(sx, sy float64) Matrix

ScaleMatrix returns a scaling matrix.

func SkewMatrix

func SkewMatrix(angleX, angleY float64) Matrix

SkewMatrix returns a skew transformation matrix.

func TranslateMatrix

func TranslateMatrix(tx, ty float64) Matrix

TranslateMatrix returns a translation matrix.

func (Matrix) Determinant

func (m Matrix) Determinant() float64

Determinant returns the determinant of the matrix.

func (Matrix) Inverse

func (m Matrix) Inverse() Matrix

Inverse returns the inverse of the matrix, or the identity matrix if not invertible.

func (Matrix) IsIdentity

func (m Matrix) IsIdentity() bool

IsIdentity returns true if this is the identity matrix.

func (Matrix) Multiply

func (m Matrix) Multiply(other Matrix) Matrix

Multiply returns the product of m and other (m * other).

func (Matrix) String

func (m Matrix) String() string

String returns a string representation of the matrix.

func (Matrix) TransformPoint

func (m Matrix) TransformPoint(x, y float64) (float64, float64)

TransformPoint applies the matrix transformation to a point.

func (Matrix) TransformRect

func (m Matrix) TransformRect(r RectFrom) RectFrom

TransformRect applies the matrix transformation to a rectangle.

type OCG

type OCG struct {
	// Name is the display name of the layer.
	Name string
	// Intent is the visibility intent ("View" or "Design").
	Intent OCGIntent
	// On indicates whether the layer is initially visible.
	On bool
	// contains filtered or unexported fields
}

OCG represents an Optional Content Group (layer) in a PDF. OCGs allow content to be selectively shown or hidden.

type OCGIntent

type OCGIntent string

OCGIntent represents the intent of an Optional Content Group.

const (
	// OCGIntentView indicates the OCG is for viewing purposes.
	OCGIntentView OCGIntent = "View"
	// OCGIntentDesign indicates the OCG is for design purposes.
	OCGIntentDesign OCGIntent = "Design"
)

type OCGVisibilityPolicy

type OCGVisibilityPolicy string

OCGVisibilityPolicy defines how OCMD member OCGs are combined.

const (
	// OCGVisibilityAllOn means all member OCGs must be ON for content to be visible.
	OCGVisibilityAllOn OCGVisibilityPolicy = "AllOn"
	// OCGVisibilityAnyOn means any member OCG being ON makes content visible.
	OCGVisibilityAnyOn OCGVisibilityPolicy = "AnyOn"
	// OCGVisibilityAllOff means all member OCGs must be OFF for content to be visible.
	OCGVisibilityAllOff OCGVisibilityPolicy = "AllOff"
	// OCGVisibilityAnyOff means any member OCG being OFF makes content visible.
	OCGVisibilityAnyOff OCGVisibilityPolicy = "AnyOff"
)

type OCMD

type OCMD struct {
	// OCGs is the list of member OCGs.
	OCGs []OCG
	// Policy determines how member visibility is combined.
	Policy OCGVisibilityPolicy
	// contains filtered or unexported fields
}

OCMD represents an Optional Content Membership Dictionary. It combines multiple OCGs with a visibility policy.

type ObjID

type ObjID int

ObjID represents a typed PDF object identifier. It wraps the 0-based index into the pdfObjs array and provides safe conversion to 1-based PDF object references.

This replaces raw int indices throughout the codebase, providing type safety and preventing accidental misuse of array indices as PDF object IDs (or vice versa).

func (ObjID) Index

func (id ObjID) Index() int

Index returns the 0-based array index.

func (ObjID) IsValid

func (id ObjID) IsValid() bool

IsValid returns true if the ObjID points to a valid object.

func (ObjID) Ref

func (id ObjID) Ref() int

Ref returns the 1-based PDF object reference number.

func (ObjID) RefStr

func (id ObjID) RefStr() string

RefStr returns the PDF indirect reference string (e.g. "5 0 R").

type OpenPDFOption

type OpenPDFOption struct {
	// Box specifies which PDF box to use when importing pages.
	// Valid values: "/MediaBox", "/CropBox", "/BleedBox", "/TrimBox", "/ArtBox".
	// Default: "/MediaBox".
	Box string

	// Protection sets password protection on the output PDF.
	Protection *PDFProtectionConfig

	// Password is the user or owner password for opening encrypted PDFs.
	// If the PDF is encrypted and no password is provided, OpenPDF returns
	// ErrEncryptedPDF. Supports RC4 encryption (V1/V2, R2/R3).
	Password string
}

OpenPDFOption configures how an existing PDF is opened.

type OutlineNode

type OutlineNode struct {
	Obj      *OutlineObj
	Children []*OutlineNode
}

OutlineNode is a node of outline

func (OutlineNode) Parse

func (obj OutlineNode) Parse()

Parse parse outline

type OutlineNodes

type OutlineNodes []*OutlineNode

OutlineNodes are all nodes of outline

func (OutlineNodes) Parse

func (objs OutlineNodes) Parse()

Parse parse outline nodes

type OutlineObj

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

OutlineObj include attribute of outline

func (*OutlineObj) GetIndex

func (o *OutlineObj) GetIndex() int

func (*OutlineObj) SetFirst

func (o *OutlineObj) SetFirst(first int)

func (*OutlineObj) SetLast

func (o *OutlineObj) SetLast(last int)

func (*OutlineObj) SetNext

func (o *OutlineObj) SetNext(next int)

func (*OutlineObj) SetParent

func (o *OutlineObj) SetParent(parent int)

func (*OutlineObj) SetPrev

func (o *OutlineObj) SetPrev(prev int)

type OutlinesObj

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

OutlinesObj : outlines dictionary

func (*OutlinesObj) AddOutline

func (o *OutlinesObj) AddOutline(dest int, title string)

func (*OutlinesObj) AddOutlinesWithPosition

func (o *OutlinesObj) AddOutlinesWithPosition(dest int, title string, y float64) *OutlineObj

AddOutlinesWithPosition add outlines with position

func (*OutlinesObj) Count

func (o *OutlinesObj) Count() int

func (*OutlinesObj) SetIndexObjOutlines

func (o *OutlinesObj) SetIndexObjOutlines(index int)

type PDFAConformanceLevel

type PDFAConformanceLevel string

PDFAConformanceLevel represents the PDF/A conformance level.

const (
	PDFA1b PDFAConformanceLevel = "PDF/A-1b"
	PDFA1a PDFAConformanceLevel = "PDF/A-1a"
	PDFA2b PDFAConformanceLevel = "PDF/A-2b"
	PDFA2a PDFAConformanceLevel = "PDF/A-2a"
)

type PDFAValidationError

type PDFAValidationError struct {
	// Code is a short identifier for the error type.
	Code string
	// Message describes the violation.
	Message string
	// Clause references the PDF/A specification clause.
	Clause string
}

PDFAValidationError represents a single PDF/A compliance violation.

type PDFAValidationResult

type PDFAValidationResult struct {
	// IsValid is true if the document passes all checks for the target level.
	IsValid bool
	// Level is the target conformance level that was checked.
	Level PDFAConformanceLevel
	// Errors lists all compliance violations found.
	Errors []PDFAValidationError
	// Warnings lists non-critical issues.
	Warnings []string
}

PDFAValidationResult holds the result of a PDF/A compliance check.

func ValidatePDFA

func ValidatePDFA(pdfData []byte, level PDFAConformanceLevel) PDFAValidationResult

ValidatePDFA checks if the given PDF data conforms to the specified PDF/A level. This performs basic structural checks — it is not a full PDF/A validator but catches the most common compliance issues.

Checks performed:

  • PDF version compatibility
  • XMP metadata presence and PDF/A identification
  • Document info dictionary consistency
  • Font embedding (all fonts must be embedded)
  • Encryption (not allowed in PDF/A-1)
  • Transparency (not allowed in PDF/A-1)
  • JavaScript/actions (not allowed)

Example:

data, _ := os.ReadFile("document.pdf")
result := gopdf.ValidatePDFA(data, gopdf.PDFA1b)
if result.IsValid {
    fmt.Println("Document is PDF/A-1b compliant")
} else {
    for _, e := range result.Errors {
        fmt.Printf("Error [%s]: %s\n", e.Code, e.Message)
    }
}

type PDFDiffOptions

type PDFDiffOptions struct {
	// CompareText enables text content comparison. Default: true.
	CompareText bool
	// CompareImages enables image count comparison. Default: true.
	CompareImages bool
	// CompareFonts enables font comparison. Default: true.
	CompareFonts bool
	// CompareMetadata enables metadata comparison. Default: false.
	CompareMetadata bool
	// CompareAnnotations enables annotation comparison. Default: false.
	CompareAnnotations bool
	// TextTolerance is the position tolerance for text comparison (in points).
	// Default: 2.0.
	TextTolerance float64
	// Pages limits comparison to specific pages (0-based). Empty = all pages.
	Pages []int
}

PDFDiffOptions configures the comparison behavior.

type PDFDiffResult

type PDFDiffResult struct {
	// Differences lists all found differences.
	Differences []PDFDifference
	// IsIdentical is true if no differences were found.
	IsIdentical bool
	// Summary provides a brief overview.
	Summary string
	// PageCount1 is the page count of the first document.
	PageCount1 int
	// PageCount2 is the page count of the second document.
	PageCount2 int
}

PDFDiffResult holds the complete comparison result.

func ComparePDF

func ComparePDF(pdfData1, pdfData2 []byte, opts *PDFDiffOptions) (*PDFDiffResult, error)

ComparePDF compares two PDF documents and returns their differences.

Example:

data1, _ := os.ReadFile("original.pdf")
data2, _ := os.ReadFile("modified.pdf")
result, _ := gopdf.ComparePDF(data1, data2, nil)
if result.IsIdentical {
    fmt.Println("Documents are identical")
} else {
    for _, d := range result.Differences {
        fmt.Printf("[%s] Page %d: %s\n", d.Type, d.PageIndex, d.Description)
    }
}

type PDFDifference

type PDFDifference struct {
	// Type is the kind of difference.
	Type DiffType
	// PageIndex is the 0-based page index (-1 for document-level diffs).
	PageIndex int
	// Description is a human-readable description of the difference.
	Description string
	// Detail1 is detail from the first document.
	Detail1 string
	// Detail2 is detail from the second document.
	Detail2 string
}

PDFDifference represents a single difference between two PDF documents.

type PDFObject

type PDFObject struct {
	// Num is the object number.
	Num int
	// Generation is the generation number (usually 0).
	Generation int
	// Dict is the dictionary content (between << >>).
	Dict string
	// Stream is the raw stream data (nil if not a stream object).
	Stream []byte
	// Raw is the full raw object content between "N 0 obj" and "endobj".
	Raw string
}

PDFObject represents a parsed low-level PDF object.

func GetCatalog

func GetCatalog(pdfData []byte) (*PDFObject, error)

GetCatalog returns the PDF Catalog dictionary object.

Example:

catalog, err := gopdf.GetCatalog(data)
fmt.Println(catalog.Dict)

func ReadObject

func ReadObject(pdfData []byte, objNum int) (*PDFObject, error)

ReadObject reads a PDF object definition by object number. Returns the parsed object with its dictionary and optional stream.

Example:

data, _ := os.ReadFile("input.pdf")
obj, err := gopdf.ReadObject(data, 5)
fmt.Println(obj.Dict)

type PDFProtection

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

PDFProtection protection in pdf

func (*PDFProtection) EncryptionObj

func (p *PDFProtection) EncryptionObj() *EncryptionObj

EncryptionObj get Encryption Object

func (*PDFProtection) Objectkey

func (p *PDFProtection) Objectkey(objID int) []byte

Objectkey create object key from ObjID

func (*PDFProtection) SetProtection

func (p *PDFProtection) SetProtection(permissions int, userPass []byte, ownerPass []byte) error

SetProtection set protection information

type PDFProtectionConfig

type PDFProtectionConfig struct {
	UseProtection bool
	Permissions   int
	UserPass      []byte
	OwnerPass     []byte
}

PDFProtectionConfig config of pdf protection

type PDFVersion

type PDFVersion int

PDFVersion represents the PDF specification version.

const (
	// PDFVersion14 is PDF 1.4 (Acrobat 5). Supports transparency.
	PDFVersion14 PDFVersion = 14
	// PDFVersion15 is PDF 1.5 (Acrobat 6). Supports object/xref streams.
	PDFVersion15 PDFVersion = 15
	// PDFVersion16 is PDF 1.6 (Acrobat 7). Supports OpenType fonts.
	PDFVersion16 PDFVersion = 16
	// PDFVersion17 is PDF 1.7 (Acrobat 8, ISO 32000-1). Default.
	PDFVersion17 PDFVersion = 17
	// PDFVersion20 is PDF 2.0 (ISO 32000-2).
	PDFVersion20 PDFVersion = 20
)

func (PDFVersion) Header

func (v PDFVersion) Header() string

Header returns the full PDF header line (e.g. "%PDF-1.7").

func (PDFVersion) String

func (v PDFVersion) String() string

String returns the PDF version header string (e.g. "1.7").

type PageInfo

type PageInfo struct {
	// Width is the page width in points.
	Width float64
	// Height is the page height in points.
	Height float64
	// PageNumber is the 1-based page number.
	PageNumber int
}

PageInfo contains information about a PDF page.

type PageLabel

type PageLabel struct {
	// PageIndex is the 0-based page index where this label range starts.
	PageIndex int

	// Style is the numbering style.
	Style PageLabelStyle

	// Prefix is an optional string prefix prepended to the page number.
	// For example, "A-" would produce labels like "A-1", "A-2", etc.
	Prefix string

	// Start is the starting number for this range (default 1).
	// For example, Start=5 with Style=Decimal produces "5", "6", "7", ...
	Start int
}

PageLabel defines a page labeling range. A page label range starts at a specific page index (0-based) and applies to all subsequent pages until the next range.

type PageLabelStyle

type PageLabelStyle string

PageLabelStyle defines the numbering style for page labels.

const (
	// PageLabelDecimal uses decimal Arabic numerals (1, 2, 3, ...).
	PageLabelDecimal PageLabelStyle = "D"
	// PageLabelRomanUpper uses uppercase Roman numerals (I, II, III, ...).
	PageLabelRomanUpper PageLabelStyle = "R"
	// PageLabelRomanLower uses lowercase Roman numerals (i, ii, iii, ...).
	PageLabelRomanLower PageLabelStyle = "r"
	// PageLabelAlphaUpper uses uppercase letters (A, B, C, ...).
	PageLabelAlphaUpper PageLabelStyle = "A"
	// PageLabelAlphaLower uses lowercase letters (a, b, c, ...).
	PageLabelAlphaLower PageLabelStyle = "a"
	// PageLabelNone uses no numbering; only the prefix is shown.
	PageLabelNone PageLabelStyle = ""
)

type PageLayout

type PageLayout string

PageLayout controls how pages are displayed when the document is opened.

const (
	// PageLayoutSinglePage displays one page at a time.
	PageLayoutSinglePage PageLayout = "SinglePage"
	// PageLayoutOneColumn displays pages in one continuous column.
	PageLayoutOneColumn PageLayout = "OneColumn"
	// PageLayoutTwoColumnLeft displays pages in two columns, odd pages on left.
	PageLayoutTwoColumnLeft PageLayout = "TwoColumnLeft"
	// PageLayoutTwoColumnRight displays pages in two columns, odd pages on right.
	PageLayoutTwoColumnRight PageLayout = "TwoColumnRight"
	// PageLayoutTwoPageLeft displays two pages at a time, odd pages on left.
	PageLayoutTwoPageLeft PageLayout = "TwoPageLeft"
	// PageLayoutTwoPageRight displays two pages at a time, odd pages on right.
	PageLayoutTwoPageRight PageLayout = "TwoPageRight"
)

type PageMode

type PageMode string

PageMode controls what panel is displayed when the document is opened.

const (
	// PageModeUseNone shows no panel (default).
	PageModeUseNone PageMode = "UseNone"
	// PageModeUseOutlines shows the bookmarks/outline panel.
	PageModeUseOutlines PageMode = "UseOutlines"
	// PageModeUseThumbs shows the page thumbnails panel.
	PageModeUseThumbs PageMode = "UseThumbs"
	// PageModeFullScreen opens in full-screen mode.
	PageModeFullScreen PageMode = "FullScreen"
	// PageModeUseOC shows the optional content (layers) panel.
	PageModeUseOC PageMode = "UseOC"
	// PageModeUseAttachments shows the attachments panel.
	PageModeUseAttachments PageMode = "UseAttachments"
)

type PageObj

type PageObj struct {
	Contents        string
	ResourcesRelate string

	LinkObjIds []int
	// contains filtered or unexported fields
}

PageObj pdf page object

type PageOption

type PageOption struct {
	TrimBox  *Box
	PageSize *Rect
}

PageOption option of page

type PageTransformOptions

type PageTransformOptions struct {
	// ScaleX is the horizontal scale factor (1.0 = no change).
	ScaleX float64
	// ScaleY is the vertical scale factor (1.0 = no change).
	ScaleY float64
	// Rotation is the rotation angle in degrees (clockwise).
	Rotation float64
	// TranslateX is the horizontal translation in points.
	TranslateX float64
	// TranslateY is the vertical translation in points.
	TranslateY float64
	// OriginX, OriginY define the transformation origin point.
	// Default: center of the page.
	OriginX, OriginY float64
	// UsePageCenter uses the page center as the origin (overrides OriginX/Y).
	UsePageCenter bool
}

PageTransformOptions configures a page-level transformation.

type PagesObj

type PagesObj struct {
	PageCount int
	Kids      string
	// contains filtered or unexported fields
}

PagesObj pdf pages object

type PaintStyle

type PaintStyle string
const (
	DrawPaintStyle     PaintStyle = "S"
	FillPaintStyle     PaintStyle = "f"
	DrawFillPaintStyle PaintStyle = "B"
)

type PdfDictionaryObj

type PdfDictionaryObj struct {
	PtrToSubsetFontObj *SubsetFontObj
	// contains filtered or unexported fields
}

PdfDictionaryObj pdf dictionary object

func (*PdfDictionaryObj) AddCompositeGlyphs

func (p *PdfDictionaryObj) AddCompositeGlyphs(glyphArray *[]int, glyph int)

AddCompositeGlyphs add composite glyph composite glyph is a Unicode entity that can be defined as a sequence of one or more other characters.

func (*PdfDictionaryObj) GetOffset

func (p *PdfDictionaryObj) GetOffset(glyph int) int

GetOffset get offset from glyf table

func (*PdfDictionaryObj) SetPtrToSubsetFontObj

func (p *PdfDictionaryObj) SetPtrToSubsetFontObj(ptr *SubsetFontObj)

SetPtrToSubsetFontObj set subsetFontObj pointer

type PdfInfo

type PdfInfo struct {
	Title        string    // The document’s title
	Author       string    // The name of the person who created the document
	Subject      string    // The subject of the document
	Creator      string    // If the document was converted to PDF from another format, the name of the application which created the original document
	Producer     string    // If the document was converted to PDF from another format, the name of the application that converted the original document to PDF
	CreationDate time.Time // The date and time the document was created, in human-readable form
}

PdfInfo Document Information Dictionary

type PlaceHolderTextOption

type PlaceHolderTextOption struct {
	//Left 8 , Right 2 ,Center  16
	Align int
}

type Point

type Point struct {
	X float64
	Y float64
}

Point a point in a two-dimensional

type ProcSetObj

type ProcSetObj struct {
	//Font
	Relates             RelateFonts
	RelateColorSpaces   RelateColorSpaces
	RelateXobjs         RelateXobjects
	ExtGStates          []ExtGS
	ImportedTemplateIds map[string]int
	// contains filtered or unexported fields
}

ProcSetObj is a PDF procSet object.

type RGBColor

type RGBColor struct {
	R uint8 // Red component (0-255)
	G uint8 // Green component (0-255)
	B uint8 // Blue component (0-255)
}

Represents an RGB color with red, green, and blue components

type RecompressOption

type RecompressOption struct {
	// Format is the target format: "jpeg" or "png". Default: "jpeg".
	Format string
	// JPEGQuality is the JPEG quality (1-100). Default: 75.
	JPEGQuality int
	// MaxWidth limits the maximum image width. 0 means no limit.
	MaxWidth int
	// MaxHeight limits the maximum image height. 0 means no limit.
	MaxHeight int
}

RecompressOption configures how images are recompressed.

type Rect

type Rect struct {
	W float64
	H float64
	// contains filtered or unexported fields
}

Rect defines a rectangle.

func PaperSize

func PaperSize(name string) *Rect

PaperSize returns the page size Rect for a given paper name. Supported names: a0–a10, b0–b10, letter, legal, tabloid, ledger, statement, executive, folio, quarto. Append "-l" for landscape (e.g. "a4-l", "letter-l"). The name is case-insensitive. Returns nil if the name is not recognized.

func (*Rect) PointsToUnits

func (rect *Rect) PointsToUnits(t int) (r *Rect)

PointsToUnits converts the rectangles width and height to Units. When this is called it is assumed the values of the rectangle are in Points

func (*Rect) UnitsToPoints

func (rect *Rect) UnitsToPoints(t int) (r *Rect)

UnitsToPoints converts the rectanlges width and height to Points. When this is called it is assumed the values of the rectangle are in Units

type RectFrom

type RectFrom struct {
	X, Y, W, H float64
}

RectFrom creates a Rect positioned at (x, y) with width w and height h. This is a convenience for working with positioned rectangles.

func (RectFrom) Area

func (r RectFrom) Area() float64

Area returns the area of the rectangle.

func (RectFrom) Center

func (r RectFrom) Center() Point

Center returns the center point of the rectangle.

func (RectFrom) Contains

func (r RectFrom) Contains(px, py float64) bool

Contains returns true if point (px, py) is inside the rectangle.

func (RectFrom) ContainsRect

func (r RectFrom) ContainsRect(other RectFrom) bool

ContainsRect returns true if other is entirely inside r.

func (RectFrom) Intersection

func (r RectFrom) Intersection(other RectFrom) RectFrom

Intersection returns the overlapping area of two rectangles. Returns a zero RectFrom if they don't overlap.

func (RectFrom) Intersects

func (r RectFrom) Intersects(other RectFrom) bool

Intersects returns true if r and other overlap.

func (RectFrom) IsEmpty

func (r RectFrom) IsEmpty() bool

IsEmpty returns true if the rectangle has zero or negative area.

func (RectFrom) Normalize

func (r RectFrom) Normalize() RectFrom

Normalize ensures W and H are positive, adjusting X and Y if needed.

func (RectFrom) Union

func (r RectFrom) Union(other RectFrom) RectFrom

Union returns the smallest rectangle that contains both r and other.

type RedactionOptions

type RedactionOptions struct {
	// FillColor is the color to fill the redacted area. Default: black.
	FillColor [3]uint8
	// OverlayText is optional text to display over the redacted area.
	OverlayText string
	// OverlayFontSize is the font size for overlay text. Default: 10.
	OverlayFontSize float64
	// OverlayColor is the color for overlay text. Default: white.
	OverlayColor [3]uint8
	// RemoveUnderlyingContent controls whether to remove content under redaction.
	RemoveUnderlyingContent bool
}

RedactionOptions configures enhanced redaction behavior.

type RelateColorSpace

type RelateColorSpace struct {
	Name string
	//etc /CS1
	CountOfColorSpace int
	//etc  5 0 R
	IndexOfObj int
}

type RelateColorSpaces

type RelateColorSpaces []RelateColorSpace

type RelateFont

type RelateFont struct {
	Family string
	//etc /F1
	CountOfFont int
	//etc  5 0 R
	IndexOfObj int
	Style      int // Regular|Bold|Italic
}

RelateFont is a metadata index for fonts?

type RelateFonts

type RelateFonts []RelateFont

RelateFonts is a slice of RelateFont.

func (*RelateFonts) IsContainsFamily

func (re *RelateFonts) IsContainsFamily(family string) bool

IsContainsFamily checks if font family exists.

func (*RelateFonts) IsContainsFamilyAndStyle

func (re *RelateFonts) IsContainsFamilyAndStyle(family string, style int) bool

IsContainsFamilyAndStyle checks if font with same name and style already exists .

type RelateXobject

type RelateXobject struct {
	IndexOfObj int
}

RelateXobject is an index for ???

type RelateXobjects

type RelateXobjects []RelateXobject

RelateXobjects is a slice of RelateXobject.

type RenderOption

type RenderOption struct {
	// DPI is the resolution in dots per inch. Default: 72 (1:1 with PDF points).
	DPI float64

	// Background is the background color. Default: white.
	Background color.Color
}

RenderOption configures page rendering to an image.

type ReplaceTextOptions

type ReplaceTextOptions struct {
	// CaseInsensitive enables case-insensitive matching.
	CaseInsensitive bool
	// MaxReplacements limits the number of replacements (0 = unlimited).
	MaxReplacements int
	// Pages limits replacement to specific pages (0-based). Empty = all pages.
	Pages []int
}

ReplaceTextOptions configures text replacement behavior.

type RowCell

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

func NewRowCell

func NewRowCell(content string, cellStyle CellStyle) RowCell

type SMask

type SMask struct {
	Index                         int
	TransparencyXObjectGroupIndex int
	S                             string
	// contains filtered or unexported fields
}

SMask smask

func GetCachedMask

func GetCachedMask(opts SMaskOptions, gp *GoPdf) SMask

type SMaskMap

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

func NewSMaskMap

func NewSMaskMap() SMaskMap

func (*SMaskMap) Find

func (smask *SMaskMap) Find(sMask SMaskOptions) (SMask, bool)

func (*SMaskMap) Save

func (smask *SMaskMap) Save(id string, sMask SMask) SMask

type SMaskOptions

type SMaskOptions struct {
	TransparencyXObjectGroupIndex int
	Subtype                       SMaskSubtypes
}

func (SMaskOptions) GetId

func (smask SMaskOptions) GetId() string

type SMaskSubtypes

type SMaskSubtypes string

type SVGOption

type SVGOption struct {
	// X is the left position in page units.
	X float64
	// Y is the top position in page units.
	Y float64
	// Width is the target width. If 0, uses the SVG's native width.
	Width float64
	// Height is the target height. If 0, uses the SVG's native height.
	Height float64
}

SVGOption configures how an SVG is rendered into the PDF.

type ScrubOption

type ScrubOption struct {
	// Metadata removes standard PDF metadata (/Info dictionary).
	Metadata bool
	// XMLMetadata removes XMP metadata stream.
	XMLMetadata bool
	// EmbeddedFiles removes all embedded file attachments.
	EmbeddedFiles bool
	// PageLabels removes page label definitions.
	PageLabels bool
}

ScrubOption controls which sensitive data to remove from the PDF.

func DefaultScrubOption

func DefaultScrubOption() ScrubOption

DefaultScrubOption returns a ScrubOption with all options enabled.

type SignatureConfig

type SignatureConfig struct {
	// Certificate is the X.509 signing certificate.
	Certificate *x509.Certificate
	// CertificateChain is the optional intermediate certificate chain.
	CertificateChain []*x509.Certificate
	// PrivateKey is the signer's private key (must be *rsa.PrivateKey or *ecdsa.PrivateKey).
	PrivateKey crypto.Signer

	// Reason is the reason for signing (e.g. "Approved").
	Reason string
	// Location is the signing location (e.g. "Beijing").
	Location string
	// ContactInfo is the signer's contact information.
	ContactInfo string
	// Name is the signer's name. If empty, the certificate's CN is used.
	Name string

	// SignTime is the signing time. Defaults to time.Now().
	SignTime time.Time

	// SignatureFieldName is the name of the signature form field.
	// If empty, defaults to "Signature1".
	SignatureFieldName string

	// Visible controls whether the signature has a visible appearance.
	Visible bool
	// X, Y, W, H define the visible signature rectangle (only used when Visible is true).
	X, Y, W, H float64
	// PageNo is the 1-based page number for the visible signature. Default: 1.
	PageNo int
}

SignatureConfig holds the configuration for digitally signing a PDF.

type SignatureVerifyResult

type SignatureVerifyResult struct {
	// SignerName is the common name from the signing certificate.
	SignerName string
	// Valid is true if the signature is cryptographically valid.
	Valid bool
	// Reason is the stated reason for signing.
	Reason string
	// Location is the stated signing location.
	Location string
	// SignTime is the stated signing time.
	SignTime time.Time
	// Error contains the verification error, if any.
	Error error
}

SignatureVerifyResult holds the result of verifying a single PDF signature.

func VerifySignature

func VerifySignature(pdfData []byte) ([]SignatureVerifyResult, error)

VerifySignature verifies digital signatures in a PDF byte slice. It extracts PKCS#7 signatures and validates them against the signed byte ranges.

func VerifySignatureFromFile

func VerifySignatureFromFile(path string) ([]SignatureVerifyResult, error)

VerifySignatureFromFile reads a signed PDF file and verifies its digital signatures.

type StampName

type StampName string

StampName represents predefined PDF stamp names.

const (
	StampApproved            StampName = "Approved"
	StampAsIs                StampName = "AsIs"
	StampConfidential        StampName = "Confidential"
	StampDepartmental        StampName = "Departmental"
	StampDraft               StampName = "Draft"
	StampExperimental        StampName = "Experimental"
	StampExpired             StampName = "Expired"
	StampFinal               StampName = "Final"
	StampForComment          StampName = "ForComment"
	StampForPublicRelease    StampName = "ForPublicRelease"
	StampNotApproved         StampName = "NotApproved"
	StampNotForPublicRelease StampName = "NotForPublicRelease"
	StampSold                StampName = "Sold"
	StampTopSecret           StampName = "TopSecret"
)

type SubfontDescriptorObj

type SubfontDescriptorObj struct {
	PtrToSubsetFontObj *SubsetFontObj
	// contains filtered or unexported fields
}

SubfontDescriptorObj pdf subfont descriptorObj object

func (*SubfontDescriptorObj) SetIndexObjPdfDictionary

func (s *SubfontDescriptorObj) SetIndexObjPdfDictionary(index int)

SetIndexObjPdfDictionary set PdfDictionary pointer

func (*SubfontDescriptorObj) SetPtrToSubsetFontObj

func (s *SubfontDescriptorObj) SetPtrToSubsetFontObj(ptr *SubsetFontObj)

SetPtrToSubsetFontObj set SubsetFont pointer

type SubsetFontObj

type SubsetFontObj struct {
	Family                string
	CharacterToGlyphIndex *MapOfCharacterToGlyphIndex
	CountOfFont           int
	// contains filtered or unexported fields
}

SubsetFontObj pdf subsetFont object

func (*SubsetFontObj) AddChars

func (s *SubsetFontObj) AddChars(txt string) (string, error)

AddChars add char to map CharacterToGlyphIndex

func (*SubsetFontObj) CharCodeToGlyphIndex

func (s *SubsetFontObj) CharCodeToGlyphIndex(r rune) (uint, error)

CharCodeToGlyphIndex gets glyph index from char code.

func (*SubsetFontObj) CharIndex

func (s *SubsetFontObj) CharIndex(r rune) (uint, error)

CharIndex index of char in glyph table

func (*SubsetFontObj) CharWidth

func (s *SubsetFontObj) CharWidth(r rune) (uint, error)

CharWidth with of char

func (*SubsetFontObj) GetAscender

func (s *SubsetFontObj) GetAscender() int

func (*SubsetFontObj) GetAscenderPx

func (s *SubsetFontObj) GetAscenderPx(fontSize float64) float64

func (*SubsetFontObj) GetDescender

func (s *SubsetFontObj) GetDescender() int

func (*SubsetFontObj) GetDescenderPx

func (s *SubsetFontObj) GetDescenderPx(fontSize float64) float64

func (*SubsetFontObj) GetFamily

func (s *SubsetFontObj) GetFamily() string

GetFamily get font family name

func (*SubsetFontObj) GetTTFParser

func (s *SubsetFontObj) GetTTFParser() *core.TTFParser

GetTTFParser gets TTFParser.

func (*SubsetFontObj) GetTtfFontOption

func (s *SubsetFontObj) GetTtfFontOption() TtfOption

GetTtfFontOption get TtfOption must set before SetTTFByPath

func (*SubsetFontObj) GetUnderlinePosition

func (s *SubsetFontObj) GetUnderlinePosition() int

GetUnderlinePosition underline position.

func (*SubsetFontObj) GetUnderlinePositionPx

func (s *SubsetFontObj) GetUnderlinePositionPx(fontSize float64) float64

func (*SubsetFontObj) GetUnderlineThickness

func (s *SubsetFontObj) GetUnderlineThickness() int

GetUnderlineThickness underlineThickness.

func (*SubsetFontObj) GetUnderlineThicknessPx

func (s *SubsetFontObj) GetUnderlineThicknessPx(fontSize float64) float64

func (*SubsetFontObj) GlyphIndexToPdfWidth

func (s *SubsetFontObj) GlyphIndexToPdfWidth(glyphIndex uint) uint

GlyphIndexToPdfWidth gets width from glyphIndex.

func (*SubsetFontObj) KernValueByLeft

func (s *SubsetFontObj) KernValueByLeft(left uint) (bool, *core.KernValue)

KernValueByLeft find kern value from kern table by left

func (*SubsetFontObj) SetFamily

func (s *SubsetFontObj) SetFamily(familyname string)

SetFamily set font family name

func (*SubsetFontObj) SetIndexObjCIDFont

func (s *SubsetFontObj) SetIndexObjCIDFont(index int)

SetIndexObjCIDFont set IndexObjCIDFont

func (*SubsetFontObj) SetIndexObjUnicodeMap

func (s *SubsetFontObj) SetIndexObjUnicodeMap(index int)

SetIndexObjUnicodeMap set IndexObjUnicodeMap

func (*SubsetFontObj) SetTTFByPath

func (s *SubsetFontObj) SetTTFByPath(ttfpath string) error

SetTTFByPath set ttf

func (*SubsetFontObj) SetTTFByReader

func (s *SubsetFontObj) SetTTFByReader(rd io.Reader) error

SetTTFByReader set ttf

func (*SubsetFontObj) SetTTFData

func (s *SubsetFontObj) SetTTFData(data []byte) error

SetTTFData set ttf

func (*SubsetFontObj) SetTtfFontOption

func (s *SubsetFontObj) SetTtfFontOption(option TtfOption)

SetTtfFontOption set TtfOption must set before SetTTFByPath

type TOCItem

type TOCItem struct {
	// Level is the hierarchy level (1 = top level).
	Level int
	// Title is the bookmark title text.
	Title string
	// PageNo is the 1-based target page number.
	PageNo int
	// Y is the vertical position on the target page (in points from top).
	Y float64
}

TOCItem represents a single entry in the table of contents.

type TableLayout

type TableLayout interface {
	AddColumn(header string, width float64, align string)
	AddRow(row []string)
	AddStyledRow(row []RowCell)
	SetTableStyle(style CellStyle)
	SetHeaderStyle(style CellStyle)
	SetCellStyle(style CellStyle)
	DrawTable() error
}

type TextBlock

type TextBlock struct {
	// X, Y are the top-left coordinates of the block.
	X, Y float64
	// Width, Height are the block dimensions.
	Width, Height float64
	// Lines contains the text lines in this block.
	Lines []TextLine
}

TextBlock represents a block of text (paragraph-level grouping).

type TextExtractionFormat

type TextExtractionFormat int

TextExtractionFormat specifies the output format for text extraction.

const (
	// FormatText returns plain text with line breaks.
	FormatText TextExtractionFormat = iota
	// FormatBlocks returns text grouped by blocks (paragraphs).
	FormatBlocks
	// FormatWords returns individual words with positions.
	FormatWords
	// FormatHTML returns text formatted as HTML.
	FormatHTML
	// FormatJSON returns structured JSON output.
	FormatJSON
)

type TextLine

type TextLine struct {
	// Y is the Y coordinate of this line.
	Y float64
	// Words contains the words on this line.
	Words []TextWord
	// Text is the concatenated text of all words.
	Text string
}

TextLine represents a single line of text within a block.

type TextReplaceResult

type TextReplaceResult struct {
	// PageIndex is the 0-based page index where replacement occurred.
	PageIndex int
	// Count is the number of replacements made on this page.
	Count int
	// OriginalText is the text that was searched for.
	OriginalText string
	// ReplacementText is the text that replaced the original.
	ReplacementText string
}

TextReplaceResult holds the result of a text replacement operation.

func ReplaceText

func ReplaceText(pdfData []byte, oldText, newText string, opts *ReplaceTextOptions) ([]byte, []TextReplaceResult, error)

ReplaceText searches for oldText in the PDF content streams and replaces it with newText. This operates on the raw content stream level and works best with simple text replacements where the new text has similar length.

Returns the total number of replacements made across all pages.

Note: This modifies the raw PDF bytes. For complex replacements involving different fonts or sizes, use the Content Element API instead.

Example:

data, _ := os.ReadFile("input.pdf")
newData, results, err := gopdf.ReplaceText(data, "Draft", "Final", nil)
if err == nil {
    os.WriteFile("output.pdf", newData, 0644)
}

type TextSearchResult

type TextSearchResult struct {
	// PageIndex is the 0-based page index where the match was found.
	PageIndex int
	// X is the X coordinate of the match.
	X float64
	// Y is the Y coordinate of the match.
	Y float64
	// Width is the approximate width of the matched text.
	Width float64
	// Height is the approximate height of the matched text.
	Height float64
	// Text is the matched text.
	Text string
	// Context is the surrounding text for context.
	Context string
}

TextSearchResult represents a single text search match on a page.

func SearchText

func SearchText(pdfData []byte, query string, caseInsensitive bool) ([]TextSearchResult, error)

SearchText searches for text across all pages of the given PDF data. Returns all matches with their positions. The search is case-sensitive unless caseInsensitive is true.

Example:

data, _ := os.ReadFile("input.pdf")
results, _ := gopdf.SearchText(data, "hello", true)
for _, r := range results {
    fmt.Printf("Page %d at (%.0f, %.0f): %s\n", r.PageIndex, r.X, r.Y, r.Text)
}

func SearchTextOnPage

func SearchTextOnPage(pdfData []byte, pageIndex int, query string, caseInsensitive bool) ([]TextSearchResult, error)

SearchTextOnPage searches for text on a specific page (0-based).

type TextWord

type TextWord struct {
	// X, Y are the word position.
	X, Y float64
	// Width is the approximate word width.
	Width float64
	// Height is the word height (font size).
	Height float64
	// Text is the word content.
	Text string
	// FontName is the font used.
	FontName string
	// FontSize is the font size.
	FontSize float64
}

TextWord represents a single word with position information.

type Transparency

type Transparency struct {
	Alpha         float64
	BlendModeType BlendModeType
	// contains filtered or unexported fields
}

Transparency defines an object alpha.

func NewTransparency

func NewTransparency(alpha float64, blendModeType string) (Transparency, error)

func (Transparency) GetId

func (t Transparency) GetId() string

type TransparencyMap

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

func NewTransparencyMap

func NewTransparencyMap() TransparencyMap

func (*TransparencyMap) Find

func (tm *TransparencyMap) Find(transparency Transparency) (Transparency, bool)

func (*TransparencyMap) Save

func (tm *TransparencyMap) Save(transparency Transparency) Transparency

type TransparencyXObjectGroup

type TransparencyXObjectGroup struct {
	Index            int
	BBox             [4]float64
	Matrix           [6]float64
	ExtGStateIndexes []int
	XObjects         []cacheContentImage
	// contains filtered or unexported fields
}

type TransparencyXObjectGroupOptions

type TransparencyXObjectGroupOptions struct {
	Protection       *PDFProtection
	ExtGStateIndexes []int
	BBox             [4]float64
	XObjects         []cacheContentImage
}

type TtfOption

type TtfOption struct {
	UseKerning                bool
	Style                     int               //Regular|Bold|Italic
	OnGlyphNotFound           func(r rune)      //Called when a glyph cannot be found, just for debugging
	OnGlyphNotFoundSubstitute func(r rune) rune //Called when a glyph cannot be found, we can return a new rune to replace it.
}

TtfOption font option

type UnicodeMap

type UnicodeMap struct {
	PtrToSubsetFontObj *SubsetFontObj
	// contains filtered or unexported fields
}

UnicodeMap unicode map

func (*UnicodeMap) SetPtrToSubsetFontObj

func (u *UnicodeMap) SetPtrToSubsetFontObj(ptr *SubsetFontObj)

SetPtrToSubsetFontObj set pointer to SubsetFontObj

type WatermarkOption

type WatermarkOption struct {
	// Text is the watermark string to display.
	Text string

	// FontFamily is the font family to use (must be pre-loaded via AddTTFFont).
	FontFamily string

	// FontSize is the font size in points. Default: 48.
	FontSize float64

	// Angle is the rotation angle in degrees. Default: 45.
	Angle float64

	// Color is the RGB color of the watermark text. Default: light gray (200,200,200).
	Color [3]uint8

	// Opacity is the transparency level (0.0 = invisible, 1.0 = opaque). Default: 0.3.
	Opacity float64

	// Repeat tiles the watermark across the page when true.
	Repeat bool

	// RepeatSpacingX is the horizontal spacing between repeated watermarks. Default: 150.
	RepeatSpacingX float64

	// RepeatSpacingY is the vertical spacing between repeated watermarks. Default: 150.
	RepeatSpacingY float64
}

WatermarkOption configures how a text watermark is rendered.

type XMPMetadata

type XMPMetadata struct {
	// Dublin Core (dc:) properties
	Title       string   // dc:title
	Creator     []string // dc:creator (authors)
	Description string   // dc:description
	Subject     []string // dc:subject (keywords)
	Rights      string   // dc:rights (copyright)
	Language    string   // dc:language (e.g. "en-US")

	// XMP Basic (xmp:) properties
	CreatorTool string    // xmp:CreatorTool (application name)
	CreateDate  time.Time // xmp:CreateDate
	ModifyDate  time.Time // xmp:ModifyDate

	// PDF-specific (pdf:) properties
	Producer string // pdf:Producer
	Keywords string // pdf:Keywords
	Trapped  string // pdf:Trapped ("True", "False", "Unknown")

	// PDF/A conformance (pdfaid:)
	PDFAConformance string // pdfaid:conformance ("A", "B", "U")
	PDFAPart        int    // pdfaid:part (1, 2, 3)

	// Custom properties
	Custom map[string]string
}

XMPMetadata holds XMP (Extensible Metadata Platform) metadata for the PDF. XMP is the standard metadata format for PDF 2.0 and is also supported in earlier versions. It provides richer metadata than the traditional Document Information Dictionary (PdfInfo).

Source Files

Directories

Path Synopsis
cmd
test_open_pdf command
examples
arabic command
mask-image command

Jump to

Keyboard shortcuts

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