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 ¶
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 ¶
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 ¶
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 )
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. |