### Installation Source: https://github.com/coregx/gxpdf/blob/main/README.md Install the GxPDF library using go get. ```bash go get github.com/coregx/gxpdf ``` -------------------------------- ### Install Development Tools Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Commands to install golangci-lint and set up the local repository. ```bash # Install golangci-lint go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest # Clone and setup git clone https://github.com/YOUR_USERNAME/gxpdf.git cd gxpdf git remote add upstream https://github.com/coregx/gxpdf.git # Download dependencies go mod download # Verify setup go test ./... golangci-lint run ``` -------------------------------- ### Build and Run Source: https://github.com/coregx/gxpdf/blob/main/examples/table-detection/README.md Commands to build the table detection example and run it on a PDF file. ```bash # Build the example go build -o table-detection # Run on a PDF file ./table-detection document.pdf ``` -------------------------------- ### Usage Commands Source: https://github.com/coregx/gxpdf/blob/main/examples/image-extraction/README.md Command-line arguments for running the image extraction example. ```bash # Extract all images from a PDF go run main.go document.pdf # Extract to specific directory go run main.go document.pdf ./extracted_images # Help go run main.go ``` -------------------------------- ### Command Line Usage Source: https://github.com/coregx/gxpdf/blob/main/examples/text-extraction/README.md Command to run the text extraction example. ```bash go run main.go ``` -------------------------------- ### Creator Package Example Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md An example demonstrating how to use the creator package to generate a simple PDF with text and a rectangle. ```go c := creator.New() c.SetTitle("Annual Report") page, _ := c.NewPage() page.AddText("Hello, World!", 100, 700, creator.Helvetica, 12) page.DrawRectangle(100, 600, 200, 50, &creator.RectangleOptions{ FillColor: &creator.Blue, }) c.WriteToFile("output.pdf") ``` -------------------------------- ### Export API Examples Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Examples showing how to use different exporters (CSV, JSON, Excel) from the export package. ```go exporter := export.NewCSVExporter() exporter.Export(table, writer) jsonExp := export.NewJSONExporter() jsonExp.Export(table, writer) excelExp := export.NewExcelExporter() excelExp.Export(tables, "output.xlsx") ``` -------------------------------- ### Builder API Example Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Example usage of the declarative Builder API for document generation. ```go doc := builder.NewBuilder( builder.WithPageSize(builder.A4), builder.WithMargins(builder.Mm(20), builder.Mm(15), builder.Mm(20), builder.Mm(15)), builder.WithTitle("Annual Report"), ) doc.Page(func(page *builder.PageBuilder) { page.Header(func(h *builder.Container) { h.Text("ACME Corporation", builder.Bold(), builder.FontSize(14)) h.Line() }) page.Content(func(c *builder.Container) { c.Row(func(r *builder.RowBuilder) { r.Col(8, func(col *builder.ColBuilder) { col.Text("Main content area") }) r.Col(4, func(col *builder.ColBuilder) { col.Text("Sidebar", builder.TextColor(builder.Gray)) }) }) }) page.Footer(func(f *builder.Container) { f.PageNumber(builder.PageNum+" of "+builder.TotalPages, builder.AlignCenter(), builder.FontSize(8)) }) }) pdfBytes, err := doc.Build() ``` -------------------------------- ### Quick Start Workflow Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md A concise workflow for forking, cloning, making changes, and submitting a pull request. ```bash git clone https://github.com/YOUR_USERNAME/gxpdf.git cd gxpdf git checkout -b feat/my-feature go fmt ./... go test ./... golangci-lint run git add . git commit -m "feat: add my feature" git push origin feat/my-feature ``` -------------------------------- ### Table-Driven Test Example Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md An example of writing table-driven tests in Go for a Rectangle struct. ```go func TestRectangle_Dimensions(t *testing.T) { tests := []struct { name string rect Rectangle wantW float64 wantH float64 }{ { name: "A4 size", rect: MustRectangle(0, 0, 595, 842), wantW: 595, wantH: 842, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := tt.rect.Width(); got != tt.wantW { t.Errorf("Width() = %v, want %v", got, tt.wantW) } }) } } ``` -------------------------------- ### Load Image Source: https://github.com/coregx/gxpdf/blob/main/examples/image_embedding/README.md Demonstrates loading JPEG images from a file or an io.Reader. ```go // From file img, err := creator.LoadImage("photo.jpg") // From io.Reader file, _ := os.Open("photo.jpg") img, err := creator.LoadImageFromReader(file) ``` -------------------------------- ### Main Entry Point - Opening and Extracting PDFs Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Example of opening an existing PDF and extracting tables and text from a specific page. ```go // Open and extract from existing PDFs doc, _ := gxpdf.Open("document.pdf") tables := doc.ExtractTables() text := doc.Page(0).Text() ``` -------------------------------- ### Testing with different PDF files Source: https://github.com/coregx/gxpdf/blob/main/examples/text-extraction/README.md Examples of how to test the text extraction tool with various types of PDF documents. ```bash # Simple text document go run main.go document.pdf # Invoice with tables go run main.go invoice.pdf # Financial report go run main.go report.pdf ``` -------------------------------- ### Conventional Commit Examples Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Examples of commit messages following the Conventional Commits specification. ```bash git commit -m "feat: add PDF/A validation support" git commit -m "fix: handle empty pages in merger" git commit -m "docs: update API examples" ``` -------------------------------- ### Usage Source: https://github.com/coregx/gxpdf/blob/main/examples/image_embedding/README.md This command will create 'image_embedding_example.pdf' with embedded JPEG images. ```bash go run main.go ``` -------------------------------- ### Run Tests Source: https://github.com/coregx/gxpdf/blob/main/examples/dct-decode/README.md Commands to run the unit and integration tests for the DCT decoder and stream parser. ```bash go test ./internal/infrastructure/encoding/... go test ./internal/infrastructure/parser/... -run=TestStreamDecoder ``` -------------------------------- ### Simple Public API Example Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Demonstrates the user-facing simple API for opening a PDF and extracting tables, hiding the complex internal algorithm. ```go // User sees simple API doc, _ := gxpdf.Open("file.pdf") tables := doc.ExtractTables() // Complex 4-pass algorithm hidden inside ``` -------------------------------- ### Draw Image Source: https://github.com/coregx/gxpdf/blob/main/examples/image_embedding/README.md Shows how to draw images at specific positions and sizes, including aspect-ratio-preserving scaling. ```go // Fixed size (may stretch image) page.DrawImage(img, x, y, width, height) // Fit to box (maintains aspect ratio) page.DrawImageFit(img, x, y, maxWidth, maxHeight) ``` -------------------------------- ### Declarative Builder API Source: https://github.com/coregx/gxpdf/blob/main/README.md Example of using the declarative builder API to create a PDF document with headers, footers, and content. ```go import "github.com/coregx/gxpdf/builder" doc := builder.NewBuilder( builder.WithPageSize(builder.A4), builder.WithMargins(builder.Mm(20), builder.Mm(15), builder.Mm(20), builder.Mm(15)), builder.WithTitle("Invoice"), builder.WithDefaultFontSize(11), ) doc.Page(func(page *builder.PageBuilder) { page.Header(func(h *builder.Container) { h.Row(func(r *builder.RowBuilder) { r.Col(8, func(c *builder.ColBuilder) { c.Text("ACME Corporation", builder.Bold(), builder.FontSize(16)) }) r.Col(4, func(c *builder.ColBuilder) { c.Text("INVOICE", builder.Bold(), builder.FontSize(20), builder.AlignRight(), builder.TextColor(builder.Navy)) }) }) h.Line() }) page.Content(func(content *builder.Container) { content.Spacer(builder.Mm(10)) content.Row(func(r *builder.RowBuilder) { r.Col(6, func(c *builder.ColBuilder) { c.Text("Bill To:", builder.Bold()) c.Text("John Doe") c.Text("123 Main Street") }) r.Col(6, func(c *builder.ColBuilder) { c.Text("Invoice #: INV-2026-001", builder.AlignRight()) c.Text("Date: March 23, 2026", builder.AlignRight()) }) }) }) page.Footer(func(f *builder.Container) { f.PageNumber(builder.PageNum+" of "+builder.TotalPages, builder.AlignCenter(), builder.FontSize(8), builder.TextColor(builder.Gray)) }) }) pdfBytes, err := doc.Build() ``` -------------------------------- ### Creating Documents with Chapters and TOC Source: https://github.com/coregx/gxpdf/blob/main/README.md Example of creating a PDF document with chapters and enabling an auto-generated Table of Contents. ```go c := creator.New() c.EnableTOC() ch1 := creator.NewChapter("Introduction") ch1.Add(creator.NewParagraph("Introduction content...")) ch1_1 := ch1.NewSubChapter("Background") ch1_1.Add(creator.NewParagraph("Background information...")) ch2 := creator.NewChapter("Methods") ch2.Add(creator.NewParagraph("Methods description...")) c.AddChapter(ch1) c.AddChapter(ch2) c.WriteToFile("document_with_toc.pdf") ``` -------------------------------- ### Parameter Extraction Example Source: https://github.com/coregx/gxpdf/blob/main/examples/dct-decode/README.md A Go code snippet demonstrating how to extract the ColorTransform parameter from a PDF stream's /DecodeParms dictionary. ```go if parmsDict, ok := decodeParmsObj.(*primitive.Dictionary); ok { if ctObj := parmsDict.Get("ColorTransform"); ctObj != nil { colorTransform = ctObj.Value() } } ``` -------------------------------- ### Document-level Extraction API Source: https://github.com/coregx/gxpdf/blob/main/examples/image-extraction/README.md Go code demonstrating how to open a PDF document and extract all images. ```go doc, _ := gxpdf.Open("document.pdf") defer doc.Close() // Get all images from all pages images := doc.GetImages() // With error handling images, err := doc.GetImagesWithError() ``` -------------------------------- ### Creating Encrypted PDFs Source: https://github.com/coregx/gxpdf/blob/main/README.md Example of creating an encrypted PDF with user and owner passwords, and setting permissions and encryption algorithm. ```go c := creator.New() c.SetEncryption(creator.EncryptionOptions{ UserPassword: "user123", OwnerPassword: "owner456", Permissions: creator.PermissionPrint | creator.PermissionCopy, Algorithm: creator.EncryptionAES256, }) page, _ := c.NewPage() page.AddText("This document is encrypted!", 100, 750, creator.Helvetica, 14) c.WriteToFile("encrypted.pdf") ``` -------------------------------- ### CSV Reference Output Example Source: https://github.com/coregx/gxpdf/blob/main/testdata/TABULA_PDFS.md An example showing the mapping between a PDF file and its expected CSV output. ```text 12s0324.pdf csv/12s0324.csv (expected output) ``` -------------------------------- ### Error Context Example Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Illustrates how errors are wrapped with additional context for easier debugging. ```go if err != nil { return fmt.Errorf("parse xref at offset %d: %w", offset, err) } ``` -------------------------------- ### Go Comments Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Example of Go documentation comments for a function, explaining its purpose and return values. ```go // Parse parses a PDF file from the given reader. // It returns a Document or an error if parsing fails. func Parse(r io.Reader) (*Document, error) { ... } ``` -------------------------------- ### Creating a PDF with the Builder API Source: https://github.com/coregx/gxpdf/blob/main/README.md Example of creating a simple PDF document using the Builder API, including text and spacing. ```go package main import ( "log" "github.com/coregx/gxpdf/builder" ) func main() { doc := builder.NewBuilder( builder.WithPageSize(builder.A4), builder.WithTitle("Hello World"), ) doc.Page(func(page *builder.PageBuilder) { page.Content(func(c *builder.Container) { c.Text("Hello, GxPDF!", builder.Bold(), builder.FontSize(24)) c.Spacer(builder.Mm(5)) c.Text("Professional PDF creation in Go.") }) }) if err := doc.BuildToFile("output.pdf"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Create a New Branch Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Examples of creating new branches for features, bug fixes, documentation, refactoring, or tests. ```bash git checkout -b feat/your-feature-name # or git checkout -b fix/your-bug-fix ``` -------------------------------- ### Example Output Source: https://github.com/coregx/gxpdf/blob/main/examples/text-extraction/README.md Sample output from the text extraction process, showing positional details, extracted text, and statistics. ```text Opening PDF: sample.pdf PDF has 1 pages Extracting text from page 1... Found 25 text elements: Position details for first 20 elements: ------------------------------------------------------- [1] Text: "Hello, World!" Position: (100.00, 700.00) Size: 72.00 x 12.00 Font: Helvetica, Size: 12.0pt [2] Text: "This is a sample PDF." Position: (100.00, 686.00) Size: 108.00 x 12.00 Font: Helvetica, Size: 12.0pt ... ------------------------------------------------------- All extracted text: ------------------------------------------------------- Hello, World! This is a sample PDF. ... ------------------------------------------------------- Statistics: Total text elements: 25 Unique fonts: 2 Helvetica: 20 elements Helvetica-Bold: 5 elements Text bounding box: Bottom-left: (72.00, 100.00) Top-right: (540.00, 720.00) Dimensions: 468.00 x 620.00 points ``` -------------------------------- ### Filter Detection Examples Source: https://github.com/coregx/gxpdf/blob/main/examples/dct-decode/README.md Illustrates how the DCTDecode filter can be specified in a PDF stream's /Filter entry, either as a single filter or within an array of multiple filters. ```go // Single filter /Filter /DCTDecode // Multiple filters (array) /Filter [ /DCTDecode ] ``` -------------------------------- ### Automatic Decoding Example Source: https://github.com/coregx/gxpdf/blob/main/examples/dct-decode/README.md This Go code snippet shows how to use the parser to automatically decode a stream that uses the DCTDecode filter. ```go reader := parser.NewReader("document.pdf") err := reader.Open() if err != nil { log.Fatal(err) } defer reader.Close() // Get image stream object imageStream := ... // Get from PDF structure // Decode automatically handles DCTDecode filter decodedData, err := reader.DecodeStream(imageStream) if err != nil { log.Fatal(err) } // decodedData now contains raw RGB/grayscale pixels ``` -------------------------------- ### Creating a PDF Document (Creator API) Source: https://github.com/coregx/gxpdf/blob/main/README.md Example of creating a PDF document using the Creator API, adding text and drawing shapes. ```go package main import ( "log" "github.com/coregx/gxpdf/creator" ) func main() { c := creator.New() c.SetTitle("My Document") c.SetAuthor("GxPDF") page, _ := c.NewPage() // Add text page.AddText("Hello, GxPDF!", 100, 750, creator.HelveticaBold, 24) page.AddText("Professional PDF creation in Go", 100, 720, creator.Helvetica, 12) // Draw shapes page.DrawRectangle(100, 600, 200, 100, &creator.RectangleOptions{ FillColor: &creator.Blue, StrokeColor: &creator.Black, StrokeWidth: 2, }) if err := c.WriteToFile("output.pdf"); err != nil { log.Fatal(err) } } ``` -------------------------------- ### Rich Domain Model Example Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Compares an anemic data model with a rich domain model that includes behavior, favoring the latter. ```go // BAD: Anemic model type Page struct { Width float64 Height float64 } // GOOD: Rich model with behavior type Page struct { dimensions Rectangle content ContentStream } func (p *Page) AddText(text string, pos Position, font *Font) error { return p.content.AppendText(text, pos, font) } ``` -------------------------------- ### Image Operations API Source: https://github.com/coregx/gxpdf/blob/main/examples/image-extraction/README.md Go code demonstrating how to access image metadata, save images to files, and convert them to Go images. ```go for _, img := range images { // Get metadata fmt.Printf("%dx%d, %s\n", img.Width(), img.Height(), img.ColorSpace()) // Save to file (format determined by extension) img.SaveToFile("output.jpg") // JPEG img.SaveToFile("output.png") // PNG // Convert to Go image for processing goImg, _ := img.ToGoImage() } ``` -------------------------------- ### Digital Signatures Source: https://github.com/coregx/gxpdf/blob/main/README.md Example of signing and verifying PDF documents using the GxPDF signature package. ```go import "github.com/coregx/gxpdf/signature" // Generate or load your certificate key, cert, _ := signature.GenerateTestCertificate() signer, _ := signature.NewLocalSigner(key, []*x509.Certificate{cert}) // Sign a PDF signed, err := signature.SignDocument(pdfBytes, signer, signature.WithReason("Approved"), signature.WithLocation("Moscow"), ) // Verify signatures infos, err := signature.Verify(signed) fmt.Println(infos[0].SignedBy, infos[0].Valid) // "CN=Test" true ``` -------------------------------- ### Page-level Extraction API Source: https://github.com/coregx/gxpdf/blob/main/examples/image-extraction/README.md Go code demonstrating how to extract images from a specific page of a PDF document. ```go page := doc.Page(0) // First page // Get all images from this page images := page.GetImages() // With error handling images, err := page.GetImagesWithError() ``` -------------------------------- ### Validate file size and use timeout Source: https://github.com/coregx/gxpdf/blob/main/SECURITY.md Example of validating the input PDF file size and applying a timeout for processing. ```go // Validate file size fi, _ := os.Stat(pdfPath) if fi.Size() > maxPDFSize { return errors.New("PDF too large") } // Use timeout ctx, cancel := context.WithTimeout(ctx, 30*time.Second) def cancel() ``` -------------------------------- ### Unicode Text with Custom Fonts Source: https://github.com/coregx/gxpdf/blob/main/README.md Example demonstrating how to add Unicode text (Cyrillic, CJK) to a PDF using custom loaded fonts. ```go c := creator.New() page, _ := c.NewPage() // Load custom font with Unicode support font, _ := c.LoadFont("/path/to/arial.ttf") // Cyrillic text page.AddTextCustomFont("Привет, мир!", 100, 700, font, 18) // CJK text (requires appropriate font like Malgun Gothic) cjkFont, _ := c.LoadFont("/path/to/malgun.ttf") page.AddTextCustomFont("你好世界 • 안녕하세요", 100, 670, cjkFont, 16) c.WriteToFile("unicode.pdf") ``` -------------------------------- ### Use timeout for untrusted PDFs Source: https://github.com/coregx/gxpdf/blob/main/SECURITY.md Example of using a context with a timeout when parsing untrusted PDF files to prevent excessive resource consumption. ```go ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) def cancel() reader := pdf.NewReader("untrusted.pdf") doc, err := reader.ReadWithContext(ctx) ``` -------------------------------- ### Example Stream Dictionary with ColorTransform Source: https://github.com/coregx/gxpdf/blob/main/examples/dct-decode/README.md An example of a PDF stream dictionary that includes the DCTDecode filter and the ColorTransform parameter. ```plaintext << /Type /XObject /Subtype /Image /Width 800 /Height 600 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /DecodeParms << /ColorTransform 1 >> >> ``` -------------------------------- ### Run all tests Source: https://github.com/coregx/gxpdf/blob/main/README.md Commands to run tests for the GxPDF project. ```bash # Run all tests go test ./... # Run with race detector go test -race ./... # Run with coverage go test -cover ./... ``` -------------------------------- ### Testing Strategy - Command Line Interface Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Common Go commands for running unit tests, race detection, coverage, and benchmarks. ```bash # Unit tests go test ./... # Race detector go test -race ./... # Coverage go test -cover ./... # Benchmarks go test -bench=. -benchmem ./... ``` -------------------------------- ### Always check errors Source: https://github.com/coregx/gxpdf/blob/main/SECURITY.md Example demonstrating the importance of checking for errors during PDF parsing. ```go // Always check errors doc, err := reader.Read() if err != nil { return fmt.Errorf("PDF parsing failed: %w", err) } ``` -------------------------------- ### Opening PDFs from Memory (NEW) Source: https://github.com/coregx/gxpdf/blob/main/README.md Illustrates how to open PDF documents directly from byte slices, such as those read from network responses or databases, including encrypted PDFs. ```go // Read PDF from HTTP request, database, or any byte source data, _ := io.ReadAll(httpResponse.Body) doc, err := gxpdf.OpenFromBytes(data) if err != nil { log.Fatal(err) } defer doc.Close() // Works with encrypted PDFs too doc, _ = gxpdf.OpenFromBytesWithPassword(data, "secret") ``` -------------------------------- ### Limit pages and content size Source: https://github.com/coregx/gxpdf/blob/main/SECURITY.md Example of enforcing limits on the number of pages and the size of extracted text from a PDF. ```go // Limit pages const maxPages = 100 pages := min(doc.PageCount(), maxPages) // Limit content size const maxTextSize = 10 * 1024 * 1024 text, _ := page.ExtractText() if len(text) > maxTextSize { return errors.New("text too large") } ``` -------------------------------- ### Reading and Filling Forms Source: https://github.com/coregx/gxpdf/blob/main/README.md Shows how to read form fields from an existing PDF and then fill them programmatically. ```go // Read form fields from existing PDF doc, _ := gxpdf.Open("form.pdf") defer doc.Close() // Check if document has a form if doc.HasForm() { fields, _ := doc.GetFormFields() for _, f := range fields { fmt.Printf("%s (%s): %v\n", f.Name(), f.Type(), f.Value()) } } // Fill form fields app, _ := creator.NewAppender("form.pdf") defer app.Close() app.SetFieldValue("name", "John Doe") app.SetFieldValue("email", "john@example.com") app.SetFieldValue("agree", true) // Checkbox app.SetFieldValue("country", "USA") // Dropdown app.WriteToFile("filled_form.pdf") ``` -------------------------------- ### In-Memory PDF Opening Source: https://github.com/coregx/gxpdf/blob/main/ROADMAP.md Methods for opening PDF documents from byte slices without filesystem I/O. ```Go OpenFromBytes() OpenFromBytesWithPassword() ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/coregx/gxpdf/blob/main/README.md Go code snippet to enable debug logging using the slog and logging packages. ```go import ( "log/slog" "os" "github.com/coregx/gxpdf/logging" ) logging.SetLogger(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: slog.LevelWarn, }))) ``` -------------------------------- ### Run Tests Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Commands to execute tests with various options like coverage and race detection. ```bash go test ./... # All tests go test -cover ./... # With coverage go test -race ./... # Race detector go test ./internal/infrastructure/parser/ # Specific package ``` -------------------------------- ### Functional Options - Builder Document Settings Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Demonstrates the functional options pattern applied at the document level for a builder. ```go doc := builder.NewBuilder( builder.WithPageSize(builder.Letter), builder.WithDefaultFontSize(11), builder.WithAuthor("ACME Corp"), ) ``` -------------------------------- ### Rich Domain Model - Page AddText Method Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Example of a rich domain model object (Page) with behavior, including validation logic within a method. ```go // Rich model example type Page struct { dimensions Rectangle content ContentStream resources *Resources } func (p *Page) AddText(text string, pos Position, font *Font) error { // Validation and business logic in domain entity if err := p.validatePosition(pos); err != nil { return err } return p.content.AppendText(text, pos, font) } ``` -------------------------------- ### Extracting Vector Graphics (NEW) Source: https://github.com/coregx/gxpdf/blob/main/README.md Shows how to extract vector graphic paths from a PDF page, including their paint modes, stroke, and fill colors. ```go doc, _ := gxpdf.Open("diagram.pdf") defer doc.Close() // Extract all vector paths with colors, opacity, and CTM-transformed coordinates paths, _ := doc.GetVectorGraphicsForPage(1) for _, p := range paths { fmt.Printf("Path: %d verbs, mode=%v, stroke=%v, fill=%v\n", len(p.Verbs), p.PaintMode, p.StrokeColor, p.FillColor) } ``` -------------------------------- ### Go Naming Conventions Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Illustrates naming conventions for types, interfaces, private fields, and exported constants in Go. ```go // Types — PascalCase type Document struct { ... } type PdfReader struct { ... } // Interfaces — -er suffix when possible type Parser interface { ... } type Encoder interface { ... } // Private — camelCase type Document struct { id DocumentID version Version } // Constants — PascalCase for exported const MaxPageSize = 14400 ``` -------------------------------- ### Push and Create PR Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Commands and instructions for pushing changes and creating a pull request on GitHub. ```bash git push origin feat/your-feature-name ``` -------------------------------- ### Run Development Checks Source: https://github.com/coregx/gxpdf/blob/main/CONTRIBUTING.md Essential commands to run before submitting changes, including formatting, static analysis, and testing. ```bash go fmt ./... # Format code go vet ./... # Static analysis go test ./... # Run tests go test -race ./... # Race detector golangci-lint run # Linter ``` -------------------------------- ### Interactive Forms (AcroForm) Source: https://github.com/coregx/gxpdf/blob/main/README.md Demonstrates creating text fields, checkboxes, and dropdowns for interactive forms in a PDF. ```go import "github.com/coregx/gxpdf/creator/forms" c := creator.New() page, _ := c.NewPage() // Text field nameField := forms.NewTextField("name", 100, 700, 200, 20) nameField.SetLabel("Full Name:") nameField.SetRequired(true) page.AddField(nameField) // Checkbox agreeBox := forms.NewCheckbox("agree", 100, 660, 15, 15) agreeBox.SetLabel("I agree to the terms") page.AddField(agreeBox) // Dropdown countryDropdown := forms.NewDropdown("country", 100, 620, 150, 20) countryDropdown.AddOption("us", "United States") countryDropdown.AddOption("uk", "United Kingdom") page.AddField(countryDropdown) c.WriteToFile("form.pdf") ``` -------------------------------- ### Flattening Forms Source: https://github.com/coregx/gxpdf/blob/main/README.md Explains how to convert interactive form fields into static content, making them non-editable. ```go // Convert form fields to static content (non-editable) app, _ := creator.NewAppender("filled_form.pdf") defer app.Close() app.FlattenForm() // Flatten all fields // Or: app.FlattenFields("signature", "date") // Specific fields app.WriteToFile("flattened.pdf") ``` -------------------------------- ### Table Detection - Amount-Based Discrimination Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Illustrates the core innovation of amount-based discrimination for identifying transaction rows versus continuation text in table detection. ```go // Works universally across all bank formats isTransactionRow := hasAmount(row) // Has monetary amount = transaction isContinuation := !hasAmount(row) // No amount = continuation text ``` -------------------------------- ### Functional Options - Creator Encryption Settings Source: https://github.com/coregx/gxpdf/blob/main/docs/ARCHITECTURE.md Shows how the functional options pattern is used to configure encryption settings for a creator object. ```go c := creator.New() c.SetEncryption(creator.EncryptionOptions{ UserPassword: "user123", OwnerPassword: "owner456", Algorithm: creator.EncryptionAES256, Permissions: creator.PermissionPrint, }) ``` -------------------------------- ### Reading Encrypted PDFs Source: https://github.com/coregx/gxpdf/blob/main/README.md Explains how to open PDF documents that are protected by passwords, including those with only permission restrictions. ```go // PDFs with empty user password (permissions-only) open transparently doc, _ := gxpdf.Open("bank_statement_encrypted.pdf") defer doc.Close() // PDFs requiring a password doc, err := gxpdf.OpenWithPassword("protected.pdf", "secret") if errors.Is(err, gxpdf.ErrPasswordRequired) { log.Fatal("Wrong password") } defer doc.Close() fmt.Printf("Pages: %d\n", doc.PageCount()) ``` -------------------------------- ### Extracting Tables from PDFs Source: https://github.com/coregx/gxpdf/blob/main/README.md Demonstrates how to extract tables from a PDF document and export them to CSV format. ```go doc, _ := gxpdf.Open("bank_statement.pdf") defer doc.Close() tables := doc.ExtractTables() for _, table := range tables { fmt.Printf("Table: %d rows x %d cols\n", table.RowCount(), table.ColumnCount()) // Export to CSV csv, _ := table.ToCSV() fmt.Println(csv) } ```