pdfire

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 5, 2020 License: MIT Imports: 12 Imported by: 0

README

PDFire.io Logo

PDFire GO

GitHub

This package provides a client for the PDFire.io API. Read the Documentation for a list of available options.

Go to GoDoc.org for the library documentation.

Installation

go get -u github.com/modernice/pdfire-go

Basic usage

import "github.com/modernice/pdfire-go"

client := pdfire.New("YOUR-API-KEY")

pdf, err := pdfire.Convert(
    pdfire.URL("https://google.com"),
    pdfire.Margin(0),
    pdfire.Format(pdfire.FormatA4),
)

pdf.SaveTo("/path/on/disk.pdf")

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrorCodeInvalidRequest is returned from the API when the user sends an invalid conversion request.
	ErrorCodeInvalidRequest = APIErrorCode(400)
	// ErrorCodeUnauthenticated is returned from the API when the user provides an invalid API key.
	ErrorCodeUnauthenticated = APIErrorCode(401)
	// ErrorCodeQuotaExceeded is returned from the API when the user's monthly limits are exhausted.
	ErrorCodeQuotaExceeded = APIErrorCode(402)
	// ErrorCodeForbiddenAction is returned from the API when the user uses an option that is not included in the subscription.
	ErrorCodeForbiddenAction = APIErrorCode(403)
	// ErrorCodeConversionFailed is returned from the API when the conversion fails for any reason.
	ErrorCodeConversionFailed = APIErrorCode(500)
)
View Source
var (
	// ErrEmptyAPIKey is returned when the user provides an empty string as the API key.
	ErrEmptyAPIKey = errors.New("you have provided an empty API key")
	// ErrNilHTTPClient is returned then the user provides nil as the HTTP client.
	ErrNilHTTPClient = errors.New("you cannot provide nil as the HTTP client")
)
View Source
var (
	// FormatLetter is the page format "letter" (8.5in x 11in).
	FormatLetter = paperFormat("letter")
	// FormatLegal is the page format "legal" (8.5in x 14in).
	FormatLegal = paperFormat("legal")
	// FormatTabloid is the page format "tabloid" (11in x 17in).
	FormatTabloid = paperFormat("tabloid")
	// FormatLedger is the page format "ledger" (17in x 11in).
	FormatLedger = paperFormat("ledger")
	// FormatA0 is the page format "A0" (33.1in x 46.8in).
	FormatA0 = paperFormat("a0")
	// FormatA1 is the page format "A1" (23.4in x 33.1in).
	FormatA1 = paperFormat("a1")
	// FormatA2 is the page format "A2" (16.54in x 23.4in).
	FormatA2 = paperFormat("a2")
	// FormatA3 is the page format "A3" (11.7in x 16.54in).
	FormatA3 = paperFormat("a3")
	// FormatA4 is the page format "A4" (8.27 x 11.7in).
	FormatA4 = paperFormat("a4")
	// FormatA5 is the page format "A5" (5.83in x 8.27in).
	FormatA5 = paperFormat("a5")
	// FormatA6 is the page format "A6" (4.13in x 5.83in).
	FormatA6 = paperFormat("a6")
)
View Source
var (
	// MediaScreen is the CSS "screen" media.
	MediaScreen = media("screen")
	// MediaPrint is the CSS "print" media.
	MediaPrint = media("print")
)
View Source
var (
	// WaitEventLoad is used to wait for the "load" event of the browser before capturing the PDF.
	WaitEventLoad = waitUntilEvent("load")
	// WaitEventDOM is used to wait for the rendering of the DOM before capturing the PDF.
	WaitEventDOM = waitUntilEvent("dom")
)
View Source
var (
	// DownloadClient is the HTTP client to use for the download of cloud served PDFs.
	DownloadClient = http.DefaultClient
)
View Source
var (
	// ErrPDFNotServed is returned when trying to download a non-CDN PDF from the CDN.
	ErrPDFNotServed = errors.New("the PDF is not served via the CDN")
)

Functions

func StorageDisk

func StorageDisk(disk string) func(storage *StorageParam)

StorageDisk specifies the disk ID for the storage option.

func StoragePath

func StoragePath(path string) func(storage *StorageParam)

StoragePath specifies the file path for the storage option.

Types

type APIError

type APIError struct {
	Message string
}

APIError is an API error.

func (APIError) Error

func (err APIError) Error() string

type APIErrorCode

type APIErrorCode int

APIErrorCode is the HTTP status code

type APIErrorResponse

type APIErrorResponse struct {
	StatusCode APIErrorCode
	Errors     []APIError
}

APIErrorResponse is an API error response.

func (APIErrorResponse) Error

func (r APIErrorResponse) Error() string

type BufferResult

type BufferResult bytes.Buffer

BufferResult contains the PDF as a byte buffer.

func (*BufferResult) Bytes

func (r *BufferResult) Bytes() ([]byte, error)

Bytes returns the bytes of the PDF.

func (*BufferResult) Read

func (r *BufferResult) Read(p []byte) (n int, err error)

Read reads the next len(p) bytes from the PDF buffer or until the buffer is drained.

func (*BufferResult) SaveTo

func (r *BufferResult) SaveTo(path string) (err error)

SaveTo saves the PDF as a file to the specified path.

type Client

type Client struct {
	HTTPClient *http.Client
	APIKey     string
	BaseURL    string
}

Client is the client for the PDFire API.

func New

func New(apiKey string, options ...ClientOption) *Client

New returns a new client with the provided API key.

func (*Client) Convert

func (c *Client) Convert(options ...ConversionOption) (Result, error)

Convert converts an URL or HTML string to a PDF with the given parameter options and returns the conversion result.

func (*Client) ConvertHTML

func (c *Client) ConvertHTML(html string, options ...ConversionOption) (Result, error)

ConvertHTML converts an HTML string to a PDF and returns the conversion result.

func (*Client) ConvertHTMLReader

func (c *Client) ConvertHTMLReader(r io.Reader, options ...ConversionOption) (Result, error)

ConvertHTMLReader converts an HTML string to a PDF and returns the conversion result.

func (*Client) ConvertParams

func (c *Client) ConvertParams(params *ConversionParams) (Result, error)

ConvertParams converts with the given parameters and returns the conversion result.

func (*Client) ConvertURL

func (c *Client) ConvertURL(url string, options ...ConversionOption) (Result, error)

ConvertURL converts a URL to a PDF and returns the conversion result.

func (*Client) Merge

func (c *Client) Merge(options ...MergeOption) (Result, error)

Merge converts multiple URLs or HTML strings and merges them into a single PDF.

type ClientOption

type ClientOption func(*Client)

ClientOption applies an option to the client.

func UseAPIKey

func UseAPIKey(key string) ClientOption

UseAPIKey sets the API key for the requests.

func UseBaseURL

func UseBaseURL(url string) ClientOption

UseBaseURL sets the base URL for the requests.

func UseHTTPClient

func UseHTTPClient(httpclient *http.Client) ClientOption

UseHTTPClient sets the HTTP client for the requests.

type CommonOption

type CommonOption interface {
	ConversionOption
	MergeOption
}

CommonOption ...

type CommonOptionFunc

type CommonOptionFunc func(p interface{})

CommonOptionFunc ...

func CDN

func CDN(cdn bool) CommonOptionFunc

CDN sets the cdn option.

func OwnerPassword

func OwnerPassword(pw string) CommonOptionFunc

OwnerPassword sets the owner password of the PDF.

func Secure

func Secure(owner, user string) CommonOptionFunc

Secure sets the owner and user password of the PDF.

func Storage

func Storage(opt ...func(*StorageParam)) CommonOptionFunc

Storage configures the PDF to be uploaded to a cloud storage disk.

func UserPassword

func UserPassword(pw string) CommonOptionFunc

UserPassword sets the user password of the PDF.

func (CommonOptionFunc) ApplyConversionParams

func (fn CommonOptionFunc) ApplyConversionParams(p *ConversionParams)

ApplyConversionParams ...

func (CommonOptionFunc) ApplyMergeParams

func (fn CommonOptionFunc) ApplyMergeParams(p *MergeParams)

ApplyMergeParams ...

type Conversion

type Conversion struct {
	InitializedAt time.Time         `json:"initializedAt"`
	FinishedAt    time.Time         `json:"finishedAt"`
	Status        ConversionStatus  `json:"status"`
	Error         *string           `json:"error"`
	Result        *ConversionResult `json:"result"`
	// contains filtered or unexported fields
}

Conversion contains the response data of a conversion that's served via the CDN.

func (*Conversion) Bytes

func (c *Conversion) Bytes() ([]byte, error)

Bytes returns the bytes of the PDF.

func (*Conversion) Read

func (c *Conversion) Read(buf []byte) (n int, err error)

Read reads the next len(buf) bytes from the PDF. If the PDF is served via the CDN, it will be downloaded first. Returns ErrPDFNotServed if it tries to download the PDF from the CDN but can't.

func (*Conversion) SaveTo

func (c *Conversion) SaveTo(path string) error

SaveTo saves the PDF as a file to the specified path.

type ConversionOption

type ConversionOption interface {
	ApplyConversionParams(*ConversionParams)
}

ConversionOption applies an option to the conversion parameters.

type ConversionOptionFunc

type ConversionOptionFunc func(*ConversionParams)

ConversionOptionFunc ...

func AllowErrorPage

func AllowErrorPage(allow bool) ConversionOptionFunc

AllowErrorPage specifies if the API allows pages with an HTTP status code outside the 2xx range.

func BlockAds

func BlockAds(blockAds bool) ConversionOptionFunc

BlockAds sets the blockAds option.

func Delay

func Delay(timeout time.Duration) ConversionOptionFunc

Delay sets the delay for when the page has loaded.

func EmulateMedia

func EmulateMedia(media media) ConversionOptionFunc

EmulateMedia sets the CSS media option.

func EmulateMediaPrint

func EmulateMediaPrint() ConversionOptionFunc

EmulateMediaPrint sets the CSS media option to "print".

func EmulateMediaScreen

func EmulateMediaScreen() ConversionOptionFunc

EmulateMediaScreen sets the CSS media option to "screen".

func FooterTemplate

func FooterTemplate(html string) ConversionOptionFunc

FooterTemplate sets the HTML for the PDF footer.

func Format

func Format(format paperFormat) ConversionOptionFunc

Format sets the paper format of the PDF.

func HTML

func HTML(html string) ConversionOptionFunc

HTML sets the HTML option.

func Header(key string, value interface{}) ConversionOptionFunc

Header adds an HTTP header to the request.

func HeaderTemplate

func HeaderTemplate(html string) ConversionOptionFunc

HeaderTemplate sets the HTML for the PDF header.

func Headers

func Headers(headers map[string]interface{}) ConversionOptionFunc

Headers adds multiple HTTP headers to the request.

func Landscape

func Landscape(landscape bool) ConversionOptionFunc

Landscape sets the landscape option.

func Margin

func Margin(margin interface{}) ConversionOptionFunc

Margin sets the top, right, bottom and left margin of the PDF. Accepts values labeled with units (px, in, mm, cm). Defaults to pixels when no unit given.

func MarginBottom

func MarginBottom(margin interface{}) ConversionOptionFunc

MarginBottom sets the bottom margin of the PDF. Accepts values labeled with units (px, in, mm, cm). Defaults to pixels when no unit given.

func MarginBottomCentimeter

func MarginBottomCentimeter(margin float64) ConversionOptionFunc

MarginBottomCentimeter sets the bottom margin of the PDF in centimeters.

func MarginBottomInch

func MarginBottomInch(margin float64) ConversionOptionFunc

MarginBottomInch sets the bottom margin of the PDF in inch.

func MarginBottomMillimeter

func MarginBottomMillimeter(margin float64) ConversionOptionFunc

MarginBottomMillimeter sets the bottom margin of the PDF in millimeters.

func MarginBottomPixel

func MarginBottomPixel(margin int) ConversionOptionFunc

MarginBottomPixel sets the bottom margin of the PDF in pixels.

func MarginCentimeter

func MarginCentimeter(margin float64) ConversionOptionFunc

MarginCentimeter sets the top, right, bottom and left margin of the PDF in centimeters.

func MarginInch

func MarginInch(margin float64) ConversionOptionFunc

MarginInch sets the top, right, bottom and left margin of the PDF in inches.

func MarginLeft

func MarginLeft(margin interface{}) ConversionOptionFunc

MarginLeft sets the left margin of the PDF. Accepts values labeled with units (px, in, mm, cm). Defaults to pixels when no unit given.

func MarginLeftCentimeter

func MarginLeftCentimeter(margin float64) ConversionOptionFunc

MarginLeftCentimeter sets the left margin of the PDF in centimeters.

func MarginLeftInch

func MarginLeftInch(margin float64) ConversionOptionFunc

MarginLeftInch sets the left margin of the PDF in inch.

func MarginLeftMillimeter

func MarginLeftMillimeter(margin float64) ConversionOptionFunc

MarginLeftMillimeter sets the left margin of the PDF in millimeters.

func MarginLeftPixel

func MarginLeftPixel(margin int) ConversionOptionFunc

MarginLeftPixel sets the left margin of the PDF in pixels.

func MarginMillimeter

func MarginMillimeter(margin float64) ConversionOptionFunc

MarginMillimeter sets the top, right, bottom and left margin of the PDF in millimeters.

func MarginPixel

func MarginPixel(margin int) ConversionOptionFunc

MarginPixel sets the top, right, bottom and left margin of the PDF in pixels.

func MarginRight

func MarginRight(margin interface{}) ConversionOptionFunc

MarginRight sets the right margin of the PDF. Accepts values labeled with units (px, in, mm, cm). Defaults to pixels when no unit given.

func MarginRightCentimeter

func MarginRightCentimeter(margin float64) ConversionOptionFunc

MarginRightCentimeter sets the right margin of the PDF in centimeters.

func MarginRightInch

func MarginRightInch(margin float64) ConversionOptionFunc

MarginRightInch sets the right margin of the PDF in inch.

func MarginRightMillimeter

func MarginRightMillimeter(margin float64) ConversionOptionFunc

MarginRightMillimeter sets the right margin of the PDF in millimeters.

func MarginRightPixel

func MarginRightPixel(margin int) ConversionOptionFunc

MarginRightPixel sets the right margin of the PDF in pixels.

func MarginTop

func MarginTop(margin interface{}) ConversionOptionFunc

MarginTop sets the top margin of the PDF. Accepts values labeled with units (px, in, mm, cm). Defaults to pixels when no unit given.

func MarginTopCentimeter

func MarginTopCentimeter(margin float64) ConversionOptionFunc

MarginTopCentimeter sets the top margin of the PDF in centimeters.

func MarginTopInch

func MarginTopInch(margin float64) ConversionOptionFunc

MarginTopInch sets the top margin of the PDF in inches.

func MarginTopMillimeter

func MarginTopMillimeter(margin float64) ConversionOptionFunc

MarginTopMillimeter sets the top margin of the PDF in millimeters.

func MarginTopPixel

func MarginTopPixel(margin int) ConversionOptionFunc

MarginTopPixel sets the top margin of the PDF in pixels.

func Optimize

func Optimize(optimize bool) ConversionOptionFunc

Optimize enables CSS optimizations.

func PageRanges

func PageRanges(ranges ...interface{}) ConversionOptionFunc

PageRanges sets the page ranges of the PDF.

func PaperHeight

func PaperHeight(height interface{}) ConversionOptionFunc

PaperHeight sets the PDF paper height. Accepts values labeled with units (px, in, mm, cm). Defaults to pixels when no unit given.

func PaperHeightCentimeter

func PaperHeightCentimeter(height float64) ConversionOptionFunc

PaperHeightCentimeter sets the PDF paper height in centimeters.

func PaperHeightInch

func PaperHeightInch(height float64) ConversionOptionFunc

PaperHeightInch sets the PDF paper height in inches.

func PaperHeightMillimeter

func PaperHeightMillimeter(height float64) ConversionOptionFunc

PaperHeightMillimeter sets the PDF paper height in millimeters.

func PaperHeightPixel

func PaperHeightPixel(height int) ConversionOptionFunc

PaperHeightPixel sets the PDF paper height in pixels.

func PaperWidth

func PaperWidth(width interface{}) ConversionOptionFunc

PaperWidth sets the PDF paper width. Accepts values labeled with units (px, in, mm, cm). Defaults to pixels when no unit given.

func PaperWidthCentimeter

func PaperWidthCentimeter(width float64) ConversionOptionFunc

PaperWidthCentimeter sets the PDF paper width in centimeters.

func PaperWidthInch

func PaperWidthInch(width float64) ConversionOptionFunc

PaperWidthInch sets the PDF paper width in inches.

func PaperWidthMillimeter

func PaperWidthMillimeter(width float64) ConversionOptionFunc

PaperWidthMillimeter sets the PDF paper width in millimeters.

func PaperWidthPixel

func PaperWidthPixel(width int) ConversionOptionFunc

PaperWidthPixel sets the PDF paper width in pixels.

func PreferCSSPageSize

func PreferCSSPageSize(preferCSSPageSize bool) ConversionOptionFunc

PreferCSSPageSize sets the preferCSSPageSize option.

func PrintBackground

func PrintBackground(printBackground bool) ConversionOptionFunc

PrintBackground sets the printBackground option.

func Scale

func Scale(scale float64) ConversionOptionFunc

Scale sets the scale of the PDF.

func Selector

func Selector(selector string) ConversionOptionFunc

Selector sets the selector option.

func Timeout

func Timeout(timeout time.Duration) ConversionOptionFunc

Timeout sets the overall conversion timeout.

func URL

URL sets the URL option.

func ViewportHeight

func ViewportHeight(height int) ConversionOptionFunc

ViewportHeight sets the viewport height of the page.

func ViewportWidth

func ViewportWidth(width int) ConversionOptionFunc

ViewportWidth sets the viewport width of the page.

func WaitForSelector

func WaitForSelector(s string) ConversionOptionFunc

WaitForSelector sets the waitForSelector option.

func WaitForSelectorTimeout

func WaitForSelectorTimeout(timeout time.Duration) ConversionOptionFunc

WaitForSelectorTimeout sets the timeout for the waitForSelector option.

func WaitUntil

func WaitUntil(we waitUntilEvent) ConversionOptionFunc

WaitUntil sets the waitUntil option.

func WaitUntilDOM

func WaitUntilDOM() ConversionOptionFunc

WaitUntilDOM sets the waitUntil option to "dom".

func WaitUntilLoad

func WaitUntilLoad() ConversionOptionFunc

WaitUntilLoad sets the waitUntil option to "load".

func WaitUntilTimeout

func WaitUntilTimeout(timeout time.Duration) ConversionOptionFunc

WaitUntilTimeout sets the timeout for the waitUntil option.

func (ConversionOptionFunc) ApplyConversionParams

func (fn ConversionOptionFunc) ApplyConversionParams(p *ConversionParams)

ApplyConversionParams ...

type ConversionParams

type ConversionParams struct {
	HTML                   *string                `json:"html"`
	URL                    *string                `json:"url"`
	CDN                    *bool                  `json:"cdn"`
	Storage                *StorageParam          `json:"storage"`
	Landscape              *bool                  `json:"landscape"`
	PrintBackground        *bool                  `json:"printBackground"`
	Scale                  *float64               `json:"scale"`
	Format                 *paperFormat           `json:"format"`
	PaperWidth             interface{}            `json:"paperWidth"`
	PaperHeight            interface{}            `json:"paperHeight"`
	Margin                 interface{}            `json:"margin"`
	MarginTop              interface{}            `json:"marginTop"`
	MarginBottom           interface{}            `json:"marginBottom"`
	MarginLeft             interface{}            `json:"marginLeft"`
	MarginRight            interface{}            `json:"marginRight"`
	PageRanges             *string                `json:"pageRanges"`
	HeaderTemplate         *string                `json:"headerTemplate"`
	FooterTemplate         *string                `json:"footerTemplate"`
	PreferCSSPageSize      *bool                  `json:"preferCSSPageSize"`
	ViewportWidth          *int                   `json:"viewportWidth"`
	ViewportHeight         *int                   `json:"viewportHeight"`
	BlockAds               *bool                  `json:"blockAds"`
	Selector               *string                `json:"selector"`
	WaitForSelector        *string                `json:"waitForSelector"`
	WaitForSelectorTimeout *int                   `json:"waitForSelectorTimeout"`
	WaitUntil              *waitUntilEvent        `json:"waitUntil"`
	WaitUntilTimeout       *int                   `json:"waitUntilTimeout"`
	Delay                  *int                   `json:"delay"`
	Timeout                *int                   `json:"timeout"`
	Headers                map[string]interface{} `json:"headers"`
	EmulateMedia           *media                 `json:"emulateMedia"`
	OwnerPassword          *string                `json:"ownerPassword"`
	UserPassword           *string                `json:"userPassword"`
	AllowErrorPage         *bool                  `json:"allowErrorPage"`
	Optimize               *bool                  `json:"optimize"`
}

ConversionParams contains the conversion configuration.

func NewDocument

func NewDocument(options ...ConversionOption) *ConversionParams

NewDocument returns new conversion parameters (alias for NewParams).

func NewParams

func NewParams(options ...ConversionOption) *ConversionParams

NewParams returns new conversion parameters.

func (*ConversionParams) MarshalJSON

func (p *ConversionParams) MarshalJSON() ([]byte, error)

MarshalJSON marshals the params into JSON.

func (*ConversionParams) SetCDN

func (p *ConversionParams) SetCDN(cdn bool)

SetCDN sets the CDN option.

func (*ConversionParams) SetOwnerPassword

func (p *ConversionParams) SetOwnerPassword(pw string)

SetOwnerPassword sets the owner password option.

func (*ConversionParams) SetStorage

func (p *ConversionParams) SetStorage(storage StorageParam)

SetStorage sets the storage option.

func (*ConversionParams) SetUserPassword

func (p *ConversionParams) SetUserPassword(pw string)

SetUserPassword sets the user password option.

type ConversionResult

type ConversionResult struct {
	Size      int           `json:"size"`
	Width     int           `json:"width"`
	Height    int           `json:"height"`
	ExpiresAt *time.Time    `json:"expiresAt"`
	Runtime   time.Duration `json:"runtime"`
	URL       string        `json:"url"`
}

ConversionResult contains the URL, file size and expiry of the created PDF.

func (*ConversionResult) UnmarshalJSON

func (r *ConversionResult) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals the JSON result into r.

type ConversionStatus

type ConversionStatus string

ConversionStatus is the status of the conversion.

type MergeOption

type MergeOption interface {
	ApplyMergeParams(*MergeParams)
}

MergeOption ...

type MergeOptionFunc

type MergeOptionFunc func(*MergeParams)

MergeOptionFunc ...

func Document

func Document(options ...ConversionOption) MergeOptionFunc

Document adds a document to merge parameters.

func Documents

func Documents(docs ...*ConversionParams) MergeOptionFunc

Documents adds documents to merge parameters.

func (MergeOptionFunc) ApplyMergeParams

func (fn MergeOptionFunc) ApplyMergeParams(p *MergeParams)

ApplyMergeParams ...

type MergeParams

type MergeParams struct {
	Documents     []*ConversionParams `json:"documents"`
	OwnerPassword *string             `json:"ownerPassword"`
	UserPassword  *string             `json:"userPassword"`
	CDN           *bool               `json:"cdn"`
	Storage       *StorageParam       `json:"storage"`
}

MergeParams contains the conversion configuration.

func (*MergeParams) MarshalJSON

func (p *MergeParams) MarshalJSON() ([]byte, error)

MarshalJSON marshals the params into JSON.

func (*MergeParams) SetCDN

func (p *MergeParams) SetCDN(cdn bool)

SetCDN sets the CDN option.

func (*MergeParams) SetOwnerPassword

func (p *MergeParams) SetOwnerPassword(pw string)

SetOwnerPassword sets the owner password option.

func (*MergeParams) SetStorage

func (p *MergeParams) SetStorage(storage StorageParam)

SetStorage sets the storage option.

func (*MergeParams) SetUserPassword

func (p *MergeParams) SetUserPassword(pw string)

SetUserPassword sets the user password option.

type Result

type Result interface {
	io.Reader
	Bytes() ([]byte, error)
	SaveTo(path string) error
}

Result is a conversion result.

type StorageParam

type StorageParam struct {
	Disk string
	Path string
}

StorageParam is the configuration for the cloud storage.

Jump to

Keyboard shortcuts

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