gotenberg

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 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"
    "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

Simple URL to PDF conversion
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

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:

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 ClientOptions added in v0.1.1

type ClientOptions func(*clientOptions)

type OptionsBuilder added in v0.2.0

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

OptionsBuilder provides a fluent interface for building client options. This reduces allocations when chaining multiple options and provides better readability compared to functional options.

Example usage:

options := gotenberg.NewOptionsBuilder().
	PaperSizeA4().
	Margins(1.0, 1.0, 1.0, 1.0).
	PrintBackground(true).
	OutputFilename("document.pdf").
	Build()

resp, err := client.ConvertHTMLToPDF(ctx, htmlReader, options)

func NewOptionsBuilder added in v0.2.0

func NewOptionsBuilder() *OptionsBuilder

func (*OptionsBuilder) Build added in v0.2.0

func (b *OptionsBuilder) Build() ClientOptions

func (*OptionsBuilder) File added in v0.2.0

func (b *OptionsBuilder) File(name string, r io.Reader) *OptionsBuilder

func (*OptionsBuilder) Landscape added in v0.2.0

func (b *OptionsBuilder) Landscape(enabled bool) *OptionsBuilder

func (*OptionsBuilder) Margins added in v0.2.0

func (b *OptionsBuilder) Margins(top, right, bottom, left float64) *OptionsBuilder

func (*OptionsBuilder) OutputFilename added in v0.2.0

func (b *OptionsBuilder) OutputFilename(filename string) *OptionsBuilder

func (*OptionsBuilder) PaperSize added in v0.2.0

func (b *OptionsBuilder) PaperSize(width, height float64) *OptionsBuilder

func (*OptionsBuilder) PaperSizeA4 added in v0.2.0

func (b *OptionsBuilder) PaperSizeA4() *OptionsBuilder

func (*OptionsBuilder) PaperSizeLetter added in v0.2.0

func (b *OptionsBuilder) PaperSizeLetter() *OptionsBuilder

func (*OptionsBuilder) PrintBackground added in v0.2.0

func (b *OptionsBuilder) PrintBackground(enabled bool) *OptionsBuilder

func (*OptionsBuilder) Scale added in v0.2.0

func (b *OptionsBuilder) Scale(scale float64) *OptionsBuilder

func (*OptionsBuilder) SinglePage added in v0.2.0

func (b *OptionsBuilder) SinglePage(enabled bool) *OptionsBuilder

func (*OptionsBuilder) WebhookError added in v0.2.0

func (b *OptionsBuilder) WebhookError(errorURL, errorMethod string) *OptionsBuilder

func (*OptionsBuilder) WebhookExtraHeader added in v0.2.0

func (b *OptionsBuilder) WebhookExtraHeader(name, value string) *OptionsBuilder

func (*OptionsBuilder) WebhookSuccess added in v0.2.0

func (b *OptionsBuilder) WebhookSuccess(url, method string) *OptionsBuilder

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