htmlpdf

package module
v0.0.0-...-2a131dc Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 7 Imported by: 0

README

htmlpdf

htmlpdf is a Go package for converting HTML into PDF.

It ships with two rendering backends:

  • BackendChrome uses headless Chrome or Chromium for high-fidelity HTML/CSS output.
  • BackendNative uses a pure-Go renderer for document-style HTML without external binaries.

By default, BackendAuto tries Chrome first and falls back to the native renderer when no supported browser is available or Chrome cannot render successfully in the current environment.

Status

This project is pre-v1.0.0. The exported API is usable, but minor option and renderer behavior changes may still happen while the package settles into open-source development.

Install

go get github.com/HeartBeat1608/htmlpdf

Quick Start

package main

import (
	"context"
	"log"
	"time"

	"github.com/HeartBeat1608/htmlpdf"
)

func main() {
	html := []byte(`<html><body><h1>Hello</h1><p>PDF output</p></body></html>`)

	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	pdf, err := htmlpdf.GenerateContext(ctx, html, htmlpdf.Options{
		Backend: htmlpdf.BackendAuto,
		Title:   "Example",
	})
	if err != nil {
		log.Fatal(err)
	}

	_ = pdf
}

Example Application

If you want something runnable right away, there is a small starter app in examples/basic.

Run it with:

go run ./examples/basic

That generates example.pdf in your current directory.

You can also choose a backend and output path:

go run ./examples/basic -backend=native -out=invoice.pdf -title="My First PDF"

Backend Notes

Chrome backend
  • Best output fidelity.
  • Requires a Chrome or Chromium binary on the host.
  • Does not add --no-sandbox by default. If your container or CI environment requires it, set Options.ChromeDisableSandbox = true.
Native backend
  • No external process required.
  • Designed for reports, invoices, and other document-style HTML.
  • Supports a focused subset of HTML and inline CSS.

Supported block elements:

  • div, section, article, main, header, footer, p
  • h1 to h6
  • ul, ol, li
  • blockquote, pre, hr
  • table, thead, tbody, tr, td, th
  • figure

Supported inline elements:

  • span, strong, b, em, i, code, a, br
  • img as inline/block fallback content using alt text

Supported inline CSS properties:

  • font-size
  • font-weight
  • font-style
  • font-family
  • color
  • text-align
  • background-color

Unsupported properties are ignored.

Development

go test ./...
go vet ./...

Chrome integration tests are opt-in and run only when HTMLPDF_CHROME_BIN points to a local Chrome or Chromium executable.

Documentation

Overview

Package htmlpdf converts HTML to PDF.

Quick start

pdf, err := htmlpdf.Generate(htmlBytes, htmlpdf.Options{})

Backend selection

Two backends are available:

  • BackendNative — pure Go, no external process, ships with this module. Handles a well-defined subset of HTML/CSS suitable for documents, reports, and data exports.

  • BackendChrome — headless Chrome/Chromium via os/exec. Full HTML5/CSS3 fidelity. Requires a browser binary on the host.

With BackendAuto (the default), Chrome is tried first and Native is used as the fallback when Chrome is unavailable or cannot render successfully. This gives you the best output when Chrome is usable and a safe fallback everywhere else.

Supported HTML (native backend)

Block elements: div, section, article, main, header, footer, p, h1–h6, ul, ol, li, blockquote, pre, hr, table, thead, tbody, tr, td, th, figure.

Inline elements: span, strong, b, em, i, code, a, br, img (alt text only).

CSS (inline style= only): font-size, font-weight, font-style, font-family, color, text-align, background-color. All other properties are silently ignored.

Until v1.0.0, exported APIs may still evolve as the package settles into open-source development.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNoBrowser = errors.New("htmlpdf: no supported browser found (install chromium or google-chrome)")

ErrNoBrowser is returned by the Chrome backend when no supported browser binary can be located on the system PATH or at Options.ChromePath.

Functions

func Generate

func Generate(html []byte, opts Options) ([]byte, error)

Generate converts html to a PDF and returns the raw bytes.

opts may be a zero value; all fields have documented defaults. Pass a context to enforce a timeout, especially with BackendChrome.

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pdf, err := htmlpdf.GenerateContext(ctx, html, opts)
Example
package main

import (
	"fmt"

	"github.com/HeartBeat1608/htmlpdf"
)

func main() {
	html := []byte(`<html><body><h1>Hello</h1><p>Example PDF</p></body></html>`)

	pdf, err := htmlpdf.Generate(html, htmlpdf.Options{
		Backend: htmlpdf.BackendNative,
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(len(pdf) > 0)
}
Output:
true

func GenerateContext

func GenerateContext(ctx context.Context, html []byte, opts Options) ([]byte, error)

GenerateContext is like Generate but accepts a context for cancellation and timeout. The context is forwarded to the Chrome process when that backend is active; the native backend does not block on I/O so context cancellation has no effect mid-render (but the call returns quickly regardless).

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/HeartBeat1608/htmlpdf"
)

func main() {
	html := []byte(`<html><body><p>Rendered with context</p></body></html>`)

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	pdf, err := htmlpdf.GenerateContext(ctx, html, htmlpdf.Options{
		Backend: htmlpdf.BackendNative,
		Title:   "Example",
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println(len(pdf) > 0)
}
Output:
true

Types

type Backend

type Backend int

Backend selects which rendering engine to use.

const (
	// BackendAuto tries Chrome first, falls back to Native when Chrome is not
	// available or cannot render in the current environment.
	BackendAuto Backend = iota
	// BackendChrome requires headless Chrome/Chromium. Returns ErrNoBrowser if absent.
	BackendChrome
	// BackendNative uses the pure-Go renderer. No external process required.
	BackendNative
)

type Options

type Options struct {
	// Backend selects the rendering engine. Default: BackendAuto.
	Backend Backend

	// ChromePath overrides the browser binary used by BackendChrome.
	// When empty, the engine searches the system PATH.
	ChromePath string

	// ChromeDisableSandbox adds Chrome's --no-sandbox flag.
	//
	// Leave this false unless you are running in a restricted container or CI
	// environment where the browser sandbox cannot start normally.
	ChromeDisableSandbox bool

	// PageSize sets the paper size. Default: PageA4.
	PageSize PageSize

	// Orientation sets portrait or landscape. Default: Portrait.
	Orientation Orientation

	// MarginTopPt, MarginRightPt, MarginBottomPt, MarginLeftPt set page
	// margins in points (1 pt = 1/72 inch). Zero values use the default
	// 72 pt (1 inch) margins.
	MarginTopPt    float64
	MarginRightPt  float64
	MarginBottomPt float64
	MarginLeftPt   float64

	// Title sets the PDF document title metadata. When empty, the parser
	// uses the HTML <title> element if present.
	Title string
}

Options controls PDF generation behaviour.

type Orientation

type Orientation int

Orientation controls portrait vs landscape layout.

const (
	Portrait  Orientation = iota
	Landscape             // swaps width and height
)

type PageSize

type PageSize int

PageSize is a named paper size.

const (
	PageA4     PageSize = iota // 595.28 × 841.89 pt
	PageLetter                 // 612 × 792 pt
)

Directories

Path Synopsis
examples
basic command
internal
document
Package document defines the intermediate box tree produced by the HTML parser and consumed by the layout engine.
Package document defines the intermediate box tree produced by the HTML parser and consumed by the layout engine.
native/fonts
Package fonts provides character-width metrics for the standard PDF Type1 fonts.
Package fonts provides character-width metrics for the standard PDF Type1 fonts.
native/layout
Package layout converts a document.Document into a rendered PDF.
Package layout converts a document.Document into a rendered PDF.
native/parse
Package parse converts an HTML document into a document.Document box tree.
Package parse converts an HTML document into a document.Document box tree.

Jump to

Keyboard shortcuts

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