gotenberg

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2025 License: Apache-2.0 Imports: 8 Imported by: 0

README

Gotenberg Go Client

A comprehensive Go client for Gotenberg API with functional options pattern for clean and flexible usage.

Features

  • Functional Options Pattern: Clean API without mandatory option structs
  • URL to PDF: Convert web pages to PDF
  • HTML to PDF: Convert HTML documents to PDF with additional assets
  • Markdown to PDF: Convert Markdown files to PDF
  • Webhook Support: Asynchronous processing with webhooks
  • Comprehensive Options: Support for all Gotenberg configuration options
  • Type Safety: Strongly typed options with pointer helpers
  • Easy Configuration: Predefined paper sizes and helper functions

Installation

go get your-module/pkg/gotenberg

Quick Start

Basic Usage
package main

import (
    "net/http"
    "time"
    "your-module/pkg/gotenberg"
)

func main() {
    // Create client
    client := gotenberg.NewClient(&http.Client{
        Timeout: 30 * time.Second,
    }, "http://localhost:3000")

    // Convert URL to PDF (minimal)
    resp, err := client.ConvertURLToPDF("https://example.com")
    if err != nil {
        panic(err)
    }
    
    // Save PDF
    os.WriteFile("example.pdf", resp.PDF, 0644)
}
URL to PDF with Options
resp, err := client.ConvertURLToPDF("https://example.com",
    gotenberg.WithPaperSize(8.5, 11),           // Letter size
    gotenberg.WithMargins(1, 1, 1, 1),          // 1 inch margins
    gotenberg.WithLandscape(false),             // Portrait
    gotenberg.WithPrintBackground(true),        // Include background
    gotenberg.WithOutputFilename("page.pdf"),   // Custom filename
)
HTML to PDF with Assets
indexHTML := []byte(`<html><body><h1>Hello World</h1></body></html>`)

resp, err := client.ConvertHTMLToPDF(indexHTML,
    gotenberg.A4HTML(),                         // Predefined A4 size
    gotenberg.WithHTMLMargins(0.5, 0.5, 0.5, 0.5),
    gotenberg.WithAdditionalFiles(map[string][]byte{
        "style.css": []byte("body { font-family: Arial; }"),
        "logo.png":  logoBytes,
    }),
    gotenberg.WithHeader([]byte("<html><body>Header</body></html>")),
    gotenberg.WithFooter([]byte("<html><body>Footer</body></html>")),
)
Markdown to PDF
indexHTML := []byte(`<html><body>{{ .markdown }}</body></html>`)
markdownFiles := map[string][]byte{
    "content.md": []byte("# Hello\n\nThis is **markdown**."),
}

resp, err := client.ConvertMarkdownToPDF(indexHTML, markdownFiles,
    gotenberg.WithMarkdownPaperSize(8.27, 11.7), // A4
    gotenberg.WithMarkdownLandscape(false),
    gotenberg.WithMarkdownOutputFilename("doc.pdf"),
)
Webhook (Async Processing)
resp, err := client.ConvertHTMLToPDF(htmlContent,
    gotenberg.WithHTMLWebhook(
        "https://your-app.com/webhook/success",
        "https://your-app.com/webhook/error",
    ),
    gotenberg.WithHTMLWebhookMethods("POST", "POST"),
    gotenberg.WithHTMLWebhookExtraHeaders(map[string]string{
        "Authorization": "Bearer your-token",
        "X-Request-ID":  "req-123",
    }),
)

// resp.PDF will be nil for webhook requests
// PDF will be sent to your webhook URL

API Reference

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

If httpClient is nil, http.DefaultClient is used.

Conversion Methods
URL to PDF
func (c *Client) ConvertURLToPDF(url string, opts ...URLToPDFOption) (*PDFResponse, error)
HTML to PDF
func (c *Client) ConvertHTMLToPDF(indexHTML []byte, opts ...HTMLToPDFOption) (*PDFResponse, error)
Markdown to PDF
func (c *Client) ConvertMarkdownToPDF(indexHTML []byte, markdownFiles map[string][]byte, opts ...MarkdownToPDFOption) (*PDFResponse, error)
Response Structure
type PDFResponse struct {
    PDF                []byte  // PDF content (nil for webhook responses)
    ContentType        string  // Response content type
    ContentLength      int64   // Content length
    ContentDisposition string  // Content disposition header
    Trace              string  // Gotenberg trace ID
}
Error Handling
type GotenbergError struct {
    StatusCode int    // HTTP status code
    Message    string // Error message from Gotenberg
    Trace      string // Gotenberg trace ID
}

Functional Options

URL to PDF Options
  • WithPaperSize(width, height float64) - Set custom paper size
  • WithMargins(top, right, bottom, left float64) - Set margins
  • WithSinglePage(bool) - Single page mode
  • WithLandscape(bool) - Landscape orientation
  • WithPrintBackground(bool) - Include background graphics
  • WithScale(float64) - Page scale factor
  • WithOutputFilename(string) - Custom output filename
  • WithWebhook(url, errorURL string) - Webhook configuration
  • WithWebhookMethods(method, errorMethod string) - Webhook HTTP methods
  • WithWebhookExtraHeaders(map[string]string) - Additional webhook headers
HTML to PDF Options

Same as URL options plus:

  • WithAdditionalFiles(map[string][]byte) - Additional assets (CSS, images, fonts)
  • WithHeader([]byte) - Header HTML content
  • WithFooter([]byte) - Footer HTML content

Use WithHTML* prefixed functions for HTML-specific options:

  • WithHTMLPaperSize(), WithHTMLMargins(), etc.
Markdown to PDF Options

Same as HTML options with WithMarkdown* prefixed functions:

  • WithMarkdownPaperSize(), WithMarkdownMargins(), etc.
Predefined Helpers
Paper Sizes
A4()            // A4 for URL conversion
A4HTML()        // A4 for HTML conversion  
A4Markdown()    // A4 for Markdown conversion
Letter()        // Letter for URL conversion
LetterHTML()    // Letter for HTML conversion
LetterMarkdown() // Letter for Markdown conversion
Paper Size Constants
PaperSizeA4      = [2]float64{8.27, 11.7}  // A4
PaperSizeLetter  = [2]float64{8.5, 11}     // Letter
PaperSizeLegal   = [2]float64{8.5, 14}     // Legal
// ... and more
Utility Functions
Bool(v bool) *bool           // Create bool pointer
String(v string) *string     // Create string pointer  
Float64(v float64) *float64  // Create float64 pointer
Int(v int) *int              // Create int pointer

Examples

Complete Example with Error Handling
package main

import (
    "fmt"
    "net/http"
    "os"
    "time"
    "your-module/pkg/gotenberg"
)

func main() {
    client := gotenberg.NewClient(&http.Client{
        Timeout: 60 * time.Second,
    }, "http://localhost:3000")

    html := []byte(`
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>Invoice</title>
            <link rel="stylesheet" href="style.css">
        </head>
        <body>
            <h1>Invoice #12345</h1>
            <p>Thank you for your business!</p>
        </body>
        </html>
    `)

    css := []byte(`
        body { 
            font-family: Arial, sans-serif; 
            margin: 40px;
        }
        h1 { 
            color: #333; 
            border-bottom: 2px solid #007cba;
        }
    `)

    resp, err := client.ConvertHTMLToPDF(html,
        gotenberg.A4HTML(),
        gotenberg.WithHTMLMargins(1, 1, 1, 1),
        gotenberg.WithHTMLPrintBackground(true),
        gotenberg.WithHTMLOutputFilename("invoice-12345.pdf"),
        gotenberg.WithAdditionalFiles(map[string][]byte{
            "style.css": css,
        }),
    )

    if err != nil {
        if gotErr, ok := err.(*gotenberg.GotenbergError); ok {
            fmt.Printf("Gotenberg error %d: %s (trace: %s)\n", 
                gotErr.StatusCode, gotErr.Message, gotErr.Trace)
        } else {
            fmt.Printf("Error: %v\n", err)
        }
        return
    }

    if err := os.WriteFile("invoice.pdf", resp.PDF, 0644); err != nil {
        fmt.Printf("Failed to save PDF: %v\n", err)
        return
    }

    fmt.Printf("PDF created successfully! Size: %d bytes, Trace: %s\n", 
        len(resp.PDF), resp.Trace)
}

Testing

Run the tests:

go test ./pkg/gotenberg/...

The package includes comprehensive tests covering all functionality with mock Gotenberg server responses.

Requirements

License

This project is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// Standard paper sizes (width x height in inches)
	PaperSizeLetter  = [2]float64{8.5, 11}     // Letter - 8.5 x 11 (default)
	PaperSizeLegal   = [2]float64{8.5, 14}     // Legal - 8.5 x 14
	PaperSizeTabloid = [2]float64{11, 17}      // Tabloid - 11 x 17
	PaperSizeLedger  = [2]float64{17, 11}      // Ledger - 17 x 11
	PaperSizeA0      = [2]float64{33.1, 46.8}  // A0 - 33.1 x 46.8
	PaperSizeA1      = [2]float64{23.4, 33.1}  // A1 - 23.4 x 33.1
	PaperSizeA2      = [2]float64{16.54, 23.4} // A2 - 16.54 x 23.4
	PaperSizeA3      = [2]float64{11.7, 16.54} // A3 - 11.7 x 16.54
	PaperSizeA4      = [2]float64{8.27, 11.7}  // A4 - 8.27 x 11.7
	PaperSizeA5      = [2]float64{5.83, 8.27}  // A5 - 5.83 x 8.27
	PaperSizeA6      = [2]float64{4.13, 5.83}  // A6 - 4.13 x 5.83
)

Predefined paper sizes for convenience

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to the bool value

func Float64

func Float64(v float64) *float64

Float64 returns a pointer to the float64 value

func Int

func Int(v int) *int

Int returns a pointer to the int value

func String

func String(v string) *string

String returns a pointer to the string value

Types

type Client

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

Client represents a client for working with Gotenberg API

func NewClient

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

NewClient creates a new Gotenberg client

func (*Client) ConvertHTMLToPDF

func (c *Client) ConvertHTMLToPDF(indexHTML []byte, opts ...HTMLToPDFOption) (*PDFResponse, error)

ConvertHTMLToPDF converts HTML to PDF

func (*Client) ConvertMarkdownToPDF

func (c *Client) ConvertMarkdownToPDF(indexHTML []byte, markdownFiles map[string][]byte, opts ...MarkdownToPDFOption) (*PDFResponse, error)

ConvertMarkdownToPDF converts Markdown to PDF

func (*Client) ConvertURLToPDF

func (c *Client) ConvertURLToPDF(url string, opts ...URLToPDFOption) (*PDFResponse, error)

ConvertURLToPDF converts URL to PDF

type GotenbergError

type GotenbergError struct {
	StatusCode int
	Message    string
	Trace      string
}

GotenbergError represents error from Gotenberg API

func (*GotenbergError) Error

func (e *GotenbergError) Error() string

type HTMLToPDFOption

type HTMLToPDFOption func(*htmlToPDFConfig)

HTMLToPDFOption represents a functional option for HTML to PDF conversion

func A4HTML

func A4HTML() HTMLToPDFOption

A4HTML returns A4 paper size option for HTML conversion

func LetterHTML

func LetterHTML() HTMLToPDFOption

LetterHTML returns Letter paper size option for HTML conversion

func WithAdditionalFiles

func WithAdditionalFiles(files map[string][]byte) HTMLToPDFOption

WithAdditionalFiles adds additional files for HTML conversion

func WithFooter

func WithFooter(footerHTML []byte) HTMLToPDFOption

WithFooter sets footer HTML for HTML conversion

func WithHTMLLandscape

func WithHTMLLandscape(enabled bool) HTMLToPDFOption

WithHTMLLandscape sets landscape orientation for HTML conversion

func WithHTMLMargins

func WithHTMLMargins(top, right, bottom, left float64) HTMLToPDFOption

WithHTMLMargins sets margins for HTML conversion

func WithHTMLOutputFilename

func WithHTMLOutputFilename(filename string) HTMLToPDFOption

WithHTMLOutputFilename sets output filename for HTML conversion

func WithHTMLPaperSize

func WithHTMLPaperSize(width, height float64) HTMLToPDFOption

WithHTMLPaperSize sets paper size for HTML conversion

func WithHTMLPrintBackground

func WithHTMLPrintBackground(enabled bool) HTMLToPDFOption

WithHTMLPrintBackground sets print background for HTML conversion

func WithHTMLScale

func WithHTMLScale(scale float64) HTMLToPDFOption

WithHTMLScale sets scale for HTML conversion

func WithHTMLSinglePage

func WithHTMLSinglePage(enabled bool) HTMLToPDFOption

WithHTMLSinglePage sets single page mode for HTML conversion

func WithHTMLWebhook

func WithHTMLWebhook(url, errorURL string) HTMLToPDFOption

WithHTMLWebhook sets webhook configuration for HTML conversion

func WithHTMLWebhookExtraHeaders

func WithHTMLWebhookExtraHeaders(headers map[string]string) HTMLToPDFOption

WithHTMLWebhookExtraHeaders sets extra headers for webhook in HTML conversion

func WithHTMLWebhookMethods

func WithHTMLWebhookMethods(method, errorMethod string) HTMLToPDFOption

WithHTMLWebhookMethods sets webhook HTTP methods for HTML conversion

func WithHeader

func WithHeader(headerHTML []byte) HTMLToPDFOption

WithHeader sets header HTML for HTML conversion

type MarkdownToPDFOption

type MarkdownToPDFOption func(*markdownToPDFConfig)

MarkdownToPDFOption represents a functional option for Markdown to PDF conversion

func A4Markdown

func A4Markdown() MarkdownToPDFOption

A4Markdown returns A4 paper size option for Markdown conversion

func LetterMarkdown

func LetterMarkdown() MarkdownToPDFOption

LetterMarkdown returns Letter paper size option for Markdown conversion

func WithMarkdownAdditionalFiles

func WithMarkdownAdditionalFiles(files map[string][]byte) MarkdownToPDFOption

WithMarkdownAdditionalFiles adds additional files for Markdown conversion

func WithMarkdownFooter

func WithMarkdownFooter(footerHTML []byte) MarkdownToPDFOption

WithMarkdownFooter sets footer HTML for Markdown conversion

func WithMarkdownHeader

func WithMarkdownHeader(headerHTML []byte) MarkdownToPDFOption

WithMarkdownHeader sets header HTML for Markdown conversion

func WithMarkdownLandscape

func WithMarkdownLandscape(enabled bool) MarkdownToPDFOption

WithMarkdownLandscape sets landscape orientation for Markdown conversion

func WithMarkdownMargins

func WithMarkdownMargins(top, right, bottom, left float64) MarkdownToPDFOption

WithMarkdownMargins sets margins for Markdown conversion

func WithMarkdownOutputFilename

func WithMarkdownOutputFilename(filename string) MarkdownToPDFOption

WithMarkdownOutputFilename sets output filename for Markdown conversion

func WithMarkdownPaperSize

func WithMarkdownPaperSize(width, height float64) MarkdownToPDFOption

WithMarkdownPaperSize sets paper size for Markdown conversion

func WithMarkdownPrintBackground

func WithMarkdownPrintBackground(enabled bool) MarkdownToPDFOption

WithMarkdownPrintBackground sets print background for Markdown conversion

func WithMarkdownScale

func WithMarkdownScale(scale float64) MarkdownToPDFOption

WithMarkdownScale sets scale for Markdown conversion

func WithMarkdownSinglePage

func WithMarkdownSinglePage(enabled bool) MarkdownToPDFOption

WithMarkdownSinglePage sets single page mode for Markdown conversion

func WithMarkdownWebhook

func WithMarkdownWebhook(url, errorURL string) MarkdownToPDFOption

WithMarkdownWebhook sets webhook configuration for Markdown conversion

func WithMarkdownWebhookExtraHeaders

func WithMarkdownWebhookExtraHeaders(headers map[string]string) MarkdownToPDFOption

WithMarkdownWebhookExtraHeaders sets extra headers for webhook in Markdown conversion

func WithMarkdownWebhookMethods

func WithMarkdownWebhookMethods(method, errorMethod string) MarkdownToPDFOption

WithMarkdownWebhookMethods sets webhook HTTP methods for Markdown conversion

type PDFResponse

type PDFResponse struct {
	PDF                []byte
	ContentType        string
	ContentLength      int64
	ContentDisposition string
	Trace              string
}

PDFResponse represents response from Gotenberg API

type URLToPDFOption

type URLToPDFOption func(*urlToPDFConfig)

URLToPDFOption represents a functional option for URL to PDF conversion

func A4

func A4() URLToPDFOption

A4 returns A4 paper size option for URL conversion

func Letter

func Letter() URLToPDFOption

Letter returns Letter paper size option for URL conversion

func WithLandscape

func WithLandscape(enabled bool) URLToPDFOption

WithLandscape sets landscape orientation

func WithMargins

func WithMargins(top, right, bottom, left float64) URLToPDFOption

WithMargins sets margins

func WithOutputFilename

func WithOutputFilename(filename string) URLToPDFOption

WithOutputFilename sets output filename

func WithPaperSize

func WithPaperSize(width, height float64) URLToPDFOption

WithPaperSize sets paper size

func WithPrintBackground

func WithPrintBackground(enabled bool) URLToPDFOption

WithPrintBackground sets print background

func WithScale

func WithScale(scale float64) URLToPDFOption

WithScale sets scale

func WithSinglePage

func WithSinglePage(enabled bool) URLToPDFOption

WithSinglePage sets single page mode

func WithWebhook

func WithWebhook(url, errorURL string) URLToPDFOption

WithWebhook sets webhook configuration

func WithWebhookExtraHeaders

func WithWebhookExtraHeaders(headers map[string]string) URLToPDFOption

WithWebhookExtraHeaders sets extra headers for webhook

func WithWebhookMethods

func WithWebhookMethods(method, errorMethod string) URLToPDFOption

WithWebhookMethods sets webhook HTTP methods

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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