gotenberg

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 27, 2025 License: MIT Imports: 11 Imported by: 0

README

gotenberg-client

Go Reference Go Report Card License

A clean, performant and idiomatic Go client for the Gotenberg HTTP API.

Features

  • 🚀 High Performance: Optimized buffer pools and minimal allocations
  • 🎯 Fluent API: Modern builder pattern for readable configuration
  • 🔄 Streaming Support: Handle large PDFs without memory buffering
  • 📦 Zero Dependencies: Uses only Go standard library
  • 🔗 Webhook Support: Full async processing with webhooks
  • Context Support: Proper timeout and cancellation handling
  • 🛡️ Type Safe: Compile-time validation of configurations

Installation

go get github.com/nativebpm/gotenberg-client

Requirements: Go 1.21 or later

Quick Start

package main

import (
    "context"
    "time"
    "github.com/nativebpm/gotenberg-client"
)

func main() {
    htmlContent := `<html><body><h1>Hello Gotenberg!</h1></body></html>`
    
    // Create PDF with fluent builder API
    resp, err := gotenberg.NewClientBuilder("http://localhost:3000").
        WithTimeout(30 * time.Second).
        ConvertHTML().
        WithHTML(htmlContent).
        PaperSizeA4().
        Margins(1.0, 1.0, 1.0, 1.0).
        PrintBackground(true).
        OutputFilename("hello.pdf").
        Execute(context.Background())
    
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    
    // Save response to file...
}
Traditional Approach
package main

import (
    "context"
    "net/http"
    "time"
    
    "github.com/nativebpm/gotenberg-client"
)

func main() {
    client := gotenberg.NewClient(
        &http.Client{Timeout: 30 * time.Second},
        "http://localhost:3000",
    )
    
    resp, err := client.ConvertURLToPDF(context.Background(), "https://example.com")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    
    // Save or stream the PDF...
}

Usage Examples

URL to PDF with Builder Pattern
// Convert a webpage to PDF with custom settings
resp, err := gotenberg.NewClientBuilder("http://localhost:3000").
    ConvertURL().
    WithURL("https://example.com").
    PaperSizeLetter().
    Landscape(true).
    Margins(0.5, 0.5, 0.5, 0.5).
    PrintBackground(false).
    OutputFilename("webpage.pdf").
    Execute(context.Background())
HTML with CSS and Assets
htmlContent := `<html><head><link rel="stylesheet" href="styles.css"></head>
<body><h1 class="title">Styled Document</h1><img src="logo.png"></body></html>`

cssContent := `.title { color: #007bff; font-size: 24px; }`

// Load logo image
logoFile, _ := os.Open("logo.png")
defer logoFile.Close()

resp, err := gotenberg.NewClientBuilder("http://localhost:3000").
    ConvertHTML().
    WithHTML(htmlContent).
    WithCSS(cssContent).
    WithFile("logo.png", logoFile).
    PaperSizeA4().
    PrintBackground(true).
    Execute(context.Background())
Traditional API (still supported)
ctx := context.Background()
httpClient := &http.Client{Timeout: 30 * time.Second}
cli := gotenberg.NewClient(httpClient, "http://localhost:3000")

resp, err := cli.ConvertURLToPDF(ctx, "https://example.com")
if err != nil {
    // handle error
}
defer resp.Body.Close()

// stream or save the PDF
// out, _ := os.Create("out.pdf")
// io.Copy(out, resp.Body)
htmlContent := "<html><body><h1>Hello World</h1></body></html>"
cssContent := "h1 { color: blue; }"

// Use fluent builder pattern for clean, readable configuration
options := gotenberg.NewOptionsBuilder().
    File("styles.css", bytes.NewReader([]byte(cssContent))).
    PaperSizeA4().
    Margins(1.0, 1.0, 1.0, 1.0).
    PrintBackground(true).
    Scale(0.9).
    OutputFilename("document.pdf").
    Build()

resp, err := cli.ConvertHTMLToPDF(ctx, bytes.NewReader([]byte(htmlContent)), options)
if err != nil {
    // handle error
}
defer resp.Body.Close()
Webhook Configuration with Builder
options := gotenberg.NewOptionsBuilder().
    PaperSizeLetter().
    WebhookSuccess("https://your-domain.com/webhook/success", "POST").
    WebhookError("https://your-domain.com/webhook/error", "POST").
    WebhookExtraHeader("Authorization", "Bearer your-token").
    OutputFilename("async-document.pdf").
    Build()

resp, err := cli.ConvertURLToPDF(ctx, "https://example.com", options)

API Reference

Builder Pattern API

The modern builder pattern provides a fluent, chainable interface for PDF generation:

// ClientBuilder - creates and configures HTTP client
gotenberg.NewClientBuilder(baseURL string) *ClientBuilder
  .WithTimeout(duration) *ClientBuilder
  .WithHTTPClient(client) *ClientBuilder
  .ConvertHTML() *HTMLConversionBuilder
  .ConvertURL() *URLConversionBuilder
  .Build() *Client

// HTMLConversionBuilder - configures HTML to PDF conversion
.WithHTML(html string) *HTMLConversionBuilder
.WithHTMLReader(reader io.Reader) *HTMLConversionBuilder
.WithCSS(css string) *HTMLConversionBuilder
.WithFile(filename string, reader io.Reader) *HTMLConversionBuilder
.Execute(ctx context.Context) (*http.Response, error)

// URLConversionBuilder - configures URL to PDF conversion
.WithURL(url string) *URLConversionBuilder
.Execute(ctx context.Context) (*http.Response, error)

// Common configuration methods available on both builders
.PaperSizeA4() / .PaperSizeLetter() / .PaperSizeA3() / etc.
.Margins(top, right, bottom, left float64)
.Landscape(enabled bool)
.PrintBackground(enabled bool)
.Scale(scale float64)
.OutputFilename(filename string)
.WebhookSuccess(url, method string)
.WebhookError(url, method string)
.WebhookExtraHeader(name, value string)

📖 Complete Builder Pattern Guide - Detailed examples and advanced usage

Traditional Client Methods
ConvertURLToPDF

Converts a web page to PDF.

func (c *Client) ConvertURLToPDF(ctx context.Context, url string, opts ...ClientOptions) (*http.Response, error)
ConvertHTMLToPDF

Converts HTML content with optional assets to PDF.

func (c *Client) ConvertHTMLToPDF(ctx context.Context, indexHTML io.Reader, opts ...ClientOptions) (*http.Response, error)
Configuration Options
Builder Pattern
options := gotenberg.NewOptionsBuilder().
    PaperSizeA4().                           // Set paper size
    Margins(1.0, 1.0, 1.0, 1.0).           // top, right, bottom, left (inches)
    PrintBackground(true).                   // Include CSS backgrounds
    Landscape(false).                        // Portrait orientation
    Scale(0.8).                             // Scale factor (0.1-2.0)
    SinglePage(false).                       // Generate single page
    OutputFilename("document.pdf").          // Custom filename
    File("style.css", cssReader).           // Add CSS file
    WebhookSuccess("https://...", "POST").   // Success webhook
    WebhookError("https://...", "POST").     // Error webhook
    WebhookExtraHeader("Auth", "Bearer ..."). // Custom headers
    Build()
Paper Sizes

Pre-defined paper sizes available:

  • PaperSizeA4(), PaperSizeA3(), PaperSizeA5(), etc.
  • PaperSizeLetter(), PaperSizeLegal(), PaperSizeTabloid()
  • PaperSize(width, height) for custom sizes
Webhook Configuration

For async processing:

options := gotenberg.NewOptionsBuilder().
    WebhookSuccess("https://your-api.com/webhook/success", "POST").
    WebhookError("https://your-api.com/webhook/error", "POST").
    WebhookExtraHeader("Authorization", "Bearer your-token").
    WebhookExtraHeader("X-Request-ID", "unique-id").
    Build()

Examples

See the examples directory for complete working examples:

Builder Pattern Examples:

Traditional API Examples:

Running Examples
# Start Gotenberg server
docker run --rm -p 3000:3000 gotenberg/gotenberg:8

# Run builder pattern examples
cd example/cmd/advanced_builder_demo && go run .
cd ../builder_demo && go run .

# Run traditional examples
cd ../html2pdf && go run .

Performance

The client is optimized for performance:

  • Buffer pooling reduces memory allocations
  • Streaming responses handle large PDFs efficiently
  • Context support enables proper timeout handling
  • 5-15KB/op memory usage (varies by complexity)
  • 48-192 allocs/op for complete request lifecycle

Benchmark results on modern hardware:

BenchmarkConvertURLToPDF-12      291750    3810 ns/op    5539 B/op    48 allocs/op
BenchmarkConvertHTMLToPDF-12     229570    4679 ns/op    8071 B/op    55 allocs/op
BenchmarkOptionsBuilder-12        91573   11741 ns/op   14810 B/op   192 allocs/op

Error Handling

resp, err := client.ConvertHTMLToPDF(ctx, htmlReader, options)
if err != nil {
    return fmt.Errorf("conversion failed: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
    body, _ := io.ReadAll(resp.Body)
    return fmt.Errorf("gotenberg error %d: %s", resp.StatusCode, body)
}

file, err := os.Create("output.pdf")
if err != nil {
    return err
}
defer file.Close()

_, err = io.Copy(file, resp.Body)
return err

Best Practices

  • Always close resp.Body to prevent resource leaks
  • Use context.Context for timeouts and cancellations
  • Check response status codes before processing
  • Use builder pattern for clean, readable configurations
  • Inspect response headers (e.g., Gotenberg-Trace) for debugging
  • Handle large files with streaming instead of loading into memory
  • Set appropriate HTTP client timeouts for your use case

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	FieldSinglePage              = "singlePage"
	FieldPaperWidth              = "paperWidth"
	FieldPaperHeight             = "paperHeight"
	FieldMarginTop               = "marginTop"
	FieldMarginBottom            = "marginBottom"
	FieldMarginLeft              = "marginLeft"
	FieldMarginRight             = "marginRight"
	FieldPreferCSSPageSize       = "preferCssPageSize"
	FieldGenerateDocumentOutline = "generateDocumentOutline"
	FieldGenerateTaggedPDF       = "generateTaggedPdf"
	FieldPrintBackground         = "printBackground"
	FieldOmitBackground          = "omitBackground"
	FieldLandscape               = "landscape"
	FieldScale                   = "scale"
	FieldNativePageRanges        = "nativePageRanges"
)
View Source
const (
	HeaderWebhookURL              = "Gotenberg-Webhook-Url"
	HeaderWebhookErrorURL         = "Gotenberg-Webhook-Error-Url"
	HeaderWebhookMethod           = "Gotenberg-Webhook-Method"
	HeaderWebhookErrorMethod      = "Gotenberg-Webhook-Error-Method"
	HeaderWebhookExtraHTTPHeaders = "Gotenberg-Webhook-Extra-Http-Headers"
)

Variables

View Source
var (
	PaperSizeLetter  = [2]float64{8.5, 11}
	PaperSizeLegal   = [2]float64{8.5, 14}
	PaperSizeTabloid = [2]float64{11, 17}
	PaperSizeLedger  = [2]float64{17, 11}
	PaperSizeA0      = [2]float64{33.1, 46.8}
	PaperSizeA1      = [2]float64{23.4, 33.1}
	PaperSizeA2      = [2]float64{16.54, 23.4}
	PaperSizeA3      = [2]float64{11.7, 16.54}
	PaperSizeA4      = [2]float64{8.27, 11.7}
	PaperSizeA5      = [2]float64{5.83, 8.27}
	PaperSizeA6      = [2]float64{4.13, 5.83}
)

Functions

This section is empty.

Types

type Client

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

func NewClient

func NewClient(httpClient *http.Client, baseURL string) *Client

func (*Client) ConvertHTMLToPDF

func (c *Client) ConvertHTMLToPDF(ctx context.Context, indexHTML io.Reader, opts ...ClientOptions) (*http.Response, error)

func (*Client) ConvertURLToPDF

func (c *Client) ConvertURLToPDF(ctx context.Context, url string, opts ...ClientOptions) (*http.Response, error)

type ClientBuilder added in v0.3.0

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

func NewClientBuilder added in v0.3.0

func NewClientBuilder(client *http.Client, baseURL string) *ClientBuilder

func (*ClientBuilder) Build added in v0.3.0

func (cb *ClientBuilder) Build() *Client

func (*ClientBuilder) ConvertHTML added in v0.3.0

func (cb *ClientBuilder) ConvertHTML() *HTMLConversionBuilder

func (*ClientBuilder) ConvertURL added in v0.3.0

func (cb *ClientBuilder) ConvertURL() *URLConversionBuilder

type ClientOptions added in v0.1.1

type ClientOptions func(*clientOptions)

type HTMLConversionBuilder added in v0.3.0

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

func (*HTMLConversionBuilder) Execute added in v0.3.0

func (hcb *HTMLConversionBuilder) Execute(ctx context.Context, html io.Reader) (*http.Response, error)

func (*HTMLConversionBuilder) GenerateDocumentOutline added in v0.3.0

func (hcb *HTMLConversionBuilder) GenerateDocumentOutline(enabled bool) *HTMLConversionBuilder

func (*HTMLConversionBuilder) GenerateTaggedPDF added in v0.3.0

func (hcb *HTMLConversionBuilder) GenerateTaggedPDF(enabled bool) *HTMLConversionBuilder

func (*HTMLConversionBuilder) Landscape added in v0.3.0

func (hcb *HTMLConversionBuilder) Landscape(enabled bool) *HTMLConversionBuilder

func (*HTMLConversionBuilder) Margins added in v0.3.0

func (hcb *HTMLConversionBuilder) Margins(top, right, bottom, left float64) *HTMLConversionBuilder

func (*HTMLConversionBuilder) OmitBackground added in v0.3.0

func (hcb *HTMLConversionBuilder) OmitBackground(enabled bool) *HTMLConversionBuilder

func (*HTMLConversionBuilder) OutputFilename added in v0.3.0

func (hcb *HTMLConversionBuilder) OutputFilename(filename string) *HTMLConversionBuilder

func (*HTMLConversionBuilder) PageRanges added in v0.3.0

func (hcb *HTMLConversionBuilder) PageRanges(ranges string) *HTMLConversionBuilder

func (*HTMLConversionBuilder) PaperSize added in v0.3.0

func (hcb *HTMLConversionBuilder) PaperSize(width, height float64) *HTMLConversionBuilder

func (*HTMLConversionBuilder) PaperSizeA3 added in v0.3.0

func (hcb *HTMLConversionBuilder) PaperSizeA3() *HTMLConversionBuilder

func (*HTMLConversionBuilder) PaperSizeA4 added in v0.3.0

func (hcb *HTMLConversionBuilder) PaperSizeA4() *HTMLConversionBuilder

func (*HTMLConversionBuilder) PaperSizeA5 added in v0.3.0

func (hcb *HTMLConversionBuilder) PaperSizeA5() *HTMLConversionBuilder

func (*HTMLConversionBuilder) PaperSizeLegal added in v0.3.0

func (hcb *HTMLConversionBuilder) PaperSizeLegal() *HTMLConversionBuilder

func (*HTMLConversionBuilder) PaperSizeLetter added in v0.3.0

func (hcb *HTMLConversionBuilder) PaperSizeLetter() *HTMLConversionBuilder

func (*HTMLConversionBuilder) PaperSizeTabloid added in v0.3.0

func (hcb *HTMLConversionBuilder) PaperSizeTabloid() *HTMLConversionBuilder

func (*HTMLConversionBuilder) PreferCSSPageSize added in v0.3.0

func (hcb *HTMLConversionBuilder) PreferCSSPageSize(enabled bool) *HTMLConversionBuilder

func (*HTMLConversionBuilder) PrintBackground added in v0.3.0

func (hcb *HTMLConversionBuilder) PrintBackground(enabled bool) *HTMLConversionBuilder

func (*HTMLConversionBuilder) Scale added in v0.3.0

func (*HTMLConversionBuilder) SinglePage added in v0.3.0

func (hcb *HTMLConversionBuilder) SinglePage(enabled bool) *HTMLConversionBuilder

func (*HTMLConversionBuilder) WebhookError added in v0.3.0

func (hcb *HTMLConversionBuilder) WebhookError(errorURL, errorMethod string) *HTMLConversionBuilder

func (*HTMLConversionBuilder) WebhookExtraHeader added in v0.3.0

func (hcb *HTMLConversionBuilder) WebhookExtraHeader(name, value string) *HTMLConversionBuilder

func (*HTMLConversionBuilder) WebhookSuccess added in v0.3.0

func (hcb *HTMLConversionBuilder) WebhookSuccess(url, method string) *HTMLConversionBuilder

func (*HTMLConversionBuilder) WithFile added in v0.3.0

func (hcb *HTMLConversionBuilder) WithFile(filename string, reader io.Reader) *HTMLConversionBuilder

type URLConversionBuilder added in v0.3.0

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

func (*URLConversionBuilder) Execute added in v0.3.0

func (ucb *URLConversionBuilder) Execute(ctx context.Context, url string) (*http.Response, error)

func (*URLConversionBuilder) GenerateDocumentOutline added in v0.3.0

func (ucb *URLConversionBuilder) GenerateDocumentOutline(enabled bool) *URLConversionBuilder

func (*URLConversionBuilder) GenerateTaggedPDF added in v0.3.0

func (ucb *URLConversionBuilder) GenerateTaggedPDF(enabled bool) *URLConversionBuilder

func (*URLConversionBuilder) Landscape added in v0.3.0

func (ucb *URLConversionBuilder) Landscape(enabled bool) *URLConversionBuilder

func (*URLConversionBuilder) Margins added in v0.3.0

func (ucb *URLConversionBuilder) Margins(top, right, bottom, left float64) *URLConversionBuilder

func (*URLConversionBuilder) OmitBackground added in v0.3.0

func (ucb *URLConversionBuilder) OmitBackground(enabled bool) *URLConversionBuilder

func (*URLConversionBuilder) OutputFilename added in v0.3.0

func (ucb *URLConversionBuilder) OutputFilename(filename string) *URLConversionBuilder

func (*URLConversionBuilder) PageRanges added in v0.3.0

func (ucb *URLConversionBuilder) PageRanges(ranges string) *URLConversionBuilder

func (*URLConversionBuilder) PaperSize added in v0.3.0

func (ucb *URLConversionBuilder) PaperSize(width, height float64) *URLConversionBuilder

func (*URLConversionBuilder) PaperSizeA3 added in v0.3.0

func (ucb *URLConversionBuilder) PaperSizeA3() *URLConversionBuilder

func (*URLConversionBuilder) PaperSizeA4 added in v0.3.0

func (ucb *URLConversionBuilder) PaperSizeA4() *URLConversionBuilder

func (*URLConversionBuilder) PaperSizeA5 added in v0.3.0

func (ucb *URLConversionBuilder) PaperSizeA5() *URLConversionBuilder

func (*URLConversionBuilder) PaperSizeLegal added in v0.3.0

func (ucb *URLConversionBuilder) PaperSizeLegal() *URLConversionBuilder

func (*URLConversionBuilder) PaperSizeLetter added in v0.3.0

func (ucb *URLConversionBuilder) PaperSizeLetter() *URLConversionBuilder

func (*URLConversionBuilder) PaperSizeTabloid added in v0.3.0

func (ucb *URLConversionBuilder) PaperSizeTabloid() *URLConversionBuilder

func (*URLConversionBuilder) PreferCSSPageSize added in v0.3.0

func (ucb *URLConversionBuilder) PreferCSSPageSize(enabled bool) *URLConversionBuilder

func (*URLConversionBuilder) PrintBackground added in v0.3.0

func (ucb *URLConversionBuilder) PrintBackground(enabled bool) *URLConversionBuilder

func (*URLConversionBuilder) Scale added in v0.3.0

func (*URLConversionBuilder) SinglePage added in v0.3.0

func (ucb *URLConversionBuilder) SinglePage(enabled bool) *URLConversionBuilder

func (*URLConversionBuilder) WebhookError added in v0.3.0

func (ucb *URLConversionBuilder) WebhookError(errorURL, errorMethod string) *URLConversionBuilder

func (*URLConversionBuilder) WebhookExtraHeader added in v0.3.0

func (ucb *URLConversionBuilder) WebhookExtraHeader(name, value string) *URLConversionBuilder

func (*URLConversionBuilder) WebhookSuccess added in v0.3.0

func (ucb *URLConversionBuilder) WebhookSuccess(url, method string) *URLConversionBuilder

Directories

Path Synopsis
example
cmd/html2pdf command
cmd/url2pdf command

Jump to

Keyboard shortcuts

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