pdf

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 37 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Generate PDFs in Laravel Go applications

Latest version Tests Go Reference

Create PDFs from HTML and Laravel Go views. Choose Browsershot, Chrome, Gotenberg, Cloudflare, WeasyPrint or DOMPDF, then save the result, return it from a handler or attach it to mail.

Support us

Support Spatie's open source work

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

Requires Go 1.27 or newer and Laravel Go go.laravel.com v0.1.0.

go get github.com/spatie/laravel-pdf-go@v0.1.0

Install the package explicitly in bootstrap/app.go:

import (
    "github.com/spatie/laravel-pdf-go"
    laravel "go.laravel.com"
)

func Options() laravel.Options {
    return laravel.Options{
        Packages: []laravel.Package{ pdf.New() },
    }
}

The default Browsershot driver uses browsershot-go, Node.js, Puppeteer and Chrome. The separate Chrome driver needs only Chrome. See the requirements for your driver. DOMPDF still needs PHP and Composer's dompdf/dompdf.

Usage

func DownloadInvoice(r *web.Request) *web.Response {
    return pdf.From(r).
        View("pdf/invoice", map[string]any{"Number": 42}).
        Format(pdf.A4).
        Download("invoice.pdf").
        Response(r)
}

Import go.laravel.com/web for the handler. From a job or listener, pass its context.Context instead of r. For HTML, use pdf.From(ctx).HTML("<h1>Invoice</h1>").Save(ctx, "invoice.pdf").

Drivers, defaults, cache, encrypter and the queued job type are replaceable through pdf.New(func(cfg *pdf.Config) { ... }). Callbacks run after environment defaults. Builders are mutable and belong to one document. Factories belong to one application.

See the documentation or browse it in this repository. PHP-specific APIs use ordinary Go functions, typed queue jobs and explicit storage configuration. The queued generation and Lambda pages explain those differences.

Testing

go test -race ./...

Tests use an application-scoped FakeDriver, real Laravel host routes, storage and serialized queue jobs. Set PDF_TEST_CHROME, PDF_TEST_WEASYPRINT or PDF_TEST_DOMPDF_AUTOLOAD to run the external engine tests. Set PDF_TEST_NODE_MODULES to the absolute node_modules directory containing Puppeteer to also test Browsershot. Browser tests require Poppler's pdfinfo and pdftotext. CI runs the real engines on Linux as well as the unit suite on Linux, macOS and Windows.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details. Coding agents should read AGENTS.md and load the relevant skills in .agents/skills/.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

Documentation

Overview

Package pdf creates PDFs from HTML and Laravel Go views.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalid     = errors.New("pdf: invalid input")
	ErrUnsupported = errors.New("pdf: unsupported option")
)

Functions

func BlankPDF

func BlankPDF() []byte

BlankPDF is a valid blank A4 document for custom fakes.

func InlinedImage

func InlinedImage(ctx context.Context, path string, client *http.Client) (template.HTML, error)

InlinedImage reads trusted paths or URLs. Never pass untrusted visitor input.

func PageBreak

func PageBreak() template.HTML

func PageNumber

func PageNumber() template.HTML

func TotalPages

func TotalPages() template.HTML

Types

type BrowsershotDriver

type BrowsershotDriver struct {
	NodeBinary         string
	NpmBinary          string
	ChromePath         string
	NodeModulesPath    string
	IncludePath        string
	BinPath            string
	TempPath           string
	WriteOptionsToFile bool
	NoSandbox          bool
	Timeout            time.Duration
	ConfigurationKey   string
	Customize          func(*browsershot.Browsershot) `json:"-"`
}

BrowsershotDriver uses the released Node/Puppeteer backend.

func (BrowsershotDriver) Generate

func (d BrowsershotDriver) Generate(ctx context.Context, r Request) ([]byte, error)

func (BrowsershotDriver) Identity

func (d BrowsershotDriver) Identity() string

func (BrowsershotDriver) SupportsReadiness

func (BrowsershotDriver) SupportsReadiness() bool

type Builder

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

Builder is mutable and must not be shared between goroutines.

func (*Builder) Apply

func (b *Builder) Apply(fn func(*Builder)) *Builder

Apply replaces dynamic macros with an ordinary reusable Go function.

func (*Builder) Attachment

func (b *Builder) Attachment(ctx context.Context) (mail.Attachment, error)

func (*Builder) Base64

func (b *Builder) Base64(ctx context.Context) (string, error)

func (*Builder) Bytes

func (b *Builder) Bytes(ctx context.Context) ([]byte, error)

Bytes renders, applies metadata and processors, then encrypts the PDF.

func (*Builder) Cache

func (b *Builder) Cache(ttl time.Duration, key ...string) *Builder

func (*Builder) Contains

func (b *Builder) Contains(ctx context.Context, text ...string) (bool, error)

func (*Builder) Disk

func (b *Builder) Disk(name string) *Builder

func (*Builder) DocumentOutline

func (b *Builder) DocumentOutline() *Builder

func (*Builder) DontCache

func (b *Builder) DontCache() *Builder

func (*Builder) Download

func (b *Builder) Download(name string) *Builder

func (*Builder) Driver

func (b *Builder) Driver(name string) *Builder

func (*Builder) Encrypt

func (b *Builder) Encrypt(settings Encryption) *Builder

func (*Builder) FooterHTML

func (b *Builder) FooterHTML(html string) *Builder

func (*Builder) FooterView

func (b *Builder) FooterView(name string, data any) *Builder

func (*Builder) Format

func (b *Builder) Format(format Format) *Builder

func (*Builder) HTML

func (b *Builder) HTML(html string) *Builder

func (*Builder) HeaderHTML

func (b *Builder) HeaderHTML(html string) *Builder

func (*Builder) HeaderView

func (b *Builder) HeaderView(name string, data any) *Builder

func (*Builder) Headers

func (b *Builder) Headers(headers http.Header) *Builder

func (*Builder) Inline

func (b *Builder) Inline(name string) *Builder

func (*Builder) Job

func (b *Builder) Job(ctx context.Context, path string) (any, error)

Job returns the configured replacement job for chains or explicit queue dispatch.

func (*Builder) Landscape

func (b *Builder) Landscape() *Builder

func (*Builder) Margins

func (b *Builder) Margins(top, right, bottom, left float64, unit Unit) *Builder

func (*Builder) Meta

func (b *Builder) Meta(m Metadata) *Builder

func (*Builder) Name

func (b *Builder) Name(name string) *Builder

func (*Builder) Orientation

func (b *Builder) Orientation(o Orientation) *Builder

func (*Builder) PageRanges

func (b *Builder) PageRanges(ranges string) *Builder

func (*Builder) PaperSize

func (b *Builder) PaperSize(width, height float64, unit Unit) *Builder

func (*Builder) Portrait

func (b *Builder) Portrait() *Builder

func (*Builder) PostProcess

func (b *Builder) PostProcess(p PostProcessor) *Builder

func (*Builder) RenderRequest

func (b *Builder) RenderRequest(ctx context.Context) (Request, error)

func (*Builder) Response

func (b *Builder) Response(ctx context.Context) *web.Response

func (*Builder) Save

func (b *Builder) Save(ctx context.Context, path string) error

func (*Builder) SaveQueued

func (b *Builder) SaveQueued(ctx context.Context, path string, dispatch ...*queue.PendingDispatch) (queue.JobID, error)

func (*Builder) Scale

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

func (*Builder) SetDriver

func (b *Builder) SetDriver(d Driver) *Builder

func (*Builder) Tagged

func (b *Builder) Tagged() *Builder

func (*Builder) View

func (b *Builder) View(name string, data any) *Builder

func (*Builder) WaitUntilReady

func (b *Builder) WaitUntilReady(expression string, timeout time.Duration) *Builder

func (*Builder) When

func (b *Builder) When(condition bool, fn func(*Builder)) *Builder

func (*Builder) WithBrowsershot

func (b *Builder) WithBrowsershot(fn func(*browsershot.Browsershot)) *Builder

type Cache

type Cache interface {
	Remember(context.Context, string, time.Duration, func(context.Context) ([]byte, error)) ([]byte, error)
}

type ChromeDriver

type ChromeDriver struct {
	Binary      string
	NoSandbox   bool
	Timeout     time.Duration
	UserDataDir string
	Flags       map[string]any
	Environment []string
}

ChromeDriver controls Chrome directly, without Node.js or PHP.

func (ChromeDriver) Generate

func (d ChromeDriver) Generate(ctx context.Context, r Request) ([]byte, error)

func (ChromeDriver) Identity

func (d ChromeDriver) Identity() string

func (ChromeDriver) SupportsReadiness

func (ChromeDriver) SupportsReadiness() bool

type CloudflareDriver

type CloudflareDriver struct {
	Token     string
	AccountID string
	// Endpoint overrides the API URL, for proxies and tests.
	Endpoint string
	Client   *http.Client
}

func (CloudflareDriver) Generate

func (d CloudflareDriver) Generate(ctx context.Context, r Request) ([]byte, error)

func (CloudflareDriver) Identity

func (d CloudflareDriver) Identity() string

type Config

type Config struct {
	Driver         string
	Drivers        map[string]Driver
	Defaults       func(*Builder)
	Cache          Cache
	AutomaticCache bool
	CacheTTL       time.Duration
	CachePrefix    string
	CacheStore     string
	Encrypter      Encrypter
	// JobFactory must return the same serializable job type for every input.
	JobFactory  func(GenerateJob) any
	Browsershot BrowsershotDriver
	Chrome      ChromeDriver
	Cloudflare  CloudflareDriver
	Gotenberg   GotenbergDriver
	WeasyPrint  WeasyPrintDriver
	DOMPDF      DOMPDFDriver
}

Config is applied after environment defaults, once per application.

type DOMPDFDriver

type DOMPDFDriver struct {
	PHP           string
	Autoload      string
	RemoteEnabled bool
	Chroot        string
	FontDir       string
	FontCache     string
	Timeout       time.Duration
}

DOMPDFDriver uses an application's Composer installation of dompdf/dompdf. There is no native Go DOMPDF engine. Other drivers do not need PHP.

func (DOMPDFDriver) Generate

func (d DOMPDFDriver) Generate(ctx context.Context, r Request) ([]byte, error)

func (DOMPDFDriver) Identity

func (d DOMPDFDriver) Identity() string

type DefaultEncrypter

type DefaultEncrypter struct{}

DefaultEncrypter uses PDF AES-256 revision 6, including object streams.

func (DefaultEncrypter) Decrypt

func (DefaultEncrypter) Decrypt(ctx context.Context, data []byte, password string) ([]byte, error)

func (DefaultEncrypter) Encrypt

func (DefaultEncrypter) Encrypt(ctx context.Context, data []byte, settings Encryption) ([]byte, error)

func (DefaultEncrypter) Identity

func (DefaultEncrypter) Identity() string

type Driver

type Driver interface {
	Generate(context.Context, Request) ([]byte, error)
	Identity() string
}

Driver renders trusted HTML. Identity must change when its settings change.

type DriverFunc

type DriverFunc struct {
	Name      string
	Render    func(context.Context, Request) ([]byte, error)
	Readiness bool
}

DriverFunc adapts a renderer for custom drivers and application tests.

func (DriverFunc) Generate

func (d DriverFunc) Generate(ctx context.Context, r Request) ([]byte, error)

func (DriverFunc) Identity

func (d DriverFunc) Identity() string

func (DriverFunc) SupportsReadiness

func (d DriverFunc) SupportsReadiness() bool

type Encrypter

type Encrypter interface {
	Encrypt(context.Context, []byte, Encryption) ([]byte, error)
	Decrypt(context.Context, []byte, string) ([]byte, error)
	Identity() string
}

type Encryption

type Encryption struct {
	UserPassword  string       `json:"user_password"`
	OwnerPassword string       `json:"owner_password"`
	Permissions   []Permission `json:"permissions,omitzero"`
}

Encryption grants all permissions when Permissions is nil, none when empty. Queue backends and caches must protect serialized passwords and PDF content.

type Factory

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

Factory is immutable after construction and safe for concurrent use when its adapters are.

func From

func From(ctx context.Context) *Factory

func NewFactory

func NewFactory(cfg Config) (*Factory, error)

NewFactory also works outside Laravel for HTML and local file output.

func (*Factory) Builder

func (f *Factory) Builder() *Builder

func (*Factory) Decrypt

func (f *Factory) Decrypt(ctx context.Context, data []byte, password string) ([]byte, error)

func (*Factory) HTML

func (f *Factory) HTML(html string) *Builder
Example
package main

import (
	"bytes"
	"context"
	"fmt"

	pdf "github.com/spatie/laravel-pdf-go"
)

func main() {
	f, _ := pdf.NewFactory(pdf.Config{Driver: "fake", Drivers: map[string]pdf.Driver{"fake": &pdf.FakeDriver{}}})
	data, _ := f.HTML("<h1>Hello world</h1>").Format(pdf.A4).Bytes(context.Background())
	fmt.Println(bytes.HasPrefix(data, []byte("%PDF-")))
}
Output:
true

func (*Factory) View

func (f *Factory) View(name string, data any) *Builder

type FakeDriver

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

FakeDriver records rendered HTML and returns a valid blank one-page PDF. Set Config.Drivers and Config.Driver explicitly to install it in one application.

func (*FakeDriver) Generate

func (f *FakeDriver) Generate(ctx context.Context, request Request) ([]byte, error)

func (*FakeDriver) Identity

func (*FakeDriver) Identity() string

func (*FakeDriver) Requests

func (f *FakeDriver) Requests() []Request

func (*FakeDriver) SupportsReadiness

func (*FakeDriver) SupportsReadiness() bool

type Format

type Format string
const (
	Letter  Format = "letter"
	Legal   Format = "legal"
	Tabloid Format = "tabloid"
	Ledger  Format = "ledger"
	A0      Format = "a0"
	A1      Format = "a1"
	A2      Format = "a2"
	A3      Format = "a3"
	A4      Format = "a4"
	A5      Format = "a5"
	A6      Format = "a6"
)

type GenerateJob

type GenerateJob struct {
	Request           Request     `json:"request"`
	Metadata          Metadata    `json:"metadata"`
	Encryption        *Encryption `json:"encryption,omitempty"`
	Path              string      `json:"path"`
	Disk              string      `json:"disk"`
	Driver            string      `json:"driver"`
	DriverIdentity    string      `json:"driver_identity"`
	EncrypterIdentity string      `json:"encrypter_identity"`
}

GenerateJob holds only serializable data. A worker uses its application's configuration.

func (GenerateJob) Handle

func (j GenerateJob) Handle(ctx context.Context) error

type GotenbergDriver

type GotenbergDriver struct {
	URL      string
	Username string
	Password string
	Client   *http.Client
}

func (GotenbergDriver) Generate

func (d GotenbergDriver) Generate(ctx context.Context, r Request) ([]byte, error)

func (GotenbergDriver) Identity

func (d GotenbergDriver) Identity() string

func (GotenbergDriver) SupportsReadiness

func (GotenbergDriver) SupportsReadiness() bool

type HTTPError

type HTTPError struct{ StatusCode int }

HTTPError intentionally omits provider bodies, which can contain HTML and credentials.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type LaravelCache

type LaravelCache struct{ Store string }

func (LaravelCache) Remember

func (c LaravelCache) Remember(ctx context.Context, key string, ttl time.Duration, generate func(context.Context) ([]byte, error)) ([]byte, error)

type Margins

type Margins struct {
	Top    float64 `json:"top"`
	Right  float64 `json:"right"`
	Bottom float64 `json:"bottom"`
	Left   float64 `json:"left"`
	Unit   Unit    `json:"unit"`
}

type Metadata

type Metadata struct {
	Title        string `json:"title"`
	Author       string `json:"author"`
	Subject      string `json:"subject"`
	Keywords     string `json:"keywords"`
	Creator      string `json:"creator"`
	CreationDate string `json:"creation_date"`
}

type Options

type Options struct {
	Format          Format        `json:"format"`
	PaperSize       *PaperSize    `json:"paper_size,omitempty"`
	Margins         *Margins      `json:"margins,omitempty"`
	Orientation     Orientation   `json:"orientation"`
	Scale           float64       `json:"scale"`
	PageRanges      string        `json:"page_ranges"`
	Tagged          bool          `json:"tagged"`
	DocumentOutline bool          `json:"document_outline"`
	WaitForReady    string        `json:"wait_for_ready"`
	ReadyTimeout    time.Duration `json:"-"`
}

Options is serializable rendering input. Zero values keep engine defaults.

func (Options) MarshalJSON

func (o Options) MarshalJSON() ([]byte, error)

MarshalJSON represents durations as nanoseconds in both JSON implementations.

func (*Options) UnmarshalJSON

func (o *Options) UnmarshalJSON(data []byte) error

func (Options) Validate

func (o Options) Validate() error

type Orientation

type Orientation string
const (
	Portrait  Orientation = "portrait"
	Landscape Orientation = "landscape"
)

type Package

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

func New

func New(configure ...func(*Config)) *Package

func (*Package) Register

func (p *Package) Register(app *laravel.Registrar) error

type PaperSize

type PaperSize struct {
	Width  float64 `json:"width"`
	Height float64 `json:"height"`
	Unit   Unit    `json:"unit"`
}

type Permission

type Permission string
const (
	Annotate            Permission = "annot-forms"
	Assemble            Permission = "assemble"
	Copy                Permission = "copy"
	Extract             Permission = "extract"
	FillForms           Permission = "fill-forms"
	Modify              Permission = "modify"
	Print               Permission = "print"
	PrintHighResolution Permission = "print-high"
)

type PostProcessor

type PostProcessor interface {
	Process(context.Context, []byte) ([]byte, error)
	Identity() string
}

type ReadinessDriver

type ReadinessDriver interface{ SupportsReadiness() bool }

ReadinessDriver marks renderers that evaluate Options.WaitForReady.

type Request

type Request struct {
	HTML       string  `json:"html"`
	HeaderHTML string  `json:"header_html"`
	FooterHTML string  `json:"footer_html"`
	Options    Options `json:"options"`
}

Request contains rendered HTML, ready for a driver or queue worker.

type Unit

type Unit string
const (
	Millimeter Unit = "mm"
	Centimeter Unit = "cm"
	Inch       Unit = "in"
	Pixel      Unit = "px"
	Point      Unit = "pt"
)

type WeasyPrintDriver

type WeasyPrintDriver struct {
	Binary    string
	Timeout   time.Duration
	Arguments []string
}

WeasyPrintDriver runs WeasyPrint directly. Arguments never pass through a shell.

func (WeasyPrintDriver) Generate

func (d WeasyPrintDriver) Generate(ctx context.Context, r Request) ([]byte, error)

func (WeasyPrintDriver) Identity

func (d WeasyPrintDriver) Identity() string

Jump to

Keyboard shortcuts

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