docpdf

package module
v0.0.57 Latest Latest
Warning

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

Go to latest
Published: May 1, 2025 License: MIT Imports: 35 Imported by: 0

README

docpdf

An open-source Go library for generating PDFs with a minimalist and intuitive API, similar to writing in Word. Optimized to run in the browser with WebAssembly without dependencies.

Description

docpdf is a Go library that allows you to generate PDF documents with an intuitive and simple API. It is designed to be easy to use, with an approach similar to writing in a word processor like Word. The library is optimized to work in the browser with WebAssembly.

The main focus of this library is to compile into a compact binary size using TinyGo for frontend usage, as standard Go binaries tend to be large. This makes it ideal for web applications where binary size matters.

Font Convention

By default, docpdf expects the following font files in the fonts/ directory (relative to your application's execution path or as specified in Font.Path):

  • regular.ttf: For the normal text style.
  • bold.ttf: For the bold text style.
  • italic.ttf: For the italic text style.

You can override these defaults by providing a custom Font configuration when creating the document:

customFont := docpdf.Font{
    Regular: "MyCustomFont-Regular.ttf",
    Bold:    "MyCustomFont-Bold.ttf",
    Italic:  "MyCustomFont-Italic.ttf",
    Path:    "assets/fonts/", // Optional: specify a different path
}
doc := docpdf.NewDocument(customFont)

If you only provide Regular, the library will use the regular font for bold and italic styles as well.

TinyGo Compatibility Checklist

The following standard libraries will be replaced or modified as they are not 100% compatible with TinyGo, in order to reduce the binary size:

  • bufio
  • crypto/sha1
  • errors
  • fmt
  • golang.org/x/image
  • io
  • os
  • path/filepath
  • sort
  • strings
  • sync
  • time

Getting Started

Creating a new document is simple. A file writer function is optional but can be provided to customize how the PDF is saved:

// Basic usage with default file writer (uses os.WriteFile in backend environments)
doc := NewDocument()

// With custom file writer
doc := NewDocument(os.WriteFile)

// For web applications (example using a fictional HTTP response interface)
doc := NewDocument(func(filename string, data []byte) error {
    resp.Header().Set("Content-Type", "application/pdf")
    resp.Header().Set("Content-Disposition", "attachment; filename="+filename)
    _, err := resp.Write(data)
    return err
})

Page Size Options

The library offers multiple ways to specify page sizes for your documents:

  1. Using predefined page sizes:

    doc := NewDocument(PageSizeA4)  // Use A4 page size
    doc := NewDocument(PageSizeLetter)  // Use Letter page size
    
  2. Using the new PageSize struct with unit specification:

    // Create an A4 page size (210mm x 297mm) with millimeter units
    doc := NewDocument(PageSize{Width: 210, Height: 297, Unit: UnitMM})
    
    // Create a US Letter page size (8.5in x 11in) with inch units
    doc := NewDocument(PageSize{Width: 8.5, Height: 11, Unit: UnitIN})
    
  3. Combining options:

    doc := NewDocument(
       PageSize{Width: 210, Height: 297, Unit: UnitMM},  // A4 size
       Margins{Left: 15, Top: 10, Right: 10, Bottom: 10},  // Custom margins
       os.WriteFile  // Custom file writer (optional)
    )
    

Usage Example:

Page 1

image

Page 2

image

This example shows the main features of the library:

	// Create a document with default settings
	doc := NewDocument()

	// Or with custom file writer
	// doc := NewDocument(os.WriteFile)

	// Setup header and footer with the new API
	doc.SetPageHeader().
		SetLeftText("Header Left").
		SetCenterText("Document Example").
		SetRightText("Confidential").
		// ShowOnFirstPage()

		// Add footer with page numbers in format X/Y
		doc.SetPageFooter().
		SetLeftText("Created: 2023-10-01").
		SetCenterText("footer center example").
		WithPageTotal(Right).
		ShowOnFirstPage()

	// add logo image
	doc.AddImage("test/res/logo.png").Height(35).Inline().Draw()

	// add date and time aligned to the right
	doc.AddText("date: 2024-10-01").AlignRight().Inline().Draw()

	// Add a centered header
	doc.AddHeader1("Example Document").AlignCenter().Draw()

	// Add a level 2 header
	doc.AddHeader2("Section 1: Introduction").Draw()

	// Add normal text
	doc.AddText("This is a normal text paragraph that shows the basic capabilities of the gopdf library. " +
		"We can create documents with different text styles and formats.").Draw()

	// Add text with different styles
	doc.AddText("This text is in bold.").Bold().Draw()

	doc.AddText("This text is in italic.").Italic().Draw()

	// Add right-aligned text (ensuring it's in regular style, not italic)
	doc.AddText("This text is right-aligned.").Regular().AlignRight().Draw()

	// Create and add a bar chart using the new API instead of static image
	barChart := doc.AddBarChart().
		Title("Monthly Sales").
		Height(320).	
		AlignCenter().
		BarWidth(50).
		BarSpacing(10)

	// Add data to the chart
	barChart.AddBar(120, "Jan").
		AddBar(140, "Feb").
		AddBar(160, "Mar").
		AddBar(180, "Apr").
		AddBar(120, "May").
		AddBar(140, "Jun")

	// Configurar el gráfico para mostrar los ejes
	barChart.WithAxis(true, true)

	// Renderizar el gráfico
	barChart.Draw()

	// Save the document to a file
	err := doc.WritePdf("example_document.pdf")
	if err != nil {
		log.Fatalf("Error writing PDF: %v", err)
	}

Acknowledgements

This library would not have been possible without github repositories:

  • signintech/gopdf
  • phpdave11/gofpdi
  • wcharczuk/go-chart
  • golang/freetype

Important

this library is still in development and not all features are implemented yet. please check the issues for more information.

Documentation

Overview

filepath: c:\Users\Cesar\Packages\Internal\docpdf\docChart.go

Example (FormatFloatTrim)
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

Index

Examples

Constants

View Source
const (
	UnitUnset = iota // No units were set, when conversion is called on nothing will happen
	UnitPT           // Points - 1/72 of an inch, traditional unit in PDF documents
	UnitMM           // Millimeters - 1/10 of a centimeter, metric measurement unit
	UnitCM           // Centimeters - 1/100 of a meter, metric measurement unit
	UnitIN           // Inches - Imperial unit equal to 72 points
	UnitPX           // Pixels - screen unit (by default 96 DPI, thus 72/96 = 3/4 point)

)

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 (
	FontRegular = "regular"
	FontBold    = "bold"
	FontItalic  = "italic"
)

FontStyle defines the available font styles

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 (
	// Left representa alineación a la izquierda
	Left position = 8 //001000
	// Top representa alineación superior
	Top position = 4 //000100
	// Right representa alineación a la derecha
	Right position = 2 //000010
	// Bottom representa alineación inferior
	Bottom position = 1 //000001
	// Center representa alineación al centro
	Center position = 16 //010000
	// Middle representa alineación al medio
	Middle position = 32 //100000
	// Justify representa texto justificado
	Justify position = 64 //1000000
	// AllBorders representa todos los bordes
	AllBorders position = 15 //001111
)
View Source
const Bold = 2 //000010

Bold - font style bold

View Source
const Italic = 1 //000001

Italic - font style italic

View Source
const Regular = 0 //000000

Regular - font style regular

View Source
const Underline = 4 //000100

Underline - font style underline

Variables

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

Types

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 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 Document

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

func NewDocument

func NewDocument(configs ...any) *Document

NewDocument creates a new PDF document with configurable settings Accepts optional configurations:

Optional configurations include:

  • FontConfig: Custom font configuration
  • Font: Custom font family
  • Margins: Custom margins in millimeters (more intuitive than points)
  • PageSize: Custom page size with desired units
  • *Rect: Predefined page size (like PageSizeLetter, PageSizeA4, etc.)
  • func(string, []byte) error: Custom file writer function (if not provided, defaults to env.SetupDefaultFileWriter())

Examples:

  • NewDocument() // Uses default file writer
  • NewDocument(os.WriteFile) // Custom file writer
  • NewDocument(Margins{Left: 15, Top: 10, Right: 10, Bottom: 10})
  • NewDocument(PageSize{Width: 210, Height: 297, Unit: UnitMM}) // A4 size in mm
  • NewDocument(PageSizeA4) // Using predefined page size
  • NewDocument(os.WriteFile, PageSizeA4, Margins{Left: 20, Top: 10, Right: 20, Bottom: 10})

For web applications:

  • NewDocument(func(filename string, data []byte) error { response.Header().Set("Content-Type", "application/pdf") _, err := response.Write(data) return err })
func (gp Document) AddExternalLink(url string, x, y, w, h float64)

AddExternalLink adds a new external link.

func (Document) AddFooter

func (gp Document) AddFooter(f func())

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

func (*Document) AddFootnote

func (d *Document) AddFootnote(text string) *docText

AddFootnote crea una nota al pie

func (Document) AddHeader

func (gp Document) AddHeader(f func())

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

func (*Document) AddHeader1

func (d *Document) AddHeader1(text string) *docText

AddHeader1 crea un encabezado nivel 1

func (*Document) AddHeader2

func (d *Document) AddHeader2(text string) *docText

AddHeader2 crea un encabezado nivel 2

func (*Document) AddHeader3

func (d *Document) AddHeader3(text string) *docText

AddHeader3 crea un encabezado nivel 3

func (*Document) AddImage

func (doc *Document) AddImage(imagePathOrContent any) *docImage

AddImage creates a new image element in the document supporting both absolute and relative paths or image data in []byte format eg: doc.AddImage("path/to/image.png") or doc.AddImage([]byte{...})

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

AddInternalLink adds a new internal link.

func (*Document) AddJustifiedText

func (d *Document) AddJustifiedText(text string) *docText

AddJustifiedText crea texto justificado directamente

func (Document) AddOutline

func (gp Document) AddOutline(title string)

func (Document) AddOutlineWithPosition

func (gp Document) AddOutlineWithPosition(title string) *outlineObj

AddOutlineWithPosition add an outline with position

func (*Document) AddPage

func (doc *Document) AddPage()

AddPage añade una nueva página y actualiza el contador de páginas para el header y footer

func (*Document) AddPageFooter

func (d *Document) AddPageFooter(text string) *docText

AddPageFooter adds a footer to the document (legacy method for backward compatibility)

func (*Document) AddPageHeader

func (d *Document) AddPageHeader(text string) *docText

AddPageHeader adds a header to the document (legacy method for backward compatibility)

func (*Document) AddPageWithOption

func (doc *Document) AddPageWithOption(opt pageOption)

AddPageWithOption añade una nueva página con opciones y actualiza el contador de páginas para el header y footer

func (Document) AddTTFFont

func (gp Document) AddTTFFont(family string, ttfpath string) error

AddTTFFont : add font file

func (Document) AddTTFFontByReader

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

AddTTFFontByReader adds font file by reader.

func (Document) AddTTFFontByReaderWithOption

func (gp Document) AddTTFFontByReaderWithOption(family string, rd io.Reader, option ttfOption) error

AddTTFFontByReaderWithOption adds font file by reader with option.

func (Document) AddTTFFontData

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

AddTTFFontByReader adds font data by reader.

func (Document) AddTTFFontDataWithOption

func (gp Document) AddTTFFontDataWithOption(family string, fontData []byte, option ttfOption) error

AddTTFFontDataWithOption adds font data with option.

func (Document) AddTTFFontWithOption

func (gp Document) AddTTFFontWithOption(family string, ttfpath string, option ttfOption) error

AddTTFFontWithOption : add font file

func (*Document) AddText

func (d *Document) AddText(text string) *docText

AddText crea texto normal

func (Document) Br

func (gp Document) Br(h float64)

Br : new line

func (Document) Cell

func (gp Document) 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 (Document) CellWithOption

func (gp Document) CellWithOption(rectangle *Rect, text string, opt cellOption) error

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

func (*Document) Chart added in v0.0.48

func (doc *Document) Chart() *docCharts

Chart es el punto de entrada para la API de gráficos

func (Document) ClearTransparency

func (gp Document) ClearTransparency()

func (Document) Close

func (gp Document) Close() error

Close clears the gopdf buffer.

func (Document) Curve

func (gp Document) 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 (Document) FillInPlaceHoldText

func (gp Document) FillInPlaceHoldText(placeHolderName string, text string, align position) error

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

func (Document) GetBytesPdf

func (gp Document) GetBytesPdf() []byte

GetBytesPdf : get bytes of pdf file

func (Document) GetBytesPdfReturnErr

func (gp Document) GetBytesPdfReturnErr() ([]byte, error)

GetBytesPdfReturnErr : get bytes of pdf file

func (Document) GetInfo

func (gp Document) GetInfo() PdfInfo

GetInfo get Document Information Dictionary

func (*Document) GetLineHeight

func (doc *Document) GetLineHeight() float64

GetLineHeight returns the current line height based on the active font and size

func (Document) GetNextObjectID

func (gp Document) GetNextObjectID() int

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

func (Document) GetNumberOfPages

func (gp Document) GetNumberOfPages() int

GetNumberOfPages gets the number of pages from the PDF.

func (Document) GetX

func (gp Document) GetX() float64

GetX : get current position X

func (Document) GetY

func (gp Document) GetY() float64

GetY : get current position y

func (Document) ImageByHolderWithOptions

func (gp Document) ImageByHolderWithOptions(img imageHolder, opts imageOptions) error

func (Document) ImageFrom

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

func (Document) ImageFromWithOption

func (gp Document) ImageFromWithOption(img image.Image, opts imageFromOption) error

func (Document) ImportObjects

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

ImportObjects imports objects from gofpdi into current document.

func (Document) ImportPage

func (gp Document) ImportPage(sourceFile string, pageno int, box string) int

ImportPage imports a page and return template id. gofpdi code

func (Document) ImportPageStream

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

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

func (Document) ImportPagesFromSource

func (gp Document) ImportPagesFromSource(source any, box string) error

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

func (Document) ImportTemplates

func (gp Document) ImportTemplates(tpls map[string]int)

ImportTemplates names into procset dictionary.

func (Document) IsCurrFontContainGlyph

func (gp Document) IsCurrFontContainGlyph(r rune) (bool, error)

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

func (Document) IsFitMultiCell

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

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

func (Document) IsFitMultiCellWithNewline

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

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

func (Document) KernOverride

func (gp Document) KernOverride(family string, fn funcKernOverride) error

KernOverride override kern value

func (Document) Line

func (gp Document) Line(x1 float64, y1 float64, x2 float64, y2 float64)

Line : draw line

Usage:
pdf.SetTransparency(docpdf.transparency{Alpha: 0.5,blendModeType: docpdf.colorBurn})
pdf.SetLineType("dotted")
pdf.SetStrokeColor(255, 0, 0)
pdf.SetLineWidth(2)
pdf.Line(10, 30, 585, 30)
pdf.ClearTransparency()

func (Document) MarginBottom

func (gp Document) MarginBottom() float64

MarginBottom returns the bottom margin.

func (Document) MarginLeft

func (gp Document) MarginLeft() float64

MarginLeft returns the left margin.

func (Document) MarginRight

func (gp Document) MarginRight() float64

MarginRight returns the right margin.

func (Document) MarginTop

func (gp Document) MarginTop() float64

MarginTop returns the top margin.

func (Document) Margins

func (gp Document) 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 (Document) MeasureCellHeightByText

func (gp Document) MeasureCellHeightByText(text string) (float64, error)

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

func (Document) MeasureTextWidth

func (gp Document) MeasureTextWidth(text string) (float64, error)

MeasureTextWidth : measure Width of text (use current font)

func (Document) MultiCell

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

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

func (Document) MultiCellJustified

func (gp Document) MultiCellJustified(rectangle *Rect, text string) error

MultiCellJustified dibuja texto justificado dentro de un rectángulo

func (Document) MultiCellWithOption

func (gp Document) 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 (*Document) NewStyledCell

func (doc *Document) NewStyledCell(content string, style CellStyle) styledCell

NewStyledCell creates a new cell with custom styling

func (*Document) NewTable

func (doc *Document) NewTable(headers ...string) *docTable

NewTable creates a new table with the specified headers Headers can include formatting options in the following format.

Format: "headerTitle|option1,option2,option3,..."

Available options:

  • Header alignment: "HL" (left), "HC" (center, default), "HR" (right)
  • Column alignment: "CL" (left, default), "CC" (center), "CR" (right)
  • Prefix/Suffix: "P:value" (adds prefix), "S:value" (adds suffix)
  • Width: "W:number" (fixed width), "W:number%" (percentage width) Note: If width is not specified, auto width is used by default

Examples:

  • "Name" - Normal header, left-aligned column, auto width
  • "Price|HR,CR" - Right-aligned header, right-aligned column
  • "Price|HR,CR,P:$" - Right-aligned header, right-aligned column with "$" prefix
  • "Percentage|HC,CC,S:%" - Center-aligned header, center-aligned column with "%" suffix
  • "Name|HL,CL,W:30%" - Left-aligned header, left-aligned column with 30% of available width
  • "Age|HC,CR,W:20" - Center-aligned header, right-aligned column with fixed width of 20 units

func (Document) Oval

func (gp Document) Oval(x1 float64, y1 float64, x2 float64, y2 float64)

Oval : draw oval

func (*Document) PdfEngine

func (doc *Document) PdfEngine() *pdfEngine

returns the current PDF engine instance

func (Document) PlaceHolderText

func (gp Document) PlaceHolderText(placeHolderName string, placeHolderWidth float64) error

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

func (Document) Polygon

func (gp Document) 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([]docpdf.point{{X: 10, Y: 30}, {X: 585, Y: 200}, {X: 585, Y: 250}}, "DF")

func (Document) Read

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

func (Document) RectFromLowerLeft

func (gp Document) RectFromLowerLeft(x float64, y float64, wdth float64, hght float64)

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

func (Document) RectFromLowerLeftWithOpts

func (gp Document) RectFromLowerLeftWithOpts(opts drawableRectOptions) error

func (Document) RectFromLowerLeftWithStyle

func (gp Document) 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 (Document) RectFromUpperLeft

func (gp Document) RectFromUpperLeft(x float64, y float64, wdth float64, hght float64)

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

func (Document) RectFromUpperLeftWithOpts

func (gp Document) RectFromUpperLeftWithOpts(opts drawableRectOptions) error

func (Document) RectFromUpperLeftWithStyle

func (gp Document) 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 (Document) Rectangle

func (gp Document) 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 (*Document) RedrawHeaderFooter

func (doc *Document) RedrawHeaderFooter()

RedrawHeaderFooter fuerza el redibujado del encabezado y pie de página en la página actual

func (Document) Rotate

func (gp Document) Rotate(angle, x, y float64)

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

func (Document) RotateReset

func (gp Document) RotateReset()

RotateReset reset rotate

func (Document) SetAnchor

func (gp Document) SetAnchor(name string)

SetAnchor creates a new anchor.

func (Document) SetCharSpacing

func (gp Document) SetCharSpacing(charSpacing float64) error

SetCharSpacing : set the character spacing of the currently active font

func (Document) SetCompressLevel

func (gp Document) 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 (Document) SetCustomLineType

func (gp Document) 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 (Document) SetFileWriter added in v0.0.23

func (gp Document) SetFileWriter(writer fileWriter)

SetFileWriter sets a custom function for writing PDF files

func (Document) SetFillColor

func (gp Document) SetFillColor(r uint8, g uint8, b uint8)

SetFillColor set the color for the stroke

func (Document) SetFillColorCMYK

func (gp Document) SetFillColorCMYK(c, m, y, k uint8)

SetFillColorCMYK set the color for the fill in CMYK color mode

func (Document) SetFont

func (gp Document) SetFont(family string, style string, size any) 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 (Document) SetFontSize

func (gp Document) SetFontSize(fontSize float64) error

SetFontSize : set the font size (and only the font size) of the currently active font

func (Document) SetFontWithStyle

func (gp Document) SetFontWithStyle(family string, style int, size any) 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 (Document) SetGrayFill

func (gp Document) SetGrayFill(grayScale float64)

SetGrayFill set the grayscale for the fill, takes a float64 between 0.0 and 1.0

func (Document) SetGrayStroke

func (gp Document) SetGrayStroke(grayScale float64)

SetGrayStroke set the grayscale for the stroke, takes a float64 between 0.0 and 1.0

func (Document) SetInfo

func (gp Document) SetInfo(info PdfInfo)

SetInfo set Document Information Dictionary

func (Document) SetLeftMargin

func (gp Document) SetLeftMargin(margin float64)

SetLeftMargin sets left margin.

func (Document) SetLineType

func (gp Document) 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 (Document) SetLineWidth

func (gp Document) SetLineWidth(width float64)

SetLineWidth : set line width

func (Document) SetMarginBottom

func (gp Document) SetMarginBottom(margin float64)

SetMarginBottom set the bottom margin

func (Document) SetMarginLeft

func (gp Document) SetMarginLeft(margin float64)

SetMarginLeft sets the left margin

func (Document) SetMarginRight

func (gp Document) SetMarginRight(margin float64)

SetMarginRight sets the right margin

func (Document) SetMarginTop

func (gp Document) SetMarginTop(margin float64)

SetMarginTop sets the top margin

func (Document) SetMargins

func (gp Document) 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 (Document) SetNewXY

func (gp Document) 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 (Document) SetNewY

func (gp Document) 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 (Document) SetNewYIfNoOffset

func (gp Document) 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 (Document) SetNoCompression

func (gp Document) SetNoCompression()

SetNoCompression : compressLevel = 0

func (Document) SetPage

func (gp Document) SetPage(pageno int) error

SetPage set current page

func (*Document) SetPageFooter

func (d *Document) SetPageFooter() *headerFooter

SetPageFooter sets the document footer

func (*Document) SetPageHeader

func (d *Document) SetPageHeader() *headerFooter

SetPageHeader sets the document header

func (Document) SetStrokeColor

func (gp Document) SetStrokeColor(r uint8, g uint8, b uint8)

SetStrokeColor set the color for the stroke

func (Document) SetStrokeColorCMYK

func (gp Document) SetStrokeColorCMYK(c, m, y, k uint8)

SetStrokeColorCMYK set the color for the stroke in CMYK color mode

func (Document) SetTextColor

func (gp Document) SetTextColor(r uint8, g uint8, b uint8)

SetTextColor : function sets the text color

func (Document) SetTextColorCMYK

func (gp Document) SetTextColorCMYK(c, m, y, k uint8)

func (Document) SetTopMargin

func (gp Document) SetTopMargin(margin float64)

SetTopMargin sets top margin.

func (Document) SetTransparency

func (gp Document) 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 (Document) SetX

func (gp Document) SetX(x float64)

SetX : set current position X

func (Document) SetXY

func (gp Document) SetXY(x, y float64)

SetXY : set current position x and y

func (Document) SetY

func (gp Document) SetY(y float64)

SetY : set current position y

func (*Document) SpaceBefore

func (d *Document) SpaceBefore(spaces ...float64)

SpaceBefore adds vertical space (in font spaces) example: SpaceBefore(2) adds 2 spaces before the text

func (Document) SplitText

func (gp Document) SplitText(text string, width float64) ([]string, error)

SplitText splits text into multiple lines based on width performing potential mid-word breaks.

func (Document) SplitTextWithOption

func (gp Document) 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 (Document) SplitTextWithWordWrap

func (gp Document) 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 (Document) Start

func (gp Document) Start(config config)

Start : init gopdf

func (Document) StartWithImporter

func (gp Document) StartWithImporter(config config, importer *importer)

func (Document) Text

func (gp Document) Text(text string) error

Text write text start at current x,y ( current y is the baseline of text )

func (Document) UseImportedTemplate

func (gp Document) UseImportedTemplate(tplid int, x float64, y float64, w float64, h float64)

UseImportedTemplate draws an imported PDF page.

func (Document) Write deprecated

func (gp Document) Write(w io.Writer) error

Write streams the pdf as it is compiled to an io.Writer

Deprecated: use the WritePdf method instead.

func (Document) WritePdf

func (gp Document) WritePdf(pdfPath string) error

WritePdf writes the PDF file to the specified path using the configured FileWriter

func (Document) WriteTo

func (gp Document) WriteTo(w io.Writer) (n int64, err error)

WritePdf implements the io.WriterTo interface and can be used to stream the PDF as it is compiled to an io.Writer.

type Font

type Font struct {
	// Regular specifies the filename for the regular font style.
	// It's recommended to name this file "regular.ttf".
	Regular string
	// Bold specifies the filename for the bold font style.
	// It's recommended to name this file "bold.ttf".
	Bold string
	// Italic specifies the filename for the italic font style.
	// It's recommended to name this file "italic.ttf".
	Italic string
	// Path specifies the base directory where the font files are located.
	// Defaults to "fonts/".
	Path string // Base path for fonts
}

Font represents font files for different styles

type FontConfig

type FontConfig struct {
	Family         Font
	Normal         TextStyle
	Header1        TextStyle
	Header2        TextStyle
	Header3        TextStyle
	Footnote       TextStyle
	PageHeader     TextStyle
	PageFooter     TextStyle
	ChartLabel     TextStyle // For chart bar labels/values
	ChartAxisLabel TextStyle // For chart axis labels (X/Y axes)
}

FontConfig represents different font configurations for document sections

type Margins

type Margins struct {
	Left, Top, Right, Bottom float64
}

Margins type.

type PageSize added in v0.0.15

type PageSize struct {
	Width  float64 // Width of the page
	Height float64 // Height of the page
	Unit   int     // Unit type (UnitPT, UnitMM, UnitCM, UnitIN, UnitPX)
}

PageSize provides an intuitive way to define custom page sizes It allows users to specify width and height in their preferred unit of measurement

func (PageSize) ToRect added in v0.0.15

func (ps PageSize) ToRect() *Rect

ToRect converts a PageSize to a Rect for internal use

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 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 Rect

type Rect struct {
	W float64 // Width of the rectangle
	H float64 // Height of the rectangle
	// contains filtered or unexported fields
}

Rect defines a rectangle by its width and height. This is used for defining page sizes, content areas, and other rectangular regions in PDF documents. The dimensions are stored in the current unit system (points by default, but can be mm, cm, inches, or pixels).

type TextStyle

type TextStyle struct {
	Size        float64
	Color       RGBColor
	LineSpacing float64
	Alignment   position // Uses same alignment constants as cellOption (Left, Center, Right, etc)
	SpaceBefore float64  // Space before paragraph (in points)
	SpaceAfter  float64  // Space after paragraph (in points)
}

TextStyle defines text appearance properties

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL