gopdf Documentation

repository·master·Indexed 25 days ago

https://github.com/signintech/gopdf

A simple Go library for generating PDF documents. It supports Unicode subfont embedding for languages such as Chinese, Japanese, and Korean, vector graphics (lines, ovals, rectangles, curves), and image support for JPG and PNG. Key features include password protection, font kerning, text alignment, superscript/subscript styling, RGB and CMYK color models, internal/external links, and table layouts via TableLayout. It also provides specialized support for Arabic character representation and shaping.

Tokens
10.3K
Snippets
26
Records
87
Agent score
83%

What's inside gopdf

  1. Overview of gopdf features

    master

    gopdf is a Go library for generating PDF documents. Key features include:

    • Unicode subfont embedding: Supports Chinese, Japanese, Korean, and other languages.
    • Vector Graphics: Ability to draw lines, ovals, rectangles, and curves.
    • Image Support: Draw JPG and PNG images, including setting image masks.
    • Security: Password protection for PDF files.
    • Typography: Supports font kerning and various text alignments (left, center, right, justify).
    • Advanced Text: Support for superscript, subscript, and color models (RGB and CMYK).
  2. Print text in a PDF

    master

    To print text, initialize a gopdf.GoPdf instance, start it with a gopdf.Config (e.g., *gopdf.PageSizeA4), add a page, add a TTF font using AddTTFFont, set the font with SetFont, and use Cell to write text.

    package main
    import (
    	"log"
    	"github.com/signintech/gopdf"
    )
    
    func main() {
    	pdf := gopdf.GoPdf{}
    	pdf.Start(gopdf.Config{ PageSize: *gopdf.PageSizeA4 })
    	pdf.AddPage()
    	err := pdf.AddTTFFont("wts11", "../ttf/wts11.ttf")
    	if err != nil {
    		log.Print(err.Error())
    		return
    	}
    
    	err = pdf.SetFont("wts11", "", 14)
    	if err != nil {
    		log.Print(err.Error())
    		return
    	}
    	pdf.Cell(nil, "您好")
    	pdf.WritePdf("hello.pdf")
    }
  3. Import existing PDF pages

    master

    You can import pages from an existing PDF file using pdf.ImportPage(filename, page_number, box_type). The imported page is returned as a template which can then be drawn onto the current document using pdf.UseImportedTemplate(template, x, y, w, h). Note: This functionality relies on the gofpdi package logic.

    // Import page 1
    tpl1 := pdf.ImportPage("example-pdf.pdf", 1, "/MediaBox")
    
    // Draw imported template onto current page
    pdf.UseImportedTemplate(tpl1, 50, 100, 400, 0)
  4. Protect PDF with passwords

    master

    Configure password protection during pdf.Start() using gopdf.PDFProtectionConfig. You can specify permissions (e.g., PermissionsPrint, PermissionsCopy, PermissionsModify) and set both OwnerPass and UserPass as byte slices.

    pdf.Start(gopdf.Config{
        PageSize: *gopdf.PageSizeA4,
        Protection: gopdf.PDFProtectionConfig{
            UseProtection: true,
            Permissions: gopdf.PermissionsPrint | gopdf.PermissionsCopy | gopdf.PermissionsModify,
            OwnerPass:   []byte("123456"),
            UserPass:    []byte("123456789")
        },
    })
  5. Add external and internal links

    master

    To add links to a PDF:

    • External Links: Use pdf.AddExternalLink(url, x, y, w, h) to create a clickable area over text.
    • Internal Links (Anchors):
      1. Define an anchor using pdf.SetAnchor("name") at the target location.
      2. Create the link using pdf.AddInternalLink("name", x, y, w, h) at the source location.
    // External link
    pdf.Text("Link to example.com")
    pdf.AddExternalLink("http://example.com/", 27.5, 28, 125, 15)
    
    // Internal link
    pdf.Text("Link to second page")
    pdf.AddInternalLink("anchor", 27.5, 58, 120, 15)
    
    // Target anchor
    pdf.SetXY(30, 100)
    pdf.SetAnchor("anchor")
    pdf.Text("Anchor position")
  6. Set TrimBox for pages

    master
    You can set a TrimBox globally in pdf.Start(gopdf.Config{...}) or specifically for a page using pdf.AddPageWithOption(gopdf.PageOption{...}). The TrimBox is a gopdf.Box containing Left, Top, Right, and Bottom values.
  7. Rotate text or images

    master

    Use pdf.Rotate(angle, x, y) to rotate the coordinate system around a point, then draw your content. Always call pdf.RotateReset() to return to the original orientation.

    pdf.SetXY(100, 100)
    pdf.Rotate(270.0, 100.0, 100.0)
    pdf.Text("Hello...")
    pdf.RotateReset()
  8. Use Placeholders for dynamic text

    master

    If you need to print text that depends on information not known until the end of the document (like total page count), use the placeholder system:

    1. Create a placeholder: pdf.PlaceHolderText(id, size).
    2. Fill the placeholder: pdf.FillInPlaceHoldText(id, text, alignment) (where alignment is Left, Center, or Right).
  9. Set superscript and subscript text

    master

    Use SetFontWithStyle to apply gopdf.Superscript or gopdf.Subscript. The glyph size and baseline shift are derived from the font's metrics, while the logical font size maintains the line layout.

    pdf.SetFont("font", "", 14)
    pdf.Cell(nil, "E = mc")
    pdf.SetFontWithStyle("font", gopdf.Superscript, 14)
    pdf.Cell(nil, "2")
    pdf.SetFontWithStyle("font", gopdf.Regular, 14)
    pdf.Cell(nil, ", said Einstein")