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 ¶
- Variables
- type BlendMode
- type CapStyle
- type DrawOp
- type Encoding
- type Font
- type FontFamily
- type FontStyle
- type JoinStyle
- type PDF
- func (p *PDF) AddBlendMode(mode BlendMode, strokeAlpha, fillAlpha float32) int
- func (p *PDF) AddBookmark(text string, target Point) int
- func (p *PDF) AddBookmarkChild(text string, target Point, parentIndex int) int
- func (p *PDF) AddBuiltinFont(family FontFamily, style FontStyle) (fontIndex int, err error)
- func (p *PDF) AddCheckboxField(bounds Rectangle, name string, value bool)
- func (p *PDF) AddExternalLink(bounds Rectangle, url string)
- func (p *PDF) AddFontTTF(data []byte) (int, FontFamily, error)
- func (p *PDF) AddImage(img image.Image) int
- func (p *PDF) AddInternalLink(bounds Rectangle, pageIndex int, target Point)
- func (p *PDF) AddJPEG(w io.Reader) (imageIndex int, err error)
- func (p *PDF) AddLinearGradientRGB(a, b Point, r1, g1, b1, r2, g2, b2 uint8) int
- func (p *PDF) AddPage() int
- func (p *PDF) AddPageWithSize(size Size) int
- func (p *PDF) AddRadialGradientRGB(a Point, ra PT, b Point, rb PT, r1, g1, b1, r2, g2, b2 uint8) int
- func (p *PDF) AddSignatureField(bounds Rectangle, name string)
- func (p *PDF) AddTextAnnotation(bounds Rectangle, contents string)
- func (p *PDF) AddTextField(bounds Rectangle, name string, value string, options TextFieldOptions, ...)
- func (p *PDF) Close() (*bytes.Buffer, error)
- func (p *PDF) ClosePage()
- func (p *PDF) CurrentPageIndex() (page int, ok bool)
- func (p *PDF) CurrentPageSize() Size
- func (p *PDF) DisableCompression()
- func (p *PDF) ForEachPage(draw func(pageIndex int))
- func (p *PDF) Image(img image.Image, bounds Rectangle)
- func (p *PDF) ImageByIndex(index int, bounds Rectangle)
- func (p *PDF) Line(a, b Point)
- func (p *PDF) MoveToPage(pageIndex int)
- func (p *PDF) PageCount() int
- func (p *PDF) Path() *Path
- func (p *PDF) PopState()
- func (p *PDF) PushState()
- func (p *PDF) Rectangle(x, y, w, h PT, op DrawOp) *Path
- func (p *PDF) Rotate(radians float64)
- func (p *PDF) Scale(factor float32)
- func (p *PDF) SetAuthor(author string)
- func (p *PDF) SetBlendMode(mode BlendMode, strokeAlpha, fillAlpha float32) int
- func (p *PDF) SetBlendModeWithIndex(modeIndex int)
- func (p *PDF) SetBookmarkStyle(bookmarkIndex int, clr color.RGBA, style FontStyle)
- func (p *PDF) SetCap(cap CapStyle)
- func (p *PDF) SetCharacterSpacing(tc float32)
- func (p *PDF) SetCreationDate(creation time.Time)
- func (p *PDF) SetCreator(creator string)
- func (p *PDF) SetDashPattern(array []PT, phase PT)
- func (p *PDF) SetDrawCMYK(c, m, y, k uint8)
- func (p *PDF) SetDrawColor(draw color.Color)
- func (p *PDF) SetDrawGray(gray uint8)
- func (p *PDF) SetDrawGray16(gray uint16)
- func (p *PDF) SetDrawRGB(r, g, b uint8)
- func (p *PDF) SetEncryption(ownerPassword, userPassword string, permissions Permissions)
- func (p *PDF) SetFillCMYK(c, m, y, k uint8)
- func (p *PDF) SetFillColor(fill color.Color)
- func (p *PDF) SetFillGray(gray uint8)
- func (p *PDF) SetFillGray16(gray uint16)
- func (p *PDF) SetFillRGB(r, g, b uint8)
- func (p *PDF) SetFlatness(flatness float64)
- func (p *PDF) SetFont(family FontFamily, style FontStyle, size PT) (int, error)
- func (p *PDF) SetFontByIndex(index int, size PT)
- func (p *PDF) SetJoin(join JoinStyle)
- func (p *PDF) SetKeywords(keywords string)
- func (p *PDF) SetLeading(leading float32)
- func (p *PDF) SetLineWidth(width PT)
- func (p *PDF) SetMinimumVersion(v Version)
- func (p *PDF) SetMiterLimit(limit PT)
- func (p *PDF) SetRenderingIntent(ri RenderingIntent)
- func (p *PDF) SetSubject(subject string)
- func (p *PDF) SetTextRender(mode TextRenderMode)
- func (p *PDF) SetTextRise(rise float32)
- func (p *PDF) SetTextScaling(tz float32)
- func (p *PDF) SetTitle(title string)
- func (p *PDF) SetWordSpacing(tw float32)
- func (p *PDF) Shade(gradientIndex int)
- func (p *PDF) Text(text string, x, y PT) (ok bool)
- func (p *PDF) TextFlow(text string, x, y, maxWidth PT) PT
- func (p *PDF) TextSplit(text string, index int, fontSize PT, maxWidth PT) []string
- func (p *PDF) TextWidth(text string) (width PT, ok bool)
- func (p *PDF) Transform(a, b, c, d, e, f float32)
- func (p *PDF) Translate(x, y PT)
- func (p *PDF) Version() Version
- func (p *PDF) WithState(draw func())
- type PT
- type PageOrientation
- type Path
- type Permissions
- type Point
- type Rectangle
- type RenderingIntent
- type Size
- type TextFieldOptions
- type TextRenderMode
- type Version
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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.
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.
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.
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.
type JoinStyle ¶
type JoinStyle uint8
JoinStyle represents different methods for drawing the joins in line segments. See section 8.4.3.4.
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 (*PDF) AddBlendMode ¶
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 ¶
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 ¶
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 ¶
AddCheckboxField adds a checkbox to the curent page.
This function will panic if no page is currently open. See the method CurrentPage.
func (*PDF) AddExternalLink ¶
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 ¶
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 (*PDF) AddInternalLink ¶
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 ¶
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 ¶
AddLinearGradientRGB adds a linear gradient definition to the PDF document.
func (*PDF) AddPage ¶
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 ¶
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 (*PDF) AddTextAnnotation ¶
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 ¶
Close finishes processing of the description of the PDF document, and returns a buffer with the data for the PDF document.
func (*PDF) CurrentPageIndex ¶
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 ¶
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 ¶
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 ¶
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 ¶
ImageByIndex displays an image on the current page in the box specified.
func (*PDF) Line ¶
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 ¶
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) 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetBlendMode is a convenience function for calling AddBlendMode followed by SetBlendModeWithIndex.
func (*PDF) SetBlendModeWithIndex ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetCreator sets the creator for the document, which appears in the properties for the document.
func (*PDF) SetDashPattern ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
SetFillCMYK sets the fill color for the current page using a CMYK color space.
func (*PDF) SetFillColor ¶
SetFillColor sets the fill color for the current page. The color space is selected based on the color model.
func (*PDF) SetFillGray ¶
SetFillGray sets the fill color for the current page using a gray color space.
func (*PDF) SetFillGray16 ¶
SetFillGray16 sets the fill color for the current page using a gray color space.
func (*PDF) SetFillRGB ¶
SetFillRGB sets the fill color for the current page using a RGB color space.
func (*PDF) SetFlatness ¶
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 ¶
SetFont is a convenience function for calls to AddBuiltinFont followed by SetFontByIndex.
func (*PDF) SetFontByIndex ¶
SetFontByIndex sets the font information, including family, style, and size, for the current page.
func (*PDF) SetJoin ¶
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 ¶
SetKeywords sets the keywords for the document, which appears in the properties for the document.
func (*PDF) SetLeading ¶
SetLeading updates the graphics state for the current page to set the text leading. See section 9.3.5.
func (*PDF) SetLineWidth ¶
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 ¶
SetMinimumVersion compares the requested version to the current version of the PDF document, and increases the version if necessary.
func (*PDF) SetMiterLimit ¶
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 ¶
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 ¶
SetTextRise updates the graphics state for the current page to set the text rise. See section 9.3.7.
func (*PDF) SetTextScaling ¶
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 ¶
SetTitle sets the title for the document, which appears in the properties for the document.
func (*PDF) SetWordSpacing ¶
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 ¶
Shade paints the region's current clipping region according to the specified shading.
func (*PDF) Text ¶
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 ¶
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 ¶
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) Transform ¶
Transform updates the current graphics context with the specified transformation matrix. Refer to section 8.3 on coordinate systems.
func (*PDF) Translate ¶
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 ¶
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 ¶
Cm converts the length to centimeters, and returns the value as an undimensioned float.
func (PT) Inches ¶
Inches converts the length to inches, and returns the value as an undimensioned float.
func (PT) Mm ¶
Mm converts the length to millimeters, and returns the value as an undimensioned float.
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 ¶
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 ¶
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 ¶
CurveTo modifies the current path by appending a bezier curve through the control points and ending on the final coordinates.
func (*Path) Draw ¶
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 ¶
LineTo modifies the current path by appending a line to the specified coordiates.
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.
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 ¶
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).
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 ¶
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 ¶
Portrait returns the dimensions of a similar page size, but with a portrait orientation.
func (Size) 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 ¶
Version represents the version of a PDF document.
func (Version) EQ ¶
EQ returns whether the version is the same as the version specified by the parameters.
func (Version) GT ¶
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.