pdf

package module
v0.0.0-...-42f891b Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2019 License: BSD-3-Clause Imports: 17 Imported by: 0

README

PDF Writer

Package pdfwriter provides a mid-level generator for PDF documents. The goal is to provide an API at the same level of abstraction as PDF documents themselves. The document structure can be defined, as well as adding pages with text, graphics, and annotations.

Documentation Go Report Card

Install

The package can be installed from the command line using the go tool. Beyond what is provided by the standard library, there are no platform dependencies.

go get bitbucket.org/rj/pdfwriter

Getting Started

  • Package documentation and examples are on godoc.
  • Example use of the package can be found in the file pdf_test.go.

Contribute

Feedback and PRs welcome.

License

BSD © Robert Johnstone

Documentation

Overview

Package pdfwriter provides a mid-level generator for PDF documents. The goal is to provide an API at the same level of abstraction as PDF documents themselves. The document structure can be defined, as well as adding pages with text, graphics, and annotations.

The coordinate system used is based on the native format for PDF documents. Although scaling transforms are possible, all distances and dimensions are specified in points (1/72 inch). The origin for the coordinate system is in the bottom left corner.

Low-level primitives (such as described in section 3 of the reference) will not be exposed.

References

ISO 32000-1 Document management -- Portable document format -- Part 1: PDF 1.7

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	A3      = Size{841.89, 1190.55}
	A4      = Size{595.28, 841.89}
	A5      = Size{420.94, 595.28}
	A6      = Size{297.64, 420.94}
	A2      = Size{1190.55, 1683.78}
	A1      = Size{1683.78, 2383.94}
	Letter  = Size{612, 792}
	Legal   = Size{612, 1008}
	Tabloid = Size{792, 1224}
)

Common page sizes.

View Source
var (
	ErrRequiredVersion = errors.New("The version specified for the document is not sufficient to support all the features used.")
)

Functions

This section is empty.

Types

type BlendMode

type BlendMode uint8

BlendMode selects the blend function used when composing objects using transparency. For most use cases, the value BlendNormal should be used. For details on the other blend modes, refer to section 7.2.4 of the reference.

const (
	BlendNormal BlendMode = iota
	BlendMultiply
	BlendScreen
	BlendOverlay
	BlendDarken
	BlendLighten
	BlendColorDodge
	BlendColorBurn
	BlendHardLight
	BlendSoftLight
	BlendDifference
	BlendExclusion
	BlendHue
	BlendSaturation
	BlendColor
	BlendLuminosity
)

All available blend modes supported by PDF documents.

type CapStyle

type CapStyle uint8

CapStyle represents a line-cap, which describe the shape for drawing the ends of lines. See section 8.4.3.3.

const (
	ButtCap   CapStyle = 0
	RoundCap  CapStyle = 1
	SquareCap CapStyle = 2
)

Available line-cap styles.

type DrawOp

type DrawOp uint8

DrawOp represents the drawing operations to be performed when displaying a figure. Different operations may be or'ed together to create a single operations specifying multiple operations.

const (
	Nop     DrawOp = 0 // Used to finish a path, but no drawing is performed.
	Stroke  DrawOp = 1 // Stroke the outline of the shape with the current draw color
	Fill    DrawOp = 2 // Fill the shape with the current fill color
	EvenOdd DrawOp = 4 // Use the even-odd winding rule when determining which regions are part of the interior
)

Available basic drawing operations.

type Encoding

type Encoding uint8

Encoding represents one of the character set encodings supported by the PDF format.

const (
	StandardEncoding Encoding = iota
	MacRomanEncoding
	WinAnsiEncoding
	PDFDocEncoding
	MacExpertEncoding
	SymbolEncoding
	ZapfDingbatsEncoding
)

Available builtin encodings supported by PDF documents.

func (Encoding) Map

func (e Encoding) Map() map[rune]byte

Map returns a map that can be used to translate runes into bytes that match the encoding.

func (Encoding) String

func (e Encoding) String() string

String returns a string representation of the encoding.

type Font

type Font interface {
	Key() string
	Name() string
	Encoding() Encoding
	RuneWidths() []int16
	Underline() (position int, thickness int)
	// contains filtered or unexported methods
}

Font provides access to a font resource added to the PDF document.

type FontFamily

type FontFamily string

FontFamily is a key indicating a font. The keys are either provided by the builtin fonts used by PDF documents, or determined when adding an external font resource (such as a truetype font) to the document.

const (
	Courier   FontFamily = "courier"
	Helvetica FontFamily = "helvetica"
	Times     FontFamily = "times"
	Symbol    FontFamily = "symbol"
	Dingbats  FontFamily = "zapfdingbats"
)

Available font family that are builtin to PDF viewers.

type FontStyle

type FontStyle uint8

FontStyle is a bitfield of formatting options provided for builtin fonts.

Underline is not supported natively by the format, but this package will add underline when included in the style.

const (
	Normal    FontStyle = 0
	Bold      FontStyle = 1
	Italic    FontStyle = 2
	Underline FontStyle = 4
)

Available font styles supported by the builtin fonts for PDF documents.

type JoinStyle

type JoinStyle uint8

JoinStyle represents different methods for drawing the joins in line segments. See section 8.4.3.4.

const (
	MiterJoin JoinStyle = 0
	RoundJoin JoinStyle = 1
	BevelJoin JoinStyle = 2
)

Available line-join styles.

type PDF

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

A PDF manages the creation of a PDF document. It manages information about the pages in a document, along with those pages' contents. Additional required resources, such as images, fonts, and shadings are also managed.

Each PDF maintains an index to the current page, which is used to direct all drawing operations. Drawing operations are append only, so old drawing operations cannot not be queried or modified. However, old pages can be reopened and added to.

Drawing operations affect the current page. Methods that modify the graphics state or create drawing operations will panic if no page is currently selected.

Example
const Margin = 1 * Inch

// Create a new PDF document using Letter paper, and some dark blue text
// over a gray background.
doc := New(Letter)
doc.AddPage()
ps := doc.CurrentPageSize()
doc.SetFillGray(192)
doc.Rectangle(Margin, Margin, ps.Width-2*Margin, ps.Height-2*Margin, Fill)
doc.SetFillRGB(0, 0, 128)
doc.SetFont(Times, Normal, 12*Pt)
doc.Text("Hello, world!", Margin, ps.Height-Margin-12)

// Write the file to disk
data, err := doc.Close()
if err != nil {
	fmt.Printf("Error: %s\n", err)
} else {
	// Omitting error handling for example.
	file, _ := os.OpenFile("./example.pdf", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	defer file.Close()
	data.WriteTo(file)
}
Output:

func New

func New(size Size) *PDF

New creates a new PDF document. The default page size must be specified.

func (*PDF) AddBlendMode

func (p *PDF) AddBlendMode(mode BlendMode, strokeAlpha, fillAlpha float32) int

AddBlendMode creates a resource in the PDF document specifying the blend mode, as well as alpha values, to use in transparency. Once created, the blend mode can be reused as often as necessary with calls to SetBlendModeWithIndex.

Transparency requires a minimum version of 1.4. Package users should ensure that the PDF document has the required minimum version listed with a call to SetMinimumVersion.

func (*PDF) AddBookmark

func (p *PDF) AddBookmark(text string, target Point) int

AddBookmark creates a top-level bookmark for the PDF document. When created, the bookmark will show up in the table of contents, and point to the current page.

This function will panic if no page is currently open. See the method CurrentPage.

func (*PDF) AddBookmarkChild

func (p *PDF) AddBookmarkChild(text string, target Point, parentIndex int) int

AddBookmarkChild creates a bookmark for the PDF document. When created, the bookmark will show up in the table of contents, and point to the current page. The bookmark will appear as a child of the bookmark specified by parentIndex.

This function will panic if no page is currently open. See the method CurrentPage.

func (*PDF) AddBuiltinFont

func (p *PDF) AddBuiltinFont(family FontFamily, style FontStyle) (fontIndex int, err error)

AddBuiltinFont adds the font described by the family and style to the resources for the PDF document. The font can be selected for use with calls to SetFontByIndex.

If a the font has already been added, then the index of the existing resource is returned.

If the font has not already been added as a resource, or is not a builtin font, then an error will be returned.

func (*PDF) AddCheckboxField

func (p *PDF) AddCheckboxField(bounds Rectangle, name string, value bool)

AddCheckboxField adds a checkbox to the curent page.

This function will panic if no page is currently open. See the method CurrentPage.

func (p *PDF) AddExternalLink(bounds Rectangle, url string)

AddExternalLink adds a link area to the current page. When clicked, the link area will redirect to the external resources indicated by the URL.

This function will panic if no page is currently open. See the method CurrentPage.

func (*PDF) AddFontTTF

func (p *PDF) AddFontTTF(data []byte) (int, FontFamily, error)

AddFontTTF adds a truetype font as a resource to the PDF document. The parameter data contains the bytes for the font file. The font can be selected for use with calls to SetFontByIndex.

func (*PDF) AddImage

func (p *PDF) AddImage(img image.Image) int

AddImage creates a resource in the PDF document with the image data. The function returns an index, which can be used with the method Image to draw the picture onto a page.

Note, that images of type image.Gray, image.Gray16, and image.RGBA are supported by copying the pixel data directly. Other images type will require a potentially expensive conversion to RGBA before the image data will be written to the PDF document.

func (p *PDF) AddInternalLink(bounds Rectangle, pageIndex int, target Point)

AddInternalLink adds a link area to the current page. When clicked, the link area will redirect to another location in the document, specified by the pageIndex and the x, y position on that page.

This function will panic if no page is currently open. See the method CurrentPage.

func (*PDF) AddJPEG

func (p *PDF) AddJPEG(w io.Reader) (imageIndex int, err error)

AddJPEG embeds a JPEG image into the PDF document. Note that the image is not actually displayed on any page. However, once created, the image can be used multiple times. See the method ImageWithIndex.

func (*PDF) AddLinearGradientRGB

func (p *PDF) AddLinearGradientRGB(a, b Point, r1, g1, b1, r2, g2, b2 uint8) int

AddLinearGradientRGB adds a linear gradient definition to the PDF document.

func (*PDF) AddPage

func (p *PDF) AddPage() int

AddPage appends a new page to the document using the default page size. The new page will be opened for drawing. The page index for the new page will be returned.

func (*PDF) AddPageWithSize

func (p *PDF) AddPageWithSize(size Size) int

AddPageWithSize appends a new page to the document using the specified page size. The new page will be opened for drawing. The page index for the new page will be returned.

Example
// Create a new PDF document with a default page size of Letter.
doc := New(Letter)
doc.AddPage()              // First page
doc.AddPageWithSize(Legal) // Second page
doc.AddPage()              // Third page

// Verify the page sizes.
for i := 0; i < doc.PageCount(); i++ {
	doc.MoveToPage(i)
	fmt.Printf("Page %d has size %s.\n", i+1, doc.CurrentPageSize())
}
Output:

Page 1 has size Letter.
Page 2 has size Legal.
Page 3 has size Letter.

func (*PDF) AddRadialGradientRGB

func (p *PDF) AddRadialGradientRGB(a Point, ra PT, b Point, rb PT, r1, g1, b1, r2, g2, b2 uint8) int

AddRadialGradientRGB adds a radial gradient definition to the PDF document.

func (*PDF) AddSignatureField

func (p *PDF) AddSignatureField(bounds Rectangle, name string)

func (*PDF) AddTextAnnotation

func (p *PDF) AddTextAnnotation(bounds Rectangle, contents string)

AddTextAnnotation adds a note attached to a point on the current page.

This function will panic if no page is currently open. See the method CurrentPage.

func (*PDF) AddTextField

func (p *PDF) AddTextField(bounds Rectangle, name string, value string, options TextFieldOptions, maxlen int)

AddTextField adds a text field to the current page.

This function will panic if no page is currently open. See the method CurrentPage.

func (*PDF) Close

func (p *PDF) Close() (*bytes.Buffer, error)

Close finishes processing of the description of the PDF document, and returns a buffer with the data for the PDF document.

func (*PDF) ClosePage

func (p *PDF) ClosePage()

ClosePage closes the current page.

func (*PDF) CurrentPageIndex

func (p *PDF) CurrentPageIndex() (page int, ok bool)

CurrentPageIndex returns the index of the currently open page. The page index is 0-based, and should be used in calls to MoveToPage.

If no page is currently open, then the value of ok will be false.

func (*PDF) CurrentPageSize

func (p *PDF) CurrentPageSize() Size

CurrentPageSize returns the size of the current page. If no page is current, then the default page size for the document is returned.

func (*PDF) DisableCompression

func (p *PDF) DisableCompression()

DisableCompression disables the compression of data streams inside the PDF document.

func (*PDF) ForEachPage

func (p *PDF) ForEachPage(draw func(pageIndex int))

ForEachPage moves through each page in the PDF document, and calls the specified callback.

Example
const Margin = 1 * Inch

// Create a new PDF document, with some pages.
doc := New(Letter)
doc.AddPage()
doc.SetFillRGB(192, 0, 0)
doc.Rectangle(0, 0, Letter.Width, Letter.Height, Fill|Stroke)
doc.AddPage()
doc.SetFillRGB(0, 192, 0)
doc.Rectangle(0, 0, Letter.Width, Letter.Height, Fill|Stroke)
doc.AddPage()
doc.SetFillRGB(0, 0, 192)
doc.Rectangle(0, 0, Letter.Width, Letter.Height, Fill|Stroke)

// Add a footer to each page
doc.ForEachPage(func(index int) {
	doc.SetFillGray(0)
	doc.SetFont(Times, Normal, 10)
	doc.Text(
		fmt.Sprintf("Page %d of %d", index+1, doc.PageCount()),
		72, 72,
	)
})

// Write the file to disk
data, err := doc.Close()
if err != nil {
	fmt.Printf("Error: %s\n", err)
} else {
	// Omitting error handling for example.
	file, _ := os.OpenFile("./example.pdf", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	defer file.Close()
	data.WriteTo(file)
}
Output:

func (*PDF) Image

func (p *PDF) Image(img image.Image, bounds Rectangle)

Image creates an image resource for the supplied image, and then displays that image on the current page in the box specified. This is a utility function to cover calling AddImage followed by ImageByIndex.

func (*PDF) ImageByIndex

func (p *PDF) ImageByIndex(index int, bounds Rectangle)

ImageByIndex displays an image on the current page in the box specified.

func (*PDF) Line

func (p *PDF) Line(a, b Point)

Line draws a line between points (x1, y1) and (x2, y2) on the current page. The color, linewidth and cap style are determined from the graphics state.

func (*PDF) MoveToPage

func (p *PDF) MoveToPage(pageIndex int)

MoveToPage closes the current page, and then selects the page with the specified page index. Future drawing command will then be appended to that page.

func (*PDF) PageCount

func (p *PDF) PageCount() int

PageCount returns the number of pages in the document.

func (*PDF) Path

func (p *PDF) Path() *Path

Path returns a handle for the current drawing path.

func (*PDF) PopState

func (p *PDF) PopState()

PopState restores a graphics state by popping the most recent state from the graphics stack.

func (*PDF) PushState

func (p *PDF) PushState()

PushState saves the current graphics state to the graphics stack.

func (*PDF) Rectangle

func (p *PDF) Rectangle(x, y, w, h PT, op DrawOp) *Path

Rectangle displays a rectangle on the current page. If Fill is included in the drawing operations, the the rectangle will be filled using the current fill color. If Stroke is included in the drawing operation, the rectangle will be outlined using the current draw color, line width, and join style.

func (*PDF) Rotate

func (p *PDF) Rotate(radians float64)

Rotate updates the current graphics context with a transformation matrix to rotate future drawing operations. This is a utility function to simplify calls to Transform.

func (*PDF) Scale

func (p *PDF) Scale(factor float32)

Scale updates the current graphics context with a transformation matrix to scale future drawing operations. This is a utility function to simplify calls to Transform.

func (*PDF) SetAuthor

func (p *PDF) SetAuthor(author string)

SetAuthor sets the author for the document, which appears in the properties for the document.

Example
doc := New(Letter.Portrait())
doc.SetAuthor("Your Name")
doc.SetCreationDate(time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC)) // For reproducibility of the test output
data, err := doc.Close()
if err != nil {
	fmt.Printf("Error: %s\n", err)
} else {
	fmt.Printf("%s\n", data)
}
Output:

func (*PDF) SetBlendMode

func (p *PDF) SetBlendMode(mode BlendMode, strokeAlpha, fillAlpha float32) int

SetBlendMode is a convenience function for calling AddBlendMode followed by SetBlendModeWithIndex.

func (*PDF) SetBlendModeWithIndex

func (p *PDF) SetBlendModeWithIndex(modeIndex int)

SetBlendModeWithIndex adds the information for the selected blend mode to the current graphics state.

This function will panic if no page is currently open. See the method CurrentPage.

func (*PDF) SetBookmarkStyle

func (p *PDF) SetBookmarkStyle(bookmarkIndex int, clr color.RGBA, style FontStyle)

SetBookmarkStyle adds styling information to a bookmark. However, the style information will only be written if the version is set to 1.4 or greater. See the method SetMinimumVersion.

Although the parameter colour is an RGBA, alpha is not supported in bookmarks.

Underlining is not supported in bookmarks.

func (*PDF) SetCap

func (p *PDF) SetCap(cap CapStyle)

SetCap updates the graphics state for the current page to set the line cap style. The line cap style specifies the shape used at the end of all open paths.

func (*PDF) SetCharacterSpacing

func (p *PDF) SetCharacterSpacing(tc float32)

SetCharacterSpacing updates the graphics state for the current page to set additional spacing between characters when displaying text. The units are unscaled text space units. See section 9.3.2.

func (*PDF) SetCreationDate

func (p *PDF) SetCreationDate(creation time.Time)

SetCreationDate sets the creation date for the document, which appears in the properties for the document. If the creation date is zero, it will be replaced with the current time when the document is closed.

func (*PDF) SetCreator

func (p *PDF) SetCreator(creator string)

SetCreator sets the creator for the document, which appears in the properties for the document.

func (*PDF) SetDashPattern

func (p *PDF) SetDashPattern(array []PT, phase PT)

SetDashPattern updates the graphics state for the current page to set the pattern of dashes and gaps when stroking a path. The array describes the lengths of dashes and gaps when drawing a line. The phase specifies a distance into the pattern which indicates the starting point when drawing a new line.

To clear the dash pattern so that further lines are strokes without any gaps, use a nil array.

See section 8.4.3.6.

func (*PDF) SetDrawCMYK

func (p *PDF) SetDrawCMYK(c, m, y, k uint8)

SetDrawCMYK updates the graphics state for the current page to set the draw color. The graphics state is also updated to use the CMKY color space.

func (*PDF) SetDrawColor

func (p *PDF) SetDrawColor(draw color.Color)

SetDrawColor updates the graphics state for the current page to set the draw color. The color space is selected based on the color model.

func (*PDF) SetDrawGray

func (p *PDF) SetDrawGray(gray uint8)

SetDrawGray updates the graphics state for the current page to set the draw color. The graphics state is also updated to use the gray color space.

func (*PDF) SetDrawGray16

func (p *PDF) SetDrawGray16(gray uint16)

SetDrawGray16 updates the graphics state for the current page to set the draw color. The graphics state is also updated to use the gray color space.

func (*PDF) SetDrawRGB

func (p *PDF) SetDrawRGB(r, g, b uint8)

SetDrawRGB updates the graphics state for the current page to set the draw color. The graphics state is also updated to use the RGB color space.

func (*PDF) SetEncryption

func (p *PDF) SetEncryption(ownerPassword, userPassword string, permissions Permissions)

SetEncryption set the PDF document to be encrypted. Users who can supply the owner password will get full access to the document, while users who can supply the user password will only get access to capabilities included in the permissions.

func (*PDF) SetFillCMYK

func (p *PDF) SetFillCMYK(c, m, y, k uint8)

SetFillCMYK sets the fill color for the current page using a CMYK color space.

func (*PDF) SetFillColor

func (p *PDF) SetFillColor(fill color.Color)

SetFillColor sets the fill color for the current page. The color space is selected based on the color model.

func (*PDF) SetFillGray

func (p *PDF) SetFillGray(gray uint8)

SetFillGray sets the fill color for the current page using a gray color space.

func (*PDF) SetFillGray16

func (p *PDF) SetFillGray16(gray uint16)

SetFillGray16 sets the fill color for the current page using a gray color space.

func (*PDF) SetFillRGB

func (p *PDF) SetFillRGB(r, g, b uint8)

SetFillRGB sets the fill color for the current page using a RGB color space.

func (*PDF) SetFlatness

func (p *PDF) SetFlatness(flatness float64)

SetFlatness updates the graphics state for the current page to set the flatness tolerance. The flatness tolerances controls the accuracy used when converting curves to line segments for drawing. See section 4.3.3 and 6.5.1 in the reference.

A value outside of the range [0,100] is an error, and will cause a panic.

See section 10.6.2.

func (*PDF) SetFont

func (p *PDF) SetFont(family FontFamily, style FontStyle, size PT) (int, error)

SetFont is a convenience function for calls to AddBuiltinFont followed by SetFontByIndex.

func (*PDF) SetFontByIndex

func (p *PDF) SetFontByIndex(index int, size PT)

SetFontByIndex sets the font information, including family, style, and size, for the current page.

func (*PDF) SetJoin

func (p *PDF) SetJoin(join JoinStyle)

SetJoin updates the graphics state for the current page to set the line join style. The line join style specifies the shape used at the corners when paths are stroked.

func (*PDF) SetKeywords

func (p *PDF) SetKeywords(keywords string)

SetKeywords sets the keywords for the document, which appears in the properties for the document.

func (*PDF) SetLeading

func (p *PDF) SetLeading(leading float32)

SetLeading updates the graphics state for the current page to set the text leading. See section 9.3.5.

func (*PDF) SetLineWidth

func (p *PDF) SetLineWidth(width PT)

SetLineWidth updates the graphics state for the current page to set the linewidth.

A negative value is an error, and will cause a panic.

func (*PDF) SetMinimumVersion

func (p *PDF) SetMinimumVersion(v Version)

SetMinimumVersion compares the requested version to the current version of the PDF document, and increases the version if necessary.

func (*PDF) SetMiterLimit

func (p *PDF) SetMiterLimit(limit PT)

SetMiterLimit updates the graphics state for the current page to set a limit for on how far miter joins can extend beyond the line width. See section 8.4.3.5.

func (*PDF) SetRenderingIntent

func (p *PDF) SetRenderingIntent(ri RenderingIntent)

SetRenderingIntent update the current graphics context with the specified rendering intent. Refer to section 8.6.5.8.

func (*PDF) SetSubject

func (p *PDF) SetSubject(subject string)

SetSubject sets the subject for the document, which appears in the properties for the document.

func (*PDF) SetTextRender

func (p *PDF) SetTextRender(mode TextRenderMode)

SetTextRender updates the graphics state for the current page to set the text render mode. The text render mode indicates the drawing operations used when displaying glyphs. See section 9.3.6.

func (*PDF) SetTextRise

func (p *PDF) SetTextRise(rise float32)

SetTextRise updates the graphics state for the current page to set the text rise. See section 9.3.7.

func (*PDF) SetTextScaling

func (p *PDF) SetTextScaling(tz float32)

SetTextScaling updates the graphics state for the current page to modify the horizontal scaling when displaying text. The default value is 100. See section 9.3.4.

func (*PDF) SetTitle

func (p *PDF) SetTitle(title string)

SetTitle sets the title for the document, which appears in the properties for the document.

func (*PDF) SetWordSpacing

func (p *PDF) SetWordSpacing(tw float32)

SetWordSpacing updates the graphics state for the current page to set additional spacing between words when displaying text. The units are unscaled text space units. See section 9.3.3.

func (*PDF) Shade

func (p *PDF) Shade(gradientIndex int)

Shade paints the region's current clipping region according to the specified shading.

func (*PDF) Text

func (p *PDF) Text(text string, x, y PT) (ok bool)

Text displays text on the current page using the current fill color. The font for the text must be set before calling this method using SetFont.

func (*PDF) TextFlow

func (p *PDF) TextFlow(text string, x, y, maxWidth PT) PT

TextFlow display text on the current page using the current fill color. The width of the text is contrained, and text will move to a new line when required.

func (*PDF) TextSplit

func (p *PDF) TextSplit(text string, index int, fontSize PT, maxWidth PT) []string

TextSplit determines how a string should be split into separate lines based on the font specified by the index and font size so that no line is longer than the maximum width.

This function does not modify the PDF document. To add the text to the document, call SetFontByIndex to select the correct font, and then use call Text for each line.

func (*PDF) TextWidth

func (p *PDF) TextWidth(text string) (width PT, ok bool)

TextWidth calculates the width

func (*PDF) Transform

func (p *PDF) Transform(a, b, c, d, e, f float32)

Transform updates the current graphics context with the specified transformation matrix. Refer to section 8.3 on coordinate systems.

func (*PDF) Translate

func (p *PDF) Translate(x, y PT)

Translate updates the current graphics context with a transformation matrix to translate future drawing operations. This is a utility function to simplify calls to Transform.

func (*PDF) Version

func (p *PDF) Version() Version

Version returns the version information for this document. Some operations may require a higher level, so the version may be increased when required to support features.

func (*PDF) WithState

func (p *PDF) WithState(draw func())

WithState isolated drawing commands that might affect the graphics state by pushing the state prior to the callback, and then popping it afterwards.

Drawing operations on the PDF are not allowed to add pages, or perform any other action that might change current page.

Example
pageSize := Size{1 * Inch, 1 * Inch}
doc := New(pageSize)
doc.SetLineWidth(1 * Pt)
doc.Line(Point{0, 24}, Point{72, 24})
doc.WithState(func() {
	doc.SetLineWidth(2 * Pt)
	doc.Line(Point{0, 36}, Point{72, 36})
})
// Note, this drawing command will use a linewidth of 1pt.  The change to the
// linewidth for the prior command was reversed when the callback was finished.
doc.Line(Point{0, 48}, Point{72, 48})
Output:

type PT

type PT float64

A PT is a representation of length stored in postscript points.

Example
length := 72 * Pt

fmt.Printf("72 points is:\n")
fmt.Printf("  %.1f inches\n", length.Inches())
fmt.Printf("  %.1f centimeters\n", length.Cm())
fmt.Printf("  %.1f millimeters\n", length.Mm())
fmt.Printf("  %.1f pica\n", length.Pica())
Output:

72 points is:
  1.0 inches
  2.5 centimeters
  25.4 millimeters
  6.0 pica
const (
	Pt   PT = 1
	Inch PT = 72        // Convert inches to points.
	Cm   PT = 72 / 2.54 // Convert centimeters to points.
	Mm   PT = 72 / 25.4 // Convert millimeters to points.
	Pica PT = 72 / 6    // Convert postscript pica to points.
)

Commonly used units of measure.

func (PT) Cm

func (pt PT) Cm() float64

Cm converts the length to centimeters, and returns the value as an undimensioned float.

func (PT) Inches

func (pt PT) Inches() float64

Inches converts the length to inches, and returns the value as an undimensioned float.

func (PT) Mm

func (pt PT) Mm() float64

Mm converts the length to millimeters, and returns the value as an undimensioned float.

func (PT) Pica

func (pt PT) Pica() float64

Pica converts the length to pica, and returns the value as an undimensioned float.

func (PT) Points

func (pt PT) Points() float64

Points converts the length to points (1/72"), and returns the value as an undimensioned float.

func (PT) Scale

func (pt PT) Scale(num, den int) PT

Scale scales the length by ratio of num:den.

type PageOrientation

type PageOrientation uint8

PageOrientation represents the direction in which a document is printed or displayed.

const (
	Portrait  PageOrientation = 0 // Page oriented so that width < height.
	Landscape PageOrientation = 1 // Page oriented so that height < width.
)

The possible page orientations.

type Path

type Path bytes.Buffer

Path is a handle for the current drawing path. Note, each page can have only a single drawing path current at a time. Any path should be closed and painted prior to starting a new path on the same page.

func (*Path) Clip

func (path *Path) Clip()

Clip updates the clipping path with the intersection of the current clipping path and the current drawing path.

func (*Path) ClipWithEvenOdd

func (path *Path) ClipWithEvenOdd()

ClipWithEvenOdd updates the clipping path with the intersection of the current clipping path and the current drawing path. The interior of the current path is determined using the even-odd winding rule.

func (*Path) Close

func (path *Path) Close(op DrawOp)

Close closes the current subpath. If necessary, a line segment is appended to the subpath.

As a convenience, drawing operations can be specified directly. If Fill is included in the drawing operations, the the path will be filled using the current fill color. If Stroke is included in the drawing operation, the path will be outlined using the current draw color, line width, and join style.

If EvenOdd is included in the drawing operation, an even-odd winding rule will be used when filling the interior.

If op is zero, the path will be closed, but no drawing operation will be performed. The path can then be used to set a clipping region, or drawn latter.

func (*Path) CurveTo

func (path *Path) CurveTo(cx, cy, dx, dy, x, y PT)

CurveTo modifies the current path by appending a bezier curve through the control points and ending on the final coordinates.

func (*Path) Draw

func (path *Path) Draw(op DrawOp)

Draw the current drawing path. If Fill is included in the drawing operations, the the path will be filled using the current fill color. If Stroke is included in the drawing operation, the path will be outlined using the current draw color, line width, and join style.

If EvenOdd is included in the drawing operation, an even-odd winding rule will be used when filling the interior.

func (*Path) LineTo

func (path *Path) LineTo(x, y PT)

LineTo modifies the current path by appending a line to the specified coordiates.

func (*Path) MoveTo

func (path *Path) MoveTo(x, y PT)

MoveTo starts a new subpath at the specified coordinates.

func (*Path) Shade

func (path *Path) Shade(gradientIndex int)

Shade fills the the current drawing path with specified shader.

type Permissions

type Permissions uint16

Permissions is a bit field describing the user permissions for an encrypted PDF document. See section 3.5.2 of the reference.

const (
	PrintPermission                Permissions = 1 << 2
	ModifyPermission               Permissions = 1 << 3
	CopyPermission                 Permissions = 1 << 4
	AnnotationsPermission          Permissions = 1 << 5
	FormPermission                 Permissions = 1 << 8
	ExtractTextAndImagesPermission Permissions = 1 << 9
	AssembleDocumentPermission     Permissions = 1 << 10
	FaithfulPrintPermission        Permissions = 1 << 11
	Revision3Permissions           Permissions = FormPermission | ExtractTextAndImagesPermission | AssembleDocumentPermission | FaithfulPrintPermission
)

Available permission flags for encrypted PDF documents.

type Point

type Point struct {
	X, Y PT
}

A Point is an X, Y coordinate pair.

func (Point) Add

func (p Point) Add(q Point) Point

Add returns the vector p+q.

func (Point) Mul

func (p Point) Mul(k float64) Point

Mul returns the vector p*k.

func (Point) String

func (p Point) String() string

String returns a string representation of p like "(3,4)".

func (Point) Sub

func (p Point) Sub(q Point) Point

Sub returns the vector p-q.

type Rectangle

type Rectangle struct {
	Min, Max Point
}

A Rectangle contains the points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y. It is well-formed if Min.X <= Max.X and likewise for Y. Points are always well-formed. A rectangle's methods always return well-formed outputs for well-formed inputs.

func Rect

func Rect(x0, y0, x1, y1 PT) Rectangle

Rect is shorthand for Rectangle{Pt(x0, y0), Pt(x1, y1)}. The returned rectangle has minimum and maximum coordinates swapped if necessary so that it is well-formed.

Example
// The following rectangle will have to have the corners flipped.
r := Rect(7.5*Inch, 10*Inch, 1*Inch, 1*Inch)
fmt.Printf("The rectangle is %s.\n", r)
Output:

The rectangle is (72,72)-(540,720).

func (Rectangle) Canon

func (r Rectangle) Canon() Rectangle

Canon returns the canonical version of r. The returned rectangle has minimum and maximum coordinates swapped if necessary so that it is well-formed.

func (Rectangle) Dx

func (r Rectangle) Dx() PT

Dx returns r's width.

func (Rectangle) Dy

func (r Rectangle) Dy() PT

Dy returns r's height.

func (Rectangle) Size

func (r Rectangle) Size() Point

Size returns r's width and height.

func (Rectangle) String

func (r Rectangle) String() string

String returns a string representation of r like "(3,4)-(6,5)".

type RenderingIntent

type RenderingIntent string

RenderingIntent represents specifies how rendering devices should handle colour accuracy. See section 8.6.5.8.

const (
	AbsoluteColorimetric RenderingIntent = "AbsoluteColorimetric"
	RelativeColorimetric RenderingIntent = "RelativeColorimetric"
	Saturation           RenderingIntent = "Saturation"
	Perceptual           RenderingIntent = "Perceptual"
)

Available rendering intents.

type Size

type Size struct {
	Width, Height PT
}

A Size is the width and height of a page.

func (Size) Landscape

func (s Size) Landscape() Size

Landscape returns the dimensions of a similar page size, but with a landscape orientation.

func (Size) Orientation

func (s Size) Orientation() PageOrientation

Orientation determines the orientation of the page size.

func (Size) Portrait

func (s Size) Portrait() Size

Portrait returns the dimensions of a similar page size, but with a portrait orientation.

func (Size) String

func (s Size) String() string

String returns the name of the page size, if recognized. For page sizes that are not recognized, the page size will be described as "Custom".

Example
// We can check the name of the known page sizes.
fmt.Printf("Dimensions of '%s' are %.0f x %.0f points.\n",
	Letter, Letter.Width, Letter.Height)
Output:

Dimensions of 'Letter' are 612 x 792 points.

type TextFieldOptions

type TextFieldOptions uint32

TextFieldOptions contains flags affecting the behaviour of text fields. See section 8.6.3 of the reference.

const (
	TextFieldNoOpt           TextFieldOptions = 0
	TextFieldReadOnly        TextFieldOptions = (1 << 0)
	TextFieldRequired        TextFieldOptions = (1 << 1)
	TextFieldNoExport        TextFieldOptions = (1 << 2)
	TextFieldMultiline       TextFieldOptions = (1 << 12)
	TextFieldPassword        TextFieldOptions = (1 << 13)
	TextFieldFileSelect      TextFieldOptions = (1 << 20) // Requires PDF version 1.4.
	TextFieldDoNotSpellCheck TextFieldOptions = (1 << 22) // Requires PDF version 1.4.
	TextFieldDoNotScroll     TextFieldOptions = (1 << 23) // Requires PDF version 1.4.
)

All field options for text fields.

type TextRenderMode

type TextRenderMode uint8

TextRenderMode describes the drawing operations to be applied when displaying text. The default mode is FillText. For details on the other text render modes, refer to section 5.2.5 of the reference.

const (
	FillText                   TextRenderMode = 0 // Glyph outlines are filled
	StrokeText                 TextRenderMode = 1 // Glyph outlines are stroked
	FillAndStrokeText          TextRenderMode = 2 // Glyph outlines are filled and then stroked
	InvisibleText              TextRenderMode = 3
	FillAndAddToClipping       TextRenderMode = 4
	StrokeAndAddToClipping     TextRenderMode = 5
	FillStrokeAndAddToClipping TextRenderMode = 6
	AddToClippingPath          TextRenderMode = 7 // Glyph outlines are used as a clipping boundary
)

Available text render modes supported by PDF documents.

type Version

type Version struct {
	Major uint8
	Minor uint8
}

Version represents the version of a PDF document.

func (Version) EQ

func (v Version) EQ(major uint8, minor uint8) bool

EQ returns whether the version is the same as the version specified by the parameters.

func (Version) GT

func (v Version) GT(major uint8, minor uint8) bool

GT returns whether the version is greater than the version specified by the parameters.

Example
// Example version for the PDF file.
v := Version{1, 3}

// Can we use blending?
if v.LT(1, 4) {
	fmt.Printf("Blending is unavailable, have %s, need 1.4.\n", v)
}
Output:

Blending is unavailable, have 1.3, need 1.4.

func (Version) LT

func (v Version) LT(major uint8, minor uint8) bool

LT returns whether the version is less than the version specified by the parameters.

func (Version) String

func (v Version) String() string

String returns a string representation of the PDF document version.

Example
// We can check the name of the known page sizes.
v := Version{1, 3}
fmt.Printf("String representation is %s.\n", v)
Output:

String representation is 1.3.

Directories

Path Synopsis
Package vgpdf implements the vg.Canvas interface using pdfwriter.
Package vgpdf implements the vg.Canvas interface using pdfwriter.

Jump to

Keyboard shortcuts

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