go-pdf/fpdf

repository·main·Indexed 20 days ago

https://github.com/go-pdf/fpdf

A high-level PDF document generator for Go, implemented from the original PHP FPDF library. It supports text, drawing, images, and UTF-8, including support for TrueType fonts and RTL/LTR modes. The library features an internal error state management system and provides utilities for handling document attachments, page margins, and coordinate conversions.

Tokens
20.2K
Snippets
80
Records
103
Agent score
71%

What's inside go-pdf/fpdf

  1. How error management works in FPDF

    main

    Instead of checking for errors after every single method call, go-pdf/fpdf uses an internal error state. If a method fails, an internal error field is set, and subsequent method calls typically return without performing operations.

    To manage errors effectively:

    1. Check at the end: It is generally sufficient to check for errors after calling Output() or OutputFileAndClose().
    2. Check status: Use Ok() to check if the instance is in a valid state, or Err() to see if an error has occurred.
    3. Retrieve error: Use Error() to get the specific error message.
    4. Manual error injection: If an error occurs in your own application logic during generation, you can transfer it to the FPDF instance using SetError() or SetErrorf().
  2. Install go-pdf/fpdf

    main

    To install the go-pdf/fpdf package, use the standard go get command. To receive updates later, use the -u -v flags.

    go get github.com/go-pdf/fpdf
    
    # To receive updates
    go get -u -v github.com/go-pdf/fpdf/...
  3. Generate font definition files with makefont

    main

    To use non-UTF-8 TrueType or Type1 fonts, you must generate a font definition file and a compressed version of the font. You can do this using the makefont command-line utility.

    1. Build the utility: cd makefont && go build.
    2. Run the utility: Use the --embed, --enc (encoding map), --dst (destination directory), and the path to the .ttf file.
    # Example command
    ./makefont --embed --enc=../font/cp1252.map --dst=../font ../font/calligra.ttf
  4. Use FpdfTpl to manage and reuse PDF templates

    main

    The FpdfTpl type is a concrete implementation of the Template interface. It allows you to capture specific pages or entire sets of pages from a PDF generation process to be reused later.

    Key capabilities include:

    • Page Selection: Use FromPage(page int) to create a new template instance pointing to a specific page (note: pages are 1-indexed). Use FromPages() to get a slice containing all pages in the template.
    • Metadata Access: Retrieve the template's bounding dimensions via Size(), its unique identifier via ID(), and the images it uses via Images().
    • Serialization: You can convert a template into a byte slice using Serialize() and reconstruct it later using DeserializeTemplate(b []byte). This is useful for caching templates or passing them between processes.
    // Example: Creating and using a template
    // (Assuming 'tpl' is an existing FpdfTpl instance)
    
    // 1. Get a specific page (e.g., page 2)
    page2, err := tpl.FromPage(2)
    if err != nil {
        // handle error
    }
    
    // 2. Serialize for later use
    data, err := tpl.Serialize()
    if err != nil {
        // handle error
    }
    
    // 3. Reconstruct the template later
    newTpl, err := fpdf.DeserializeTemplate(data)
    if err != nil {
        // handle error
    }
  5. How to use transformation contexts in GoFPDF

    main

    To apply transformations (scaling, rotation, skewing, etc.) to text, drawings, or images, you must use a transformation context. This prevents transformations from affecting the rest of the document.

    The Lifecycle:

    1. Call TransformBegin() to start a new context.
    2. Call one or more transformation methods (e.g., TransformScale, TransformRotate, TransformTranslate).
    3. Perform your output operations (text, drawing, or image).
    4. Call TransformEnd() to close the context and return to the previous state.

    Important: All transformation contexts must be properly ended with TransformEnd() before outputting the document. Failure to do so or attempting to end a context that wasn't started will result in an error.

    // Example usage pattern
    f.TransformBegin()
    f.TransformRotate(45, 100, 100)
    f.Cell(0, 10, "Rotated Text")
    f.TransformEnd()
  6. How error handling works in fpdf

    main

    The fpdf package uses an internal error state management scheme. Instead of checking every method call for an error, you can typically perform your generation sequence and check for errors at the end (e.g., when calling Output() or OutputFileAndClose()).

    • If an error occurs, an internal error field is set. Subsequent method calls will typically return without performing operations, and the error state is retained.
    • To check if an error has occurred, use Ok() or Err().
    • To retrieve the specific error message, use Error().
    • If an error occurs in your application logic during PDF generation, you can manually transfer that error to the fpdf instance using SetError() or SetErrorf().
  7. Generate graphs and grids with GridType

    main

    The GridType struct provides a high-level abstraction for generating graphs. It allows you to work with logical data coordinates (e.g., a data range of 0 to 100) rather than manual page coordinates. It handles the scaling of data points to the page, drawing background grids, and rendering tick marks and labels.

    Core Workflow

    1. Initialize: Create a grid using NewGrid(x, y, w, h) where x, y, w, h are in page units.
    2. Configure Scales: Define how data maps to the grid using either:
      • TickmarksContainX(min, max) and TickmarksContainY(min, max): Automatically generates viewer-friendly tick marks within the specified range.
      • TickmarksExtentX(min, div, count) and TickmarksExtentY(min, div, count): Sets exact tick mark values based on a starting value, a division increment, and a count.
    3. Customize Appearance: Set colors (ClrText, ClrMain, ClrSub), line widths (WdMain, WdSub), and label formatters (XTickStr, YTickStr).
    4. Render: Call grid.Grid(pdf) to draw the background grid and labels.
    5. Plot Data: Use grid.Plot(pdf, xMin, xMax, count, fnc) to draw lines based on a mathematical function fnc(x).
    grid := fpdf.NewGrid(10, 10, 100, 100)
    grid.TickmarksContainX(0, 50)
    grid.TickmarksContainY(0, 100)
    grid.Grid(pdf)
    
    // Plot a simple line: y = x
    grid.Plot(pdf, 0, 50, 50, func(x float64) float64 {
        return x
    })
  8. Understand the SVGBasicType structure

    main

    The SVGBasicType struct is the primary descriptor for a parsed basic vector image. It aggregates the dimensions and the geometric segments required to reconstruct the image.

    Fields:

    • Wd (float64): The width of the SVG in points.
    • Ht (float64): The height of the SVG in points.
    • Segments ([][]SVGBasicSegmentType): A slice of paths, where each path is a slice of individual movement/drawing segments.
  9. Create internal and external links

    main

    PDF links can be internal (jumping to a location in the document) or external (opening a URL).

    Internal Links:

    1. Call AddLink() to create a link identifier.
    2. Call SetLink(link, y, page) to define the destination. If y or page are -1, they default to the current position/page.
    3. Pass the returned integer to Cell(), Write(), Image(), or Link() to make that element clickable.

    External Links:

    • Use LinkString(x, y, w, h, linkStr) to create a clickable rectangular area for a URL.
    • Use WriteLinkString(h, displayStr, targetStr) to make flowing text a clickable URL.
    • Use ImageOptions with the linkStr parameter to make an image a clickable URL.
    // Internal Link Example
    linkID := f.AddLink()
    f.SetLink(linkID, 50, 2) // Link to page 2, y=50
    
    f.Cell(40, 10, "Jump to Page 2", "1", 0, "C", false, linkID, "")
  10. Configure PDF metadata and info

    main

    The Fpdf instance allows you to set document metadata which is included in the PDF's /Info dictionary. This includes:

    • Producer
    • Title
    • Subject
    • Author
    • Keywords
    • Creator
    • CreationDate
    • ModDate (Modification Date)

    Dates are automatically formatted into the PDF standard D:YYYYMMDDHHMMSS format.

  11. Install the fpdf package

    main

    To install the fpdf package, use the standard Go get command:

    go get github.com/go-pdf/fpdf

    To receive updates later, run:

    go get -u -v github.com/go-pdf/fpdf/...
    go get github.com/go-pdf/fpdf
  12. Draw complex paths using MoveTo, LineTo, and CurveTo

    main

    To create high-quality shapes with smooth line joins, use the path drawing API instead of individual line commands. A path is constructed by moving a virtual stylus around the page and then applying a drawing or filling operation.

    1. Initialize the path: Use MoveTo(x, y) to set the starting position.
    2. Define the shape:
      • LineTo(x, y): Adds a straight line segment.
      • CurveTo(cx, cy, x, y): Adds a quadratic Bézier curve segment.
      • CurveBezierCubicTo(cx0, cy0, cx1, cy1, x, y): Adds a cubic Bézier curve segment.
      • ArcTo(...): Adds an elliptical arc.
      • ClosePath(): Connects the current point back to the last MoveTo point.
    3. Render the path: Use DrawPath(styleStr) to actually paint the shape on the page.
    f.MoveTo(10, 10)
    f.LineTo(50, 50)
    f.CurveTo(75, 75, 100, 100)
    f.ClosePath()
    f.DrawPath("DF") // Draws an outlined and filled path