Help us shape the future of Go! Take the 2026 Go Developer Survey

html2pdf

package module
v0.0.0-...-369b943 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2025 License: MIT Imports: 15 Imported by: 0

README

html2pdf-go

A simple Go package for converting HTML content to PDF using the chromedp package under the hood. The package supports concurrent PDF generation through a worker pool system.

Features

  • Concurrent HTML to PDF conversion using Chrome/Chromium
  • Configurable worker pool size
  • Customizable PDF output settings (page size, margins, etc.)
  • Support for waiting for page load and animations
  • Automatic retry mechanism for failed conversions
  • Debug logging option
  • Resource cleanup with graceful shutdown

Installation

go get github.com/xarunoba/html2pdf-go

Ensure you have Chrome or Chromium installed on your system.

Usage

Basic Usage
package main

import (
    "context"
    "log"
    "os"

    "github.com/xarunoba/html2pdf-go"
)

func main() {
    // Create a new converter with default options
    converter, err := html2pdf.New()
    if err != nil {
        log.Fatal(err)
    }
    defer converter.Close()

    // HTML content to convert
    html := `
        <!DOCTYPE html>
        <html>
            <body>
                <h1>Hello, World!</h1>
            </body>
        </html>
    `

    // Convert HTML to PDF
    ctx := context.Background()
    pdf, err := converter.Convert(ctx, html)
    if err != nil {
        log.Fatal(err)
    }

    // Save the PDF
    if err := os.WriteFile("output.pdf", pdf, 0644); err != nil {
        log.Fatal(err)
    }
}

For more usage examples, please check the examples directory.

Configuration Options

Converter Options
Option Description Default
WithWorkers Number of concurrent Chrome tabs 1
WithTimeout Maximum time for conversion 60 seconds
WithRetryAttempts Number of retry attempts 3
WithRetryDelay Delay between retries 1 second
WithDebug Enable debug logging false
PDF Options
Option Description Default
WithPaperSize Page width and height (inches) 8.5 x 11
WithMargins Page margins (inches) 0.5 all sides
WithWaitForLoad Wait for page to load true
WithWaitForAnimations Animation completion wait time 500ms
WithWaitTimeout Maximum wait time 60s

Considerations

  • This package uses Chrome/Chromium for PDF generation, which provides excellent CSS support and rendering accuracy but may not be the fastest solution for high-volume processing.
  • Memory usage scales with the number of workers, as each worker maintains a Chrome tab.
  • Performance can vary based on system resources, document complexity, and whether the HTML contains external resources.
  • For production environments, consider running benchmarks to determine optimal worker pool size for your use case.

Requirements

  • Go 1.23 or later
  • Chrome or Chromium browser installed on the system

Documentation

Overview

Package html2pdf provides functionality to convert HTML content to PDF documents using Chrome/Chromium. It manages a pool of Chrome instances to handle concurrent conversions efficiently and safely.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrEmptyPDF   = errors.New("PDF generation produced empty output")
	ErrTimeout    = errors.New("conversion timeout exceeded")
	ErrInitialize = errors.New("failed to initialize converter")
	ErrConversion = errors.New("conversion failed")
	ErrCleanup    = errors.New("failed to cleanup resources")
	ErrShutdown   = errors.New("converter is shutting down")
)

Functions

This section is empty.

Types

type Converter

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

Converter manages a pool of Chrome instances for converting HTML to PDF. It handles concurrent conversions and cleanup of resources.

func New

func New(opts ...Option) (*Converter, error)

New creates a new Converter instance with the specified options. It initializes Chrome workers and sets up signal handling for graceful shutdown. Returns an error if initialization fails.

func (*Converter) Close

func (c *Converter) Close() error

Close shuts down the Converter and releases all associated resources. It ensures all Chrome instances are properly terminated. Should be called when the Converter is no longer needed.

func (*Converter) Convert

func (c *Converter) Convert(ctx context.Context, html string, opts ...PDFOption) ([]byte, error)

Convert transforms the provided HTML string into a PDF document. It uses a pooled Chrome instance and applies the specified PDF options. The context can be used to cancel the operation or set a deadline. Returns the PDF as a byte slice or an error if the conversion fails.

type Option

type Option func(*Converter)

Option represents a function that modifies Converter configuration.

func WithDebug

func WithDebug(debug bool) Option

WithDebug enables or disables debug logging. The debug flag must be a boolean value, otherwise it will be false.

func WithRetryAttempts

func WithRetryAttempts(n int) Option

WithRetryAttempts sets the number of retry attempts for failed conversions. The number must be positive, otherwise it will be ignored. If n <= 0, the default number of attempts (3) is used.

func WithRetryDelay

func WithRetryDelay(d time.Duration) Option

WithRetryDelay sets the delay between retry attempts in seconds. The duration must be positive, otherwise it will be ignored. If d <= 0, the default delay (1s) is used.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the maximum duration for a single conversion operation. The duration must be positive, otherwise it will be ignored. If d <= 0, the default timeout (60s) is used.

func WithWorkers

func WithWorkers(n int) Option

WithWorkers sets the number of concurrent Chrome workers. The number must be positive, otherwise it will be ignored. If n <= 0, the default number of workers (1) is used.

type PDFOption

type PDFOption func(*pdfConfig)

PDFOption represents a function that modifies PDF generation settings.

func WithMargins

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

WithMargins sets the PDF margins in inches. The top, right, bottom, and left values must be positive, otherwise they will be ignored. If any value is <= 0, the default margins (0.5x0.5) are used.

func WithPaperSize

func WithPaperSize(width, height float64) PDFOption

WithPaperSize sets the PDF paper size in inches. The width and height must be positive, otherwise they will be ignored. If width or height <= 0, the default size (8.5x11) is used.

func WithWaitForAnimations

func WithWaitForAnimations(d time.Duration) PDFOption

WithWaitForAnimations sets how long to wait for animations to complete in milliseconds. The duration must be positive, otherwise it will be ignored. If d <= 0, the default duration (500ms) is used.

func WithWaitForLoad

func WithWaitForLoad(wait bool) PDFOption

WithWaitForLoad sets whether to wait for the page to load before generating the PDF. The wait flag must be a boolean value, otherwise it will be false.

func WithWaitTimeout

func WithWaitTimeout(d time.Duration) PDFOption

WithWaitTimeout sets the maximum duration to wait for page load and animations in seconds. The duration must be positive, otherwise it will be ignored. If d <= 0, the default timeout (60s) is used.

Directories

Path Synopsis
examples
basic command
customoptions command
parallel command

Jump to

Keyboard shortcuts

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