wkhtmltopdf

package module
v0.0.0-...-0049d75 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2018 License: MIT Imports: 7 Imported by: 2

README

wkhtmltopdf-go

GoDoc Build Status Coverage Status Go Report Card

wkhtmltopdf-go is a go wrapper for wkhtmltopdf.

It is intended to simplify the production of pdf documents in go, using html/css templates as a source. Multiple input sources, specified by filename, url or an io.Reader, can be combined to form a single pdf and written to either a file or an io.Writer.

Installation

To get the go library:

go get -u github.com/andrewcharlton/wkhtmltopdf-go

wkhtmltopdf also needs to be installed. It is assumed that wkhtmltopdf can be found on your PATH. If this is not the case, you can set the Executable variable to wkhtmltopdf's location.

Example Usage

To create a simple pdf from a url:

import "github.com/andrewcharlton/wkhtmltopdf-go"

func GooglePDF() {

	doc := wkhtmltopdf.NewDocument()
	pg := wkhtmltopdf.NewPage("www.google.com")
	doc.AddPages(pg)

	doc.WriteToFile("google.pdf")
}

Options can be set when creating both documents and pages. To create a landscape document without images:

import "github.com/andrewcharlton/wkhtmltopdf-go"

func GooglePDF() {

	doc := wkhtmltopdf.NewDocument(wkhtmltopdf.Landscape())
	pg := wkhtmltopdf.NewPage("www.google.com", wkhtmltopdf.NoImages())
	doc.AddPages(pg)

	doc.WriteToFile("google.pdf")
}

See GoDoc for a full list of options.

Documents can also be created from io.Readers, and written to io.Writers to facilitate use in a server environment. If multiple readers are used, these will be written to temporary files. Each document creates its own temporary directory, so should be safe for concurrent use. If only a single reader is used, this will be piped to wkhtmltopdf.

package main

import (
    "bytes"
    "html/template"
    "log"
    "net/http"

    "github.com/andrewcharlton/wkhtmltopdf-go"
)

const page = `
<html>
  <body>
    <h1>Test Page</h1>

	<p>Path: {{.}}</p>
  </body>
</html>`

func handler(w http.ResponseWriter, r *http.Request) {

    tmpl := template.Must(template.New("page").Parse(page))
    buf := &bytes.Buffer{}
    tmpl.Execute(buf, r.URL.String())

    doc := wkhtmltopdf.NewDocument()
    pg, err := wkhtmltopdf.NewPageReader(buf)
    if err != nil {
        log.Fatal("Error reading page buffer")
    }
    doc.AddPages(pg)

    w.Header().Set("Content-Type", "application/pdf")
    w.Header().Set("Content-Disposition", `attachment; filename="test.pdf"`)
    err = doc.Write(w)
    if err != nil {
        log.Fatal("Error serving pdf")
    }
}

func main() {

    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)

}

Documentation

Overview

Package wkhtmltopdf implements a wrapper for the html to pdf converter wkhtmltopdf.

For more information on wkhtmltopdf see: http://wkhtmltopdf.org/

Creating Documents

Creating a pdf document is simple:

doc := wkhtmltopdf.NewDocument()
pg := wkhtmltopdf.NewPage("www.google.com")
doc.AddPages(pg)
doc.WriteToFile("google.pdf")

Pages can be sourced from both URLs and local filenames.

Applying Options

You can apply options to both the document and individual pages when creating them.

doc := wkhtmltopdf.NewDocument(wkhtmltopdf.Grayscale(), wkhtmltopdf.PageSize("A4"))
pg := wkhtmltopdf.NewPage("www.google.com", wkhtmltopdf.DefaultHeader())
doc.AddPages(pg)
doc.WriteToFile("google.pdf")

Using Readers and Writers

As well as URLs/filenames, you can source pages from an io.Reader, and write them to an io.Writer.

If a single reader is provided, this is piped to wkhtmltopdf through stdin. If multiple readers are provided, the contents are written to a temporary directory and used from there. The location of the temporary directories can be changed by setting the TempDir variable.

doc := wkhtmltopdf.NewDocument()

buf := bytes.NewBufferString("<html><body><h1>Test Page</h1></body></html>")
pg, err := wkhtmltopdf.NewPageReader(buf)
if err != nil {
	log.Fatal("Error reading from reader.")
}
doc.AddPages(pg)

output := &bytes.Buffer{}
err := doc.Write(output)
if err != nil {
	log.Fatal("Error writing to writer.")
}
Example
package main

/* This example creates an http server, which returns a simple
   pdf document with a title and the path of the request.
*/

import (
	"bytes"
	"html/template"
	"log"
	"net/http"

	"github.com/andrewcharlton/wkhtmltopdf-go"
)

const page = `
<html>
  <body>
    <h1>Test Page</h1>

	<p>Path: {{.}}</p>
  </body>
</html>`

func handler(w http.ResponseWriter, r *http.Request) {

	tmpl := template.Must(template.New("page").Parse(page))
	buf := &bytes.Buffer{}
	tmpl.Execute(buf, r.URL.String())

	doc := wkhtmltopdf.NewDocument()
	pg, err := wkhtmltopdf.NewPageReader(buf)
	if err != nil {
		log.Fatal("Error reading page buffer")
	}
	doc.AddPages(pg)

	w.Header().Set("Content-Type", "application/pdf")
	w.Header().Set("Content-Disposition", `attachment; filename="test.pdf"`)
	err = doc.Write(w)
	if err != nil {
		log.Fatal("Error serving pdf")
	}
}

func main() {

	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)

}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (

	// Executable is the command to run wkhtmltopdf. If wkhtmltopdf
	// cannot be found on your path, amend this to its location.
	Executable = "wkhtmltopdf"

	// TempDir is where the directories for creating temporary
	// files are created.
	TempDir = "."
)

Functions

This section is empty.

Types

type Document

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

A Document represents a single pdf document.

func NewDocument

func NewDocument(opts ...Option) *Document

NewDocument creates a new document.

func (*Document) AddCover

func (doc *Document) AddCover(cover *Page)

AddCover adds a cover page to the document.

func (*Document) AddOptions

func (doc *Document) AddOptions(opts ...Option)

AddOptions allows the setting of options after document creation.

func (*Document) AddPages

func (doc *Document) AddPages(pages ...*Page)

AddPages to the document. Pages will be included in the final pdf in the order they are added.

func (*Document) Write

func (doc *Document) Write(w io.Writer) error

Write creates the pdf document and writes it to the provided reader.

func (*Document) WriteToFile

func (doc *Document) WriteToFile(filename string) error

WriteToFile creates the pdf document and writes it to the specified filename.

type GlobalOption

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

A GlobalOption can be applied only to a document.

func CookieJar

func CookieJar(path string) GlobalOption

CookieJar - read and write cookies from and to the supplied cookie jar file.

func DPI

func DPI(dpi int) GlobalOption

DPI - change the dpi explicitly.

func DisableDottedLines

func DisableDottedLines() GlobalOption

DisableDottedLines - do not use dotted lines in the toc

func DisableTocLinks() GlobalOption

DisableTocLinks - do not link from toc to sections

func Grayscale

func Grayscale() GlobalOption

Grayscale - PDF will be generated in grayscale.

func ImageDPI

func ImageDPI(dpi int) GlobalOption

ImageDPI - When embedding images, scale them down to this dpi.

func ImageQuality

func ImageQuality(quality int) GlobalOption

ImageQuality - When jpeg compressing images, use this quality (default 94).

func Landscape

func Landscape() GlobalOption

Landscape - Set the page orientation to landscape.

func LowQuality

func LowQuality() GlobalOption

LowQuality - Generates lower quality pdf/ps. Useful to shrink the result document space.

func MarginBottom

func MarginBottom(units string) GlobalOption

MarginBottom - Set the page bottom margin.

func MarginLeft

func MarginLeft(units string) GlobalOption

MarginLeft - Set the page left margin.

func MarginRight

func MarginRight(units string) GlobalOption

MarginRight - Set the page right margin.

func MarginTop

func MarginTop(units string) GlobalOption

MarginTop - Set the page top margin.

func NoCollate

func NoCollate() GlobalOption

NoCollate - do not collate when printing multiple copies.

func NoOutline

func NoOutline() GlobalOption

NoOutline - do not put an outline into the pdf

func NoPDFCompression

func NoPDFCompression() GlobalOption

NoPDFCompression - Do not use lossless compression on pdf objects.

func Outline

func Outline() GlobalOption

Outline - put an outline into the pdf

func OutlineDepth

func OutlineDepth(level int) GlobalOption

OutlineDepth - set the depth of the outline

func PageHeight

func PageHeight(units string) GlobalOption

PageHeight - Set the page height.

func PageSize

func PageSize(size string) GlobalOption

PageSize - Set paper size to A4, letter etc.

func PageWidth

func PageWidth(units string) GlobalOption

PageWidth - Set the page width.

func Quiet

func Quiet() GlobalOption

Quiet - Be less verbose.

func Title

func Title(title string) GlobalOption

Title - the title of the generated pdf file (the title of the first document is used if not specified).

func TocHeaderText

func TocHeaderText(text string) GlobalOption

TocHeaderText - the header text of the toc

func TocLevelIndentation

func TocLevelIndentation(width string) GlobalOption

TocLevelIndentation - for each level of headings in the toc indent by this length

func TocTextSizeShrink

func TocTextSizeShrink(factor float64) GlobalOption

TocTextSizeShrink - for each level of headings in the toc the font is scaled by this factor

func XSLStyleSheet

func XSLStyleSheet(file string) GlobalOption

XSLStyleSheet - use the supplied xsl style sheet for printing the table of content

type Option

type Option interface {
	// contains filtered or unexported methods
}

An Option to be applied to a page or document.

type Page

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

A Page represents a single html document, which may span multiple pages in the finished pdf document. Options can be applied to the page.

func NewPage

func NewPage(filename string, opts ...PageOption) *Page

NewPage creates a new page from the given filename (which can be a url), with the given options.

func NewPageReader

func NewPageReader(r io.Reader, opts ...PageOption) (*Page, error)

NewPageReader creates a new page from an io.Reader. The reader will be drained on page creation, and stored in a temporary buffer.

func (*Page) AddOptions

func (pg *Page) AddOptions(opts ...PageOption)

AddOptions allows the setting of options after page creation.

type PageOption

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

A PageOption can be applied to pages and/or documents.

func Allow

func Allow(path string) PageOption

Allow the file or files from the specified folder to be loaded (repeatable)

func Background

func Background() PageOption

Background - print background (default)

func BypassProxy

func BypassProxy(host string) PageOption

BypassProxy - bypass proxy for host (repeatable)

func CacheDir

func CacheDir(path string) PageOption

CacheDir - web cache directory

func CheckboxCheckedSVG

func CheckboxCheckedSVG(path string) PageOption

CheckboxCheckedSVG - Use this svg file when rendering checked checkboxes

func CheckboxSVG

func CheckboxSVG(path string) PageOption

CheckboxSVG - Use this svg file when rendering unchecked checkboxes

func Cookie(name, value string) PageOption

Cookie - Set an additional cookie (repeatable), value should be url encoded.

func CustomHeader

func CustomHeader(name, value string) PageOption

CustomHeader - Set an additional HTTP header (repeatable)

func CustomHeaderPropagation

func CustomHeaderPropagation() PageOption

CustomHeaderPropagation - Add HTTP headers specified by --custom-header for each resource request.

func DefaultHeader

func DefaultHeader() PageOption

DefaultHeader - Add a default header, with the name of the page to the left and the page numner to the right.

func DisableExternalLinks() PageOption

DisableExternalLinks - Do not make links to remote web pages

func DisableForms

func DisableForms() PageOption

DisableForms - Do not turn HTML form fields into pdf form fields

func DisableInternalLinks() PageOption

DisableInternalLinks - do not make local links

func DisableJavascript

func DisableJavascript() PageOption

DisableJavascript - do not allow web pages to run javascript

func DisableLocalFileAccess

func DisableLocalFileAccess() PageOption

DisableLocalFileAccess - do not allow conversion of a local file to read in other local files unless explicitly allowed with Allow()

func DisablePlugins

func DisablePlugins() PageOption

DisablePlugins - disable installed plugins

func DisableSmartShrinking

func DisableSmartShrinking() PageOption

DisableSmartShrinking - disable the intelligent shrinking strategy used by webkit that makes the pixel/dpi ratio none constant.

func DisableTocBackLinks() PageOption

DisableTocBackLinks - do not link from section header to toc

func EnableExternalLinks() PageOption

EnableExternalLinks - Make links to remote web pages

func EnableForms

func EnableForms() PageOption

EnableForms - Turn HTML form fields into pdf form fields

func EnableInternalLinks() PageOption

EnableInternalLinks - make local links

func EnableJavascript

func EnableJavascript() PageOption

EnableJavascript - do allow web pages to run javascript

func EnableLocalFileAccess

func EnableLocalFileAccess() PageOption

EnableLocalFileAccess - do not allow conversion of a local file to read in other local files unless explicitly allowed with Allow()

func EnablePlugins

func EnablePlugins() PageOption

EnablePlugins - enable installed plugins (plugins will likely not work)

func EnableSmartShrinking

func EnableSmartShrinking() PageOption

EnableSmartShrinking - enable the intelligent shrinking strategy used by webkit that makes the pixel/dpi ratio none constant.

func EnableTocBackLinks() PageOption

EnableTocBackLinks - link from section header to toc

func Encoding

func Encoding(encoding string) PageOption

Encoding - Set the default text encoding for text input

func ExcludeFromOutline

func ExcludeFromOutline() PageOption

ExcludeFromOutline - do not include in the table of contents and outlines

func FooterCenter

func FooterCenter(text string) PageOption

FooterCenter - centered footer text

func FooterFontName

func FooterFontName(font string) PageOption

FooterFontName - set footer font name

func FooterFontSize

func FooterFontSize(size int) PageOption

FooterFontSize - set footer font size

func FooterHTML

func FooterHTML(url string) PageOption

FooterHTML - Adds an html footer

func FooterLeft

func FooterLeft(text string) PageOption

FooterLeft - left aligned footer text

func FooterLine

func FooterLine() PageOption

FooterLine - display line above the footer

func FooterRight

func FooterRight(text string) PageOption

FooterRight - right aligned footer text

func FooterSpacing

func FooterSpacing(spacing float64) PageOption

FooterSpacing - spacing between the footer and content in mm.

func HeaderCenter

func HeaderCenter(text string) PageOption

HeaderCenter - centered header text

func HeaderFontName

func HeaderFontName(font string) PageOption

HeaderFontName - set header font name

func HeaderFontSize

func HeaderFontSize(size int) PageOption

HeaderFontSize - set header font size

func HeaderHTML

func HeaderHTML(url string) PageOption

HeaderHTML - Adds an html header

func HeaderLeft

func HeaderLeft(text string) PageOption

HeaderLeft - left aligned header text

func HeaderLine

func HeaderLine() PageOption

HeaderLine - display line above the header

func HeaderRight

func HeaderRight(text string) PageOption

HeaderRight - right aligned header text

func HeaderSpacing

func HeaderSpacing(spacing float64) PageOption

HeaderSpacing - spacing between the header and content in mm.

func Images

func Images() PageOption

Images - do load or print images

func IncludeInOutline

func IncludeInOutline() PageOption

IncludeInOutline - include in the table of contents and outlines

func JavascriptDelay

func JavascriptDelay(msec int) PageOption

JavascriptDelay - Wait some milliseconds for javascript to finish

func KeepRelativeLinks() PageOption

KeepRelativeLinks - keep relative external links as relative external links

func LoadErrorHandling

func LoadErrorHandling(handler string) PageOption

LoadErrorHandling - Specify how to handle pages that fail to load: abort, ignore or skip.

func LoadMediaErrorHandling

func LoadMediaErrorHandling(handler string) PageOption

LoadMediaErrorHandling - specify how to handle media pages that fail to load: abort, ignore or skip.

func MinFontSize

func MinFontSize(size int) PageOption

MinFontSize - minimum font size

func NoBackground

func NoBackground() PageOption

NoBackground - do not print background

func NoCustomHeaderPropagation

func NoCustomHeaderPropagation() PageOption

NoCustomHeaderPropagation - Do not add HTTP headers specified by --custom-header for each resource request.

func NoFooterLine

func NoFooterLine() PageOption

NoFooterLine - do not display line above the footer

func NoHeaderLine

func NoHeaderLine() PageOption

NoHeaderLine - do not display line above the header

func NoImages

func NoImages() PageOption

NoImages - do not load or print images

func NoPrintMediaType

func NoPrintMediaType() PageOption

NoPrintMediaType - do not use print media type instead of screen

func NoStopSlowScripts

func NoStopSlowScripts() PageOption

NoStopSlowScripts

func PageOffset

func PageOffset(offset int) PageOption

PageOffset - set the starting page number

func Password

func Password(password string) PageOption

Password - HTTP authentication password

func Post

func Post(name, value string) PageOption

Post - add an additional post field

func PostFile

func PostFile(name, path string) PageOption

PostFile - post an additional file (repeatable)

func PrintMediaType

func PrintMediaType() PageOption

PrintMediaType - use print media type instead of screen

func Proxy

func Proxy(proxy string) PageOption

Proxy - use a proxy

func RadioButton

func RadioButton(path string) PageOption

RadioButton - use this svg file when rendering unchecked radio buttons

func RadioButtonChecked

func RadioButtonChecked(path string) PageOption

RadioButtonChecked - use this svg file when rendering checked radio buttons

func Replace

func Replace(name, value string) PageOption

Replace - replace 'name' with value in header and footer (repeatable).

func ResolveRelativeLinks() PageOption

ResolveRelativeLinks

func RunScript

func RunScript(js string) PageOption

RunScript

func StopSlowScripts

func StopSlowScripts() PageOption

StopSlowScripts - stop slow running javascripts

func UserStyleSheet

func UserStyleSheet(url string) PageOption

UserStyleSheet - specify a user style sheet, to load with every page

func Username

func Username(username string) PageOption

Username - HTTP authentication username

func ViewportSize

func ViewportSize(size string) PageOption

ViewportSize - set viewport size if you have custom scrollbars or css attribute over-flow to emulate window size

func WindowStatus

func WindowStatus(status string) PageOption

WindowStatus - wait until window.status is equal to this string before rendering page

func Zoom

func Zoom(factor float64) PageOption

Zoom - use this zoom factor

Jump to

Keyboard shortcuts

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