Documentation
¶
Overview ¶
Package document contains the high-level PDF document implementation.
Most applications can start with the root gopdfkit package. Import document directly when you need explicit constructor options, document model types, measurement helpers, or lower-level PDF drawing APIs.
Example ¶
Example demonstrates the generation of a simple PDF document. Note that since only core fonts are used (in this case Arial, a synonym for Helvetica), an empty string can be specified for the font directory in the call to New(). Note also that the example.Filename() and example.Summary() functions belong to a separate, internal package and are not part of the gopdfkit library. If an error occurs at some point during the construction of the document, subsequent method calls exit immediately and the error is finally retrieved with the output call where it can be handled by the application.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New(document.OrientationPortrait, "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello World!")
fileStr := example.Filename("basic")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/basic.pdf
Index ¶
- Constants
- func FormDocumentHTML(form FormDocument) string
- func GenerateThumbnail(r io.Reader, options ThumbnailOptions) ([]byte, string, error)
- func GenerateThumbnailImage(src image.Image, sourceFormat string, options ThumbnailOptions) ([]byte, string, error)
- func GetPageSizes(source any) (map[int]map[string]Size, error)
- func QRCodeImageName(payload string) string
- func QRCodePNG(payload string, sizePx int) ([]byte, error)
- func RenderHTMLTemplate(templateHTML string, values HTMLTemplateValues) (string, error)
- func SetDefaultCatalogSort(flag bool)
- func SetDefaultCompression(compress bool)
- func SetDefaultCreationDate(tm time.Time)
- func SetDefaultModificationDate(tm time.Time)
- func TickmarkPrecision(div float64) int
- func Tickmarks(min, max float64) (list []float64, precision int)
- func UTF8CutFont(inBuf []byte, cutset string) (outBuf []byte)
- func UnicodeTranslator(r io.Reader) (f func(string) string, err error)
- func UnicodeTranslatorFromFile(fileStr string) (f func(string) string, err error)
- func ValidateFormDocumentHTML(form FormDocument) []string
- type Attachment
- type AttachmentBlock
- type Block
- type BlockKind
- type BlockMeasurement
- type BorderSide
- type BorderStyle
- type BoxStyle
- type CSSColorType
- type ClauseBlock
- type CompiledHTML
- type CompiledHTMLRecoveryIssue
- type CompiledHTMLStats
- type ComplianceMetadata
- type ComplianceValidationIssue
- type ComplianceValidationReport
- type ComplianceValidationSeverity
- type Document
- func (f *Document) AddAttachmentAnnotation(a *Attachment, x, y, w, h float64)
- func (f *Document) AddFont(familyStr, styleStr, fileStr string)
- func (f *Document) AddFontFromBytes(familyStr, styleStr string, jsonFileBytes, zFileBytes []byte)
- func (f *Document) AddFontFromReader(familyStr, styleStr string, r io.Reader)
- func (f *Document) AddLayer(name string, visible bool) (layerID int)
- func (f *Document) AddLink() int
- func (f *Document) AddPage()
- func (f *Document) AddPageFormat(orientationStr string, size Size)
- func (f *Document) AddPageFormatRotation(orientationStr string, size Size, rotation int)
- func (f *Document) AddPageRotation(rotation int)
- func (f *Document) AddSpotColor(name string, cyan, magenta, yellow, black byte)
- func (f *Document) AddTextWatermark(label string)
- func (f *Document) AddUTF8Font(familyStr, styleStr, fileStr string)
- func (f *Document) AddUTF8FontFromBytes(familyStr, styleStr string, utf8Bytes []byte)
- func (f *Document) AddUTF8FontFromCache(family, style string, cache *FontCache)
- func (f *Document) AliasNbPages(aliasStr string)
- func (f *Document) Arc(x, y, rx, ry, degRotate, degStart, degEnd float64, styleStr string)
- func (f *Document) ArcTo(x, y, rx, ry, degRotate, degStart, degEnd float64)
- func (f *Document) BeginArtifact()
- func (f *Document) BeginLayer(id int)
- func (f *Document) BeginStructure(role string)
- func (f *Document) Beziergon(points []Point, styleStr string)
- func (f *Document) Bookmark(txtStr string, level int, y float64)
- func (f *Document) Cell(w, h float64, txtStr string)
- func (f *Document) CellFormat(w, h float64, txtStr, borderStr string, ln int, alignStr string, fill bool, ...)
- func (f *Document) Cellf(w, h float64, fmtStr string, args ...any)
- func (f *Document) Circle(x, y, r float64, styleStr string)
- func (f *Document) ClearError()
- func (f *Document) ClipCircle(x, y, r float64, outline bool)
- func (f *Document) ClipEllipse(x, y, rx, ry float64, outline bool)
- func (f *Document) ClipEnd()
- func (f *Document) ClipPolygon(points []Point, outline bool)
- func (f *Document) ClipRect(x, y, w, h float64, outline bool)
- func (f *Document) ClipRoundedRect(x, y, w, h, r float64, outline bool)
- func (f *Document) ClipRoundedRectExt(x, y, w, h, rTL, rTR, rBR, rBL float64, outline bool)
- func (f *Document) ClipText(x, y float64, txtStr string, outline bool)
- func (f *Document) Close()
- func (f *Document) ClosePath()
- func (f *Document) CreateTemplate(fn func(*Tpl)) Template
- func (f *Document) CreateTemplateCustom(corner Point, size Size, fn func(*Tpl)) Template
- func (f *Document) Curve(x0, y0, cx, cy, x1, y1 float64, styleStr string)
- func (f *Document) CurveBezierCubic(x0, y0, cx0, cy0, cx1, cy1, x1, y1 float64, styleStr string)
- func (f *Document) CurveBezierCubicTo(cx0, cy0, cx1, cy1, x, y float64)
- func (f *Document) CurveCubic(x0, y0, cx0, cy0, x1, y1, cx1, cy1 float64, styleStr string)
- func (f *Document) CurveTo(cx, cy, x, y float64)
- func (f *Document) DrawPath(styleStr string)
- func (f *Document) Ellipse(x, y, rx, ry, degRotate float64, styleStr string)
- func (f *Document) EnableTaggedPDF()
- func (f *Document) EndArtifact()
- func (f *Document) EndLayer()
- func (f *Document) EndStructure()
- func (f *Document) Err() bool
- func (f *Document) Error() error
- func (f *Document) GetAlpha() (alpha float64, blendModeStr string)
- func (f *Document) GetAutoPageBreak() (auto bool, margin float64)
- func (f *Document) GetCellMargin() float64
- func (f *Document) GetConversionRatio() float64
- func (f *Document) GetDrawColor() (int, int, int)
- func (f *Document) GetDrawSpotColor() (name string, c, m, y, k byte)
- func (f *Document) GetFillColor() (int, int, int)
- func (f *Document) GetFillSpotColor() (name string, c, m, y, k byte)
- func (f *Document) GetFontDesc(familyStr, styleStr string) FontDescriptor
- func (f *Document) GetFontSize() (ptSize, unitSize float64)
- func (f *Document) GetImageInfo(imageStr string) (info *ImageInfo)
- func (f *Document) GetLineWidth() float64
- func (f *Document) GetMargins() (left, top, right, bottom float64)
- func (f *Document) GetPageHeight() float64
- func (f *Document) GetPageSize() (width, height float64)
- func (f *Document) GetPageSizeStr(sizeStr string) (size Size)
- func (f *Document) GetPageSizes(source any) map[int]map[string]Size
- func (f *Document) GetPageWidth() float64
- func (f *Document) GetStringSymbolWidth(s string) int
- func (f *Document) GetStringWidth(s string) float64
- func (f *Document) GetTextColor() (int, int, int)
- func (f *Document) GetTextSpotColor() (name string, c, m, y, k byte)
- func (f *Document) GetX() float64
- func (f *Document) GetXY() (float64, float64)
- func (f *Document) GetY() float64
- func (f *Document) HTMLNew() (html HTML)
- func (f *Document) ImageFromCache(name string, cache *ImageCache, x, y, w, h float64, flow bool, ...)
- func (f *Document) ImageOptions(imageNameStr string, x, y, w, h float64, flow bool, options ImageOptions, ...)
- func (f *Document) ImageOptionsExtended(name string, opts ExtendedImageOptions)
- func (f *Document) ImageTypeFromMime(mimeStr string) (tp string)
- func (f *Document) ImportObjPos(objPos map[string]map[int]string)
- func (f *Document) ImportObjects(objs map[string][]byte)
- func (f *Document) ImportPage(sourceFile string, pageNo int, box string) int
- func (f *Document) ImportPageStream(source io.Reader, pageNo int, box string) int
- func (f *Document) ImportPagesFromSource(source any, box string) []int
- func (f *Document) ImportTemplates(tpls map[string]string)
- func (f *Document) LTR()
- func (f *Document) Line(x1, y1, x2, y2 float64)
- func (f *Document) LineTo(x, y float64)
- func (f *Document) LinearGradient(x, y, w, h float64, r1, g1, b1, r2, g2, b2 int, x1, y1, x2, y2 float64)
- func (f *Document) Link(x, y, w, h float64, link int)
- func (f *Document) LinkString(x, y, w, h float64, linkStr string)
- func (f *Document) Ln(h float64)
- func (f *Document) MoveTo(x, y float64)
- func (f *Document) MultiCell(w, h float64, txtStr, borderStr, alignStr string, fill bool)
- func (f *Document) Ok() bool
- func (f *Document) OpenLayerPane()
- func (f *Document) Output(w io.Writer) error
- func (f *Document) OutputAndClose(w io.WriteCloser) error
- func (f *Document) OutputFileAndClose(fileStr string) error
- func (f *Document) OutputSigned(w io.Writer, options sign.Options) error
- func (f *Document) OutputSignedFile(fileStr string, options sign.Options) error
- func (f *Document) PageCount() int
- func (f *Document) PageNo() int
- func (f *Document) PageSize(pageNum int) (wd, ht float64, unitStr string)
- func (f *Document) PointConvert(pt float64) (u float64)
- func (f *Document) PointToUnitConvert(pt float64) (u float64)
- func (f *Document) Polygon(points []Point, styleStr string)
- func (f *Document) RTL()
- func (f *Document) RadialGradient(x, y, w, h float64, r1, g1, b1, r2, g2, b2 int, x1, y1, x2, y2, r float64)
- func (f *Document) RawWriteArtifactBuf(r io.Reader)
- func (f *Document) RawWriteArtifactStr(str string)
- func (f *Document) RawWriteBuf(r io.Reader)
- func (f *Document) RawWriteStr(str string)
- func (f *Document) Rect(x, y, w, h float64, styleStr string)
- func (f *Document) RegisterAlias(alias, replacement string)
- func (f *Document) RegisterImageFromCache(name string, cache *ImageCache) *ImageInfo
- func (f *Document) RegisterImageOptions(fileStr string, options ImageOptions) (info *ImageInfo)
- func (f *Document) RegisterImageOptionsReader(imgName string, options ImageOptions, r io.Reader) (info *ImageInfo)
- func (f *Document) RegisterQRCodePNG(payload string, sizePx int) (string, error)
- func (f *Document) RegisterThumbnail(name string, r io.Reader, options ThumbnailOptions) (*ImageInfo, error)
- func (f *Document) RoundedRect(x, y, w, h, r float64, corners string, stylestr string)
- func (f *Document) RoundedRectExt(x, y, w, h, rTL, rTR, rBR, rBL float64, stylestr string)
- func (f *Document) SVGWrite(sb *SVG, scale float64)
- func (f *Document) SetAcceptPageBreakFunc(fnc func() bool)
- func (f *Document) SetAlpha(alpha float64, blendModeStr string)
- func (f *Document) SetAttachments(as []Attachment)
- func (f *Document) SetAuthor(authorStr string, isUTF8 bool)
- func (f *Document) SetAutoPageBreak(auto bool, margin float64)
- func (f *Document) SetCatalogSort(flag bool)
- func (f *Document) SetCellMargin(margin float64)
- func (f *Document) SetComplianceMetadata(profile ComplianceMetadata)
- func (f *Document) SetCompression(compress bool)
- func (f *Document) SetCompressionLevel(level int)
- func (f *Document) SetCreationDate(tm time.Time)
- func (f *Document) SetCreator(creatorStr string, isUTF8 bool)
- func (f *Document) SetDashPattern(dashArray []float64, dashPhase float64)
- func (f *Document) SetDisplayMode(zoomStr, layoutStr string)
- func (f *Document) SetDrawColor(r, g, b int)
- func (f *Document) SetDrawSpotColor(name string, tint byte)
- func (f *Document) SetError(err error)
- func (f *Document) SetErrorf(fmtStr string, args ...any)
- func (f *Document) SetFillColor(r, g, b int)
- func (f *Document) SetFillSpotColor(name string, tint byte)
- func (f *Document) SetFont(familyStr, styleStr string, size float64)
- func (f *Document) SetFontLoader(loader FontLoader)
- func (f *Document) SetFontLocation(fontDirStr string)
- func (f *Document) SetFontSize(size float64)
- func (f *Document) SetFontStyle(styleStr string)
- func (f *Document) SetFontUnitSize(size float64)
- func (f *Document) SetFooterFunc(fnc func())
- func (f *Document) SetFooterFuncLpi(fnc func(lastPage bool))
- func (f *Document) SetHeaderFunc(fnc func())
- func (f *Document) SetHeaderFuncMode(fnc func(), homeMode bool)
- func (f *Document) SetHomeXY()
- func (f *Document) SetJavascript(script string)
- func (f *Document) SetKeywords(keywordsStr string, isUTF8 bool)
- func (f *Document) SetLeftMargin(margin float64)
- func (f *Document) SetLineCapStyle(styleStr string)
- func (f *Document) SetLineJoinStyle(styleStr string)
- func (f *Document) SetLineWidth(width float64)
- func (f *Document) SetLink(link int, y float64, page int)
- func (f *Document) SetMargins(left, top, right float64)
- func (f *Document) SetModificationDate(tm time.Time)
- func (f *Document) SetNextTextArtifact()
- func (f *Document) SetNextTextRole(role string)
- func (f *Document) SetNoCompression()
- func (f *Document) SetOutputIntent(iccProfile []byte, identifier string) error
- func (f *Document) SetPage(pageNum int)
- func (f *Document) SetPageBox(t string, x, y, wd, ht float64)
- func (f *Document) SetPageBoxRec(t string, pb PageBox)
- func (f *Document) SetProducer(producerStr string, isUTF8 bool)
- func (f *Document) SetProtection(actionFlag byte, userPassStr, ownerPassStr string)
- func (f *Document) SetRightMargin(margin float64)
- func (f *Document) SetSubject(subjectStr string, isUTF8 bool)
- func (f *Document) SetTextColor(r, g, b int)
- func (f *Document) SetTextRenderingMode(mode int)
- func (f *Document) SetTextSpotColor(name string, tint byte)
- func (f *Document) SetTitle(titleStr string, isUTF8 bool)
- func (f *Document) SetTopMargin(margin float64)
- func (f *Document) SetUnderlineThickness(thickness float64)
- func (f *Document) SetWordSpacing(space float64)
- func (f *Document) SetX(x float64)
- func (f *Document) SetXY(x, y float64)
- func (f *Document) SetXmpMetadata(xmpStream []byte)
- func (f *Document) SetY(y float64)
- func (f *Document) SetYWithResetX(y float64, resetX bool)
- func (f *Document) SplitLines(txt []byte, w float64) [][]byte
- func (f *Document) SplitText(txt string, w float64) (lines []string)
- func (f *Document) String() string
- func (f *Document) SubWrite(ht float64, str string, subFontSize, subOffset float64, link int, ...)
- func (f *Document) Text(x, y float64, txtStr string)
- func (f *Document) Transform(tm TransformMatrix)
- func (f *Document) TransformBegin()
- func (f *Document) TransformEnd()
- func (f *Document) TransformMirrorHorizontal(x float64)
- func (f *Document) TransformMirrorLine(angle, x, y float64)
- func (f *Document) TransformMirrorPoint(x, y float64)
- func (f *Document) TransformMirrorVertical(y float64)
- func (f *Document) TransformRotate(angle, x, y float64)
- func (f *Document) TransformScale(scaleWd, scaleHt, x, y float64)
- func (f *Document) TransformScaleX(scaleWd, x, y float64)
- func (f *Document) TransformScaleXY(s, x, y float64)
- func (f *Document) TransformScaleY(scaleHt, x, y float64)
- func (f *Document) TransformSkew(angleX, angleY, x, y float64)
- func (f *Document) TransformSkewX(angleX, x, y float64)
- func (f *Document) TransformSkewY(angleY, x, y float64)
- func (f *Document) TransformTranslate(tx, ty float64)
- func (f *Document) TransformTranslateX(tx float64)
- func (f *Document) TransformTranslateY(ty float64)
- func (f *Document) UnicodeTranslatorFromDescriptor(cpStr string) (rep func(string) string)
- func (f *Document) UnitToPointConvert(u float64) (pt float64)
- func (f *Document) UseImportedPage(pageID int, x, y, w, h float64)
- func (f *Document) UseImportedTemplate(tplName string, scaleX float64, scaleY float64, tX float64, tY float64)
- func (f *Document) UseTemplate(t Template)
- func (f *Document) UseTemplateScaled(t Template, corner Point, size Size)
- func (f *Document) Write(h float64, txtStr string)
- func (f *Document) WriteAligned(width, lineHeight float64, textStr, alignStr string)
- func (f *Document) WriteDocument(doc *LayoutDocument)
- func (f *Document) WriteLinkID(h float64, displayStr string, linkID int)
- func (f *Document) WriteLinkString(h float64, displayStr, targetStr string)
- func (f *Document) Writef(h float64, fmtStr string, args ...any)
- type DocumentColor
- type DocumentKind
- type DocumentMetadata
- type DocumentParty
- type DocumentTpl
- func (t *DocumentTpl) Bytes() []byte
- func (t *DocumentTpl) FromPage(page int) (Template, error)
- func (t *DocumentTpl) FromPages() []Template
- func (t *DocumentTpl) GobDecode(buf []byte) error
- func (t *DocumentTpl) GobEncode() ([]byte, error)
- func (t *DocumentTpl) ID() string
- func (t *DocumentTpl) Images() map[string]*ImageInfo
- func (t *DocumentTpl) NumPages() int
- func (t *DocumentTpl) Serialize() ([]byte, error)
- func (t *DocumentTpl) Size() (corner Point, size Size)
- func (t *DocumentTpl) Templates() []Template
- type ExtendedImageOptions
- type FontCache
- type FontDescriptor
- type FontLoader
- type FooterBlock
- type FormAnswer
- type FormDocument
- type FormQuestion
- type FormSection
- type GridType
- func (g GridType) Grid(pdf *Document)
- func (g GridType) Ht(dataHt float64) float64
- func (g GridType) HtAbs(dataHt float64) float64
- func (g GridType) Plot(pdf *Document, xMin, xMax float64, count int, fnc func(x float64) (y float64))
- func (g GridType) Pos(xRel, yRel float64) (x, y float64)
- func (g *GridType) TickmarksContainX(min, max float64)
- func (g *GridType) TickmarksContainY(min, max float64)
- func (g *GridType) TickmarksExtentX(min, div float64, count int)
- func (g *GridType) TickmarksExtentY(min, div float64, count int)
- func (g GridType) Wd(dataWd float64) float64
- func (g GridType) WdAbs(dataWd float64) float64
- func (g GridType) X(dataX float64) float64
- func (g GridType) XRange() (min, max float64)
- func (g GridType) XY(dataX, dataY float64) (x, y float64)
- func (g GridType) Y(dataY float64) float64
- func (g GridType) YRange() (min, max float64)
- type HTML
- type HTMLSegmentType
- type HTMLTemplateImage
- type HTMLTemplateRaw
- type HTMLTemplateValues
- type HeaderBlock
- type HeadingBlock
- type ImageBlock
- type ImageCache
- type ImageCrop
- type ImageFitMode
- type ImageInfo
- type ImageOptions
- type LayoutDocument
- func FormDocumentModel(form FormDocument) *LayoutDocument
- func LongFormHTMLDocumentModel(title, htmlStr string) (*LayoutDocument, []string)
- func NewAttestationDocument(title string, blocks ...Block) *LayoutDocument
- func NewGenericDocument(title string, blocks ...Block) *LayoutDocument
- func NewLayoutDocument(kind DocumentKind) *LayoutDocument
- func NewReportDocument(title string, blocks ...Block) *LayoutDocument
- func NewStatementDocument(title string, blocks ...Block) *LayoutDocument
- func NewTransactionalDocument(title string, blocks ...Block) *LayoutDocument
- type ListBlock
- type ListItem
- type MeasureContext
- type MetadataField
- type MetadataGridBlock
- type NoteBoxBlock
- type Options
- type PDFAMode
- type PageBox
- type PageBreakBlock
- type PageChrome
- type ParagraphBlock
- type Point
- type QRBlock
- type QRVerificationBlock
- type RGBAType
- type RGBType
- type SVG
- type SVGElement
- type SVGGradient
- type SVGGradientStop
- type SVGImage
- type SVGPath
- type SVGPattern
- type SVGSegment
- type SVGStyle
- type SVGText
- type SectionBlock
- type SignatureBlock
- type SignatureColumn
- type SignatureRowBlock
- type Size
- type Spacing
- type StateType
- type TableBlock
- type TableCell
- type TableColumn
- type TableRow
- type TableStyle
- type Template
- type TextSegment
- type TextStyle
- type ThumbnailOptions
- type TickFormatFncType
- type Tpl
- type TransformMatrix
Examples ¶
- Package
- Document.AddAttachmentAnnotation
- Document.AddFont
- Document.AddFontFromBytes
- Document.AddLayer
- Document.AddPage
- Document.AddSpotColor
- Document.AddUTF8Font
- Document.Beziergon
- Document.Bookmark
- Document.Cell (Strikeout)
- Document.CellFormat (Align)
- Document.CellFormat (Codepage)
- Document.CellFormat (Codepageescape)
- Document.CellFormat (Tables)
- Document.Circle
- Document.ClipRect
- Document.ClipText
- Document.CreateTemplate
- Document.DrawPath
- Document.HTMLNew
- Document.ImageOptions
- Document.ImageOptions (Formats)
- Document.LinearGradient
- Document.MoveTo
- Document.MultiCell
- Document.MultiCell (TextAlignments)
- Document.PageSize
- Document.Polygon
- Document.RTL (UnicodeTextFixture)
- Document.Rect
- Document.RegisterAlias
- Document.RegisterAlias (Utf8)
- Document.RegisterImageOptions
- Document.RegisterImageOptionsReader
- Document.RegisterImageOptionsReader (Flow)
- Document.RegisterThumbnail
- Document.RoundedRect
- Document.SVGWrite
- Document.SetAcceptPageBreakFunc
- Document.SetAlpha
- Document.SetAttachments
- Document.SetFillColor
- Document.SetFontLoader
- Document.SetJavascript
- Document.SetKeywords
- Document.SetLeftMargin
- Document.SetLineJoinStyle
- Document.SetModificationDate
- Document.SetPage
- Document.SetPageBox
- Document.SetProtection
- Document.SetTextRenderingMode
- Document.SetUnderlineThickness
- Document.SplitLines
- Document.SplitLines (Tables)
- Document.SplitLines (TextNotesTable)
- Document.SubWrite
- Document.TransformBegin
- Document.TransformRotate
- Document.WriteAligned
- Document.WriteLinkString (TextFixture)
- GenerateThumbnail
- NewGrid
- UTF8CutFont
Constants ¶
const ( CnProtectPrint = 4 CnProtectModify = 8 CnProtectCopy = 16 CnProtectAnnotForms = 32 )
Advisory bit flag constants that control document activities.
const ( // ThumbnailFormatPNG encodes thumbnails as PNG. ThumbnailFormatPNG = "png" // ThumbnailFormatJPEG encodes thumbnails as JPEG. ThumbnailFormatJPEG = "jpg" )
const ( // OrientationPortrait represents the portrait orientation. OrientationPortrait = "portrait" // OrientationLandscape represents the landscape orientation. OrientationLandscape = "landscape" )
const ( // UnitPoint represents points. UnitPoint = "pt" // UnitMillimeter represents millimeters. UnitMillimeter = "mm" // UnitCentimeter represents centimeters. UnitCentimeter = "cm" // UnitInch represents inches. UnitInch = "inch" )
const ( // PageSizeA3 represents the DIN/ISO A3 page size. PageSizeA3 = "A3" // PageSizeA4 represents the DIN/ISO A4 page size. PageSizeA4 = "A4" // PageSizeA5 represents the DIN/ISO A5 page size. PageSizeA5 = "A5" // PageSizeLetter represents the US Letter page size. PageSizeLetter = "Letter" // PageSizeLegal represents the US Legal page size. PageSizeLegal = "Legal" )
const ( // BorderNone draws no border. BorderNone = "" // BorderFull draws a full border. BorderFull = "1" // BorderLeft draws the left border. BorderLeft = "L" // BorderTop draws the top border. BorderTop = "T" // BorderRight draws the right border. BorderRight = "R" // BorderBottom draws the bottom border. BorderBottom = "B" )
const ( // LineBreakNone disables line breaks. LineBreakNone = 0 // LineBreakNormal enables normal line breaks. LineBreakNormal = 1 // LineBreakBelow enables a line break below the current element. LineBreakBelow = 2 )
const ( // AlignLeft aligns the cell content to the left. AlignLeft = "L" // AlignRight aligns the cell content to the right. AlignRight = "R" // AlignCenter centers the cell content. AlignCenter = "C" // AlignTop aligns the cell content to the top. AlignTop = "T" // AlignBottom aligns the cell content to the bottom. AlignBottom = "B" // AlignMiddle vertically centers the cell content. AlignMiddle = "M" // AlignBaseline aligns the cell content to the baseline. AlignBaseline = "B" )
const ( // FontFlagFixedPitch is set if all glyphs have the same width (as // opposed to proportional or variable-pitch fonts, which have // different widths). FontFlagFixedPitch = 1 << 0 // FontFlagSerif is set if glyphs have serifs, which are short // strokes drawn at an angle on the top and bottom of glyph stems. // (Sans serif fonts do not have serifs.) FontFlagSerif = 1 << 1 // FontFlagSymbolic is set if the font contains glyphs outside the // Adobe standard Latin character set. This flag and the // Nonsymbolic flag shall not both be set or both be clear. FontFlagSymbolic = 1 << 2 // FontFlagScript is set if glyphs resemble cursive handwriting. FontFlagScript = 1 << 3 // FontFlagNonsymbolic is set if the font uses the Adobe standard // Latin character set or a subset of it. FontFlagNonsymbolic = 1 << 5 // FontFlagItalic is set if glyphs have dominant vertical strokes // that are slanted. FontFlagItalic = 1 << 6 // FontFlagAllCap is set if the font contains no lowercase letters; // typically used for display purposes, such as for titles or // headlines. FontFlagAllCap = 1 << 16 // SmallCap is set if the font contains both uppercase and lowercase // letters. The uppercase letters are similar to those in the // regular version of the same typeface family. The glyphs for the // lowercase letters have the same shapes as the corresponding // uppercase letters, but they are sized and their proportions // adjusted so that they have the same size and stroke weight as // lowercase glyphs in the same typeface family. SmallCap = 1 << 18 // ForceBold determines whether bold glyphs shall be painted with // extra pixels even at very small text sizes by a conforming // reader. If the ForceBold flag is set, features of bold glyphs // may be thickened at small text sizes. ForceBold = 1 << 18 )
Font flags for FontDescriptor.Flags as defined in the PDF specification.
Variables ¶
This section is empty.
Functions ¶
func FormDocumentHTML ¶
func FormDocumentHTML(form FormDocument) string
FormDocumentHTML returns the canonical supported-HTML representation of a form document.
func GenerateThumbnail ¶
GenerateThumbnail decodes an image from r and returns encoded thumbnail bytes plus the gopdfkit image type string.
Example ¶
package main
import (
"bytes"
"fmt"
"image"
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
file, err := os.Open(example.ImageFile("logo.png"))
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = file.Close() }()
data, format, err := document.GenerateThumbnail(file, document.ThumbnailOptions{MaxWidth: 64, MaxHeight: 64})
if err != nil {
fmt.Println(err)
return
}
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(format, img.Bounds().Dx() <= 64, img.Bounds().Dy() <= 64)
}
Output: png true true
func GenerateThumbnailImage ¶
func GenerateThumbnailImage(src image.Image, sourceFormat string, options ThumbnailOptions) ([]byte, string, error)
GenerateThumbnailImage returns encoded thumbnail bytes for src plus the gopdfkit image type string.
func GetPageSizes ¶
GetPageSizes returns the available page box sizes for a PDF source. Sizes are reported in PDF points. source may be a file path string, []byte, or io.Reader.
func QRCodeImageName ¶ added in v0.3.0
QRCodeImageName returns the deterministic image name used for a QR payload.
func RenderHTMLTemplate ¶
func RenderHTMLTemplate(templateHTML string, values HTMLTemplateValues) (string, error)
RenderHTMLTemplate replaces {{key}} placeholders in templateHTML with values.
Placeholder keys are looked up literally, with an additional fallback that treats {{.key}} as {{key}}. Missing keys return an error so generated PDFs do not silently contain unresolved placeholders.
func SetDefaultCatalogSort ¶
func SetDefaultCatalogSort(flag bool)
SetDefaultCatalogSort sets the default value of the catalog sort flag that will be used when initializing a new Document instance. See SetCatalogSort() for more details.
func SetDefaultCompression ¶
func SetDefaultCompression(compress bool)
SetDefaultCompression controls the default setting of the internal compression flag. See SetCompression for more details. Compression is on by default.
func SetDefaultCreationDate ¶
SetDefaultCreationDate sets the default value of the document creation date that will be used when initializing a new Document instance. See SetCreationDate() for more details.
func SetDefaultModificationDate ¶
SetDefaultModificationDate sets the default document modification date used when initializing a new Document instance. See SetCreationDate() for more details.
func TickmarkPrecision ¶
TickmarkPrecision returns an appropriate precision value for label formatting.
func Tickmarks ¶
Tickmarks returns tickmarks appropriate for a chart axis and a precision for formatting labels. The values min and max will be contained within the tickmark range.
func UTF8CutFont ¶
UTF8CutFont is a utility function that generates a TrueType font composed only of the runes included in cutset. The rune glyphs are copied from inBuf. This function is demonstrated in ExampleUTF8CutFont().
Example ¶
ExampleUTF8CutFont demonstrates how generate a TrueType font subset.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func init() {
cleanup()
}
func cleanup() {
_ = filepath.Walk(example.PdfDir(),
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil {
return nil
}
if info.Mode().IsRegular() {
if len(path) > 3 {
if path[len(path)-4:] == ".pdf" {
_ = os.Remove(path)
}
}
}
return nil
})
}
func main() {
var pdfFileStr, fullFontFileStr, subFontFileStr string
var subFont, fullFont []byte
var err error
pdfFileStr = example.Filename("Document_UTF8CutFont")
fullFontFileStr = example.FontFile("calligra.ttf")
fullFont, err = os.ReadFile(fullFontFileStr)
if err == nil {
subFontFileStr = "calligra_cabbedvwxyz.ttf"
subFont = document.UTF8CutFont(fullFont, "cabbedvwxyz")
err = os.WriteFile(subFontFileStr, subFont, 0600)
if err == nil {
y := 24.0
pdf := document.New("P", "mm", "A4", "")
fontHt := 17.0
lineHt := pdf.PointConvert(fontHt)
write := func(format string, args ...any) {
pdf.SetXY(24.0, y)
pdf.Cell(200.0, lineHt, fmt.Sprintf(format, args...))
y += lineHt
}
writeSize := func(fileStr, labelStr string) {
var info os.FileInfo
var err error
info, err = os.Stat(fileStr)
if err == nil {
write("%6d: size of %s", info.Size(), labelStr)
}
}
pdf.AddPage()
pdf.AddUTF8Font("calligra", "", subFontFileStr)
pdf.SetFont("calligra", "", fontHt)
write("cabbed")
write("vwxyz")
pdf.SetFont("courier", "", fontHt)
writeSize(fullFontFileStr, filepath.ToSlash(filepath.Join("assets", "static", "font", "calligra.ttf")))
writeSize(subFontFileStr, subFontFileStr)
err = pdf.OutputFileAndClose(pdfFileStr)
_ = os.Remove(subFontFileStr)
}
}
example.Summary(err, pdfFileStr)
}
Output: Successfully generated assets/generated/pdf/Document_UTF8CutFont.pdf
func UnicodeTranslator ¶
UnicodeTranslator returns a function that can be used to translate, where possible, UTF-8 strings to a form that is compatible with the specified code page. The returned function accepts a string and returns a string.
r should read content lines for the code page of interest. Each line is made up of three whitespace-separated fields. The first begins with "!" and is followed by two hexadecimal digits that identify the glyph position in the code page of interest. The second field begins with "U+" and is followed by the Unicode code point value. The third is the glyph name. A number of these code page map files are packaged with gopdfkit in the font directory.
An error occurs only if a line is read that does not conform to the expected format. In this case, the returned function is valid but does not perform any rune translation.
func UnicodeTranslatorFromFile ¶
UnicodeTranslatorFromFile returns a function that can be used to translate, where possible, UTF-8 strings to a form that is compatible with the specified code page. See UnicodeTranslator for more details.
fileStr identifies a font descriptor file that maps glyph positions to names.
If an error occurs reading the file, the returned function is valid but does not perform any rune translation.
func ValidateFormDocumentHTML ¶
func ValidateFormDocumentHTML(form FormDocument) []string
ValidateFormDocumentHTML validates the canonical form HTML against the supported HTML subset.
Types ¶
type Attachment ¶
type Attachment struct {
// Content contains the bytes embedded in the PDF.
Content []byte
// Filename is the displayed name of the attachment.
Filename string
// Description is only displayed when using AddAttachmentAnnotation(),
// and might be modified by the PDF reader.
Description string
// MIMEType is written to the embedded file stream /Subtype. When empty,
// it is inferred from Filename and falls back to application/octet-stream.
MIMEType string
// AFRelationship describes why the file is associated with the document.
// Common PDF/A-4f values are Source, Data, Alternative, Supplement, and
// Unspecified. When empty, Data is used.
AFRelationship string
// contains filtered or unexported fields
}
Attachment defines content to include in the PDF in one of the following ways:
- associated with the document as a whole; see SetAttachments()
- accessible through a link anchored on a page; see AddAttachmentAnnotation()
type AttachmentBlock ¶
type AttachmentBlock struct {
Name string // Attachment filename.
MIMEType string // Attachment MIME type.
Description string // Attachment description.
Data []byte // Attachment bytes.
}
AttachmentBlock describes a PDF attachment that can be added during output.
type Block ¶
type Block interface {
DocumentBlockKind() BlockKind
}
Block is implemented by every shared document block.
func FormDocumentBlocks ¶
func FormDocumentBlocks(form FormDocument) []Block
FormDocumentBlocks converts a form into shared document blocks.
type BlockKind ¶
type BlockKind string
BlockKind identifies a shared layout block.
const ( // BlockKindParagraph identifies paragraph blocks. BlockKindParagraph BlockKind = "paragraph" // BlockKindHeading identifies heading blocks. BlockKindHeading BlockKind = "heading" // BlockKindList identifies list blocks. BlockKindList BlockKind = "list" // BlockKindTable identifies table blocks. BlockKindTable BlockKind = "table" // BlockKindImage identifies image blocks. BlockKindImage BlockKind = "image" // BlockKindSignatureRow identifies signature-row blocks. BlockKindSignatureRow BlockKind = "signature-row" // BlockKindMetadataGrid identifies metadata-grid blocks. BlockKindMetadataGrid BlockKind = "metadata-grid" // BlockKindQRVerification identifies QR-verification blocks. BlockKindQRVerification BlockKind = "qr-verification" // BlockKindNoteBox identifies note-box blocks. BlockKindNoteBox BlockKind = "note-box" // BlockKindSection identifies section blocks. BlockKindSection BlockKind = "section" // BlockKindClause identifies clause blocks. BlockKindClause BlockKind = "clause" // BlockKindPageBreak identifies explicit page-break blocks. BlockKindPageBreak BlockKind = "page-break" )
type BlockMeasurement ¶
type BlockMeasurement struct {
Kind BlockKind // Block kind measured.
Width float64 // Estimated block width.
Height float64 // Estimated full block height.
MinHeight float64 // Minimum height required to start rendering.
Splittable bool // Whether the block can split across pages.
KeepTogether bool // Whether the block prefers one page.
KeepWithNext bool // Whether the block should stay with the next one.
BreakBefore bool // Whether rendering requires a prior page break.
BreakAfter bool // Whether rendering requires a following page break.
ChildMeasures []BlockMeasurement // Measurements for nested child blocks.
}
BlockMeasurement is the estimated layout footprint of a block.
func MeasureBlock ¶
func MeasureBlock(ctx MeasureContext, block Block) BlockMeasurement
MeasureBlock estimates the layout footprint for one block.
func MeasureBlocks ¶
func MeasureBlocks(ctx MeasureContext, blocks []Block) []BlockMeasurement
MeasureBlocks estimates a sequence of blocks.
func (BlockMeasurement) CanStart ¶
func (m BlockMeasurement) CanStart(availableHeight float64) bool
CanStart reports whether the block can start in the available height.
func (BlockMeasurement) Fits ¶
func (m BlockMeasurement) Fits(availableHeight float64) bool
Fits reports whether the whole block fits in the available height.
func (BlockMeasurement) ShouldMoveToNextPage ¶
func (m BlockMeasurement) ShouldMoveToNextPage(availableHeight float64) bool
ShouldMoveToNextPage reports whether the block should move before drawing.
type BorderSide ¶
type BorderSide struct {
Width float64 // Border width in document units.
Style string // Border style name.
Color DocumentColor // Optional border color.
}
BorderSide describes one border edge.
type BorderStyle ¶
type BorderStyle struct {
Top BorderSide // Top border.
Right BorderSide // Right border.
Bottom BorderSide // Bottom border.
Left BorderSide // Left border.
}
BorderStyle stores a simple per-side border model.
type BoxStyle ¶
type BoxStyle struct {
Margin Spacing // Space outside the block.
Padding Spacing // Space inside the block.
Border BorderStyle // Per-side border settings.
BackgroundColor DocumentColor // Optional background color.
KeepTogether bool // Prefer not to split this block across pages.
KeepWithNext bool // Prefer to keep this block with the next one.
}
BoxStyle describes common block styling independent of a renderer.
type CSSColorType ¶
type CSSColorType struct {
R int // Red component, 0-255.
G int // Green component, 0-255.
B int // Blue component, 0-255.
Set bool // Whether a color value was explicitly parsed.
None bool // Whether the parsed paint value is "none".
}
CSSColorType describes a parsed CSS color or paint value.
type ClauseBlock ¶
type ClauseBlock struct {
Number string // Clause number or label.
Title string // Clause title.
Blocks []Block // Clause body blocks.
BreakBefore bool // Insert a page break before the clause.
BreakAfter bool // Insert a page break after the clause.
KeepTogether bool // Prefer to keep the clause on one page.
Box BoxStyle // Clause box style.
}
ClauseBlock represents a numbered or named clause in long-form documents.
func (ClauseBlock) DocumentBlockKind ¶
func (ClauseBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindClause.
type CompiledHTML ¶ added in v0.5.0
type CompiledHTML struct {
// contains filtered or unexported fields
}
CompiledHTML stores the reusable parse products for an HTML fragment. It is safe to reuse across documents as long as callers do not mutate values reachable through Tokens().
func CompileHTML ¶ added in v0.5.0
func CompileHTML(htmlStr string) (*CompiledHTML, error)
CompileHTML tokenizes an HTML fragment, parses CSS rules, records element boundaries, pre-parses tables, and pre-parses inline SVGs for repeated rendering.
func (*CompiledHTML) DebugDump ¶ added in v0.5.1
func (compiled *CompiledHTML) DebugDump() string
DebugDump returns a compact tree dump for diagnostics.
func (*CompiledHTML) RecoveryIssues ¶ added in v0.5.1
func (compiled *CompiledHTML) RecoveryIssues() []CompiledHTMLRecoveryIssue
RecoveryIssues returns malformed-fragment recovery decisions from compilation. The returned slice is a copy.
func (*CompiledHTML) Stats ¶ added in v0.5.1
func (compiled *CompiledHTML) Stats() CompiledHTMLStats
Stats returns diagnostics for the reusable parse products stored in the compiled HTML fragment.
func (*CompiledHTML) Tokens ¶ added in v0.5.0
func (compiled *CompiledHTML) Tokens() []HTMLSegmentType
Tokens returns the token stream used by the compiled HTML fragment.
type CompiledHTMLRecoveryIssue ¶ added in v0.5.1
CompiledHTMLRecoveryIssue describes one malformed-fragment recovery decision made while building the compiled node model.
type CompiledHTMLStats ¶ added in v0.5.1
type CompiledHTMLStats struct {
Tokens int
Nodes int
Tables int
Images int
InlineSVGs int
CSSRules int
Recovery int
MaxDepth int
CachedText int
CachedStyles int
}
CompiledHTMLStats summarizes reusable parse products in a compiled fragment.
type ComplianceMetadata ¶ added in v0.5.0
type ComplianceMetadata struct {
PDFA PDFAMode
PDFUA2 bool
Arlington bool
Lang string
Title string
Identifier string
}
ComplianceMetadata controls standards identifiers, catalog markers, and tagged-PDF output.
This API writes standards metadata and tagged-PDF structure support. It does not replace external PDF/A-4, PDF/UA-2, or Arlington PDF Model validation.
type ComplianceValidationIssue ¶ added in v0.5.0
type ComplianceValidationIssue struct {
Standard string
Severity ComplianceValidationSeverity
Rule string
Message string
Object string
}
ComplianceValidationIssue stores one finding from an external standards validator such as veraPDF, a PDF/UA checker, or the Arlington checker.
type ComplianceValidationReport ¶ added in v0.5.0
type ComplianceValidationReport struct {
Issues []ComplianceValidationIssue
}
ComplianceValidationReport stores external validation findings separately from Document generation errors.
func (*ComplianceValidationReport) Add ¶ added in v0.5.0
func (report *ComplianceValidationReport) Add(issue ComplianceValidationIssue)
Add appends one external validation issue to the report.
func (ComplianceValidationReport) Failed ¶ added in v0.5.0
func (report ComplianceValidationReport) Failed() bool
Failed reports whether any issue has error severity.
type ComplianceValidationSeverity ¶ added in v0.5.0
type ComplianceValidationSeverity string
ComplianceValidationSeverity classifies an external validator issue.
const ( // ComplianceValidationInfo is informational validator output. ComplianceValidationInfo ComplianceValidationSeverity = "info" // ComplianceValidationWarning is non-fatal validator output. ComplianceValidationWarning ComplianceValidationSeverity = "warning" // ComplianceValidationError is a failing validator finding. ComplianceValidationError ComplianceValidationSeverity = "error" )
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document represents a single PDF document under construction.
func New ¶
New returns a new Document instance. Its methods are subsequently called to produce a single PDF document.
orientationStr specifies the default page orientation. For portrait mode, specify "P" or "Portrait". For landscape mode, specify "L" or "Landscape". An empty string will be replaced with "P".
unitStr specifies the unit of length used in size parameters for elements other than fonts, which are always measured in points. Specify "pt" for point, "mm" for millimeter, "cm" for centimeter, or "in" for inch. An empty string will be replaced with "mm".
sizeStr specifies the page size. Acceptable values are "A3", "A4", "A5", "Letter", "Legal", or "Tabloid". An empty string will be replaced with "A4".
fontDirStr specifies the file system location in which font resources will be found. An empty string is replaced with ".". This argument only needs to reference an actual directory if a font other than one of the core fonts is used. The core fonts are "courier", "helvetica" (also called "arial"), "times", and "zapfdingbats" (also called "symbol").
func NewWithOptions ¶
NewWithOptions returns a new Document instance using explicit construction options. It is an alternative to New when the default page size must be set by width and height instead of a named page size.
func (*Document) AddAttachmentAnnotation ¶
func (f *Document) AddAttachmentAnnotation(a *Attachment, x, y, w, h float64)
AddAttachmentAnnotation puts a link on the current page over the rectangle defined by x, y, w, and h. This link points to the content defined in a, which is embedded in the document. This method does not draw anything; call a method such as Cell() or Rect() to indicate that a link is present. Requiring a pointer to an Attachment avoids unnecessary copies in the resulting PDF: attachments that point to the same data are included only once and shared among all links. Be aware that not all PDF readers support annotated attachments. See the AddAttachmentAnnotation example for a demonstration of this method.
Example ¶
package main
import (
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetFont("Arial", "", 12)
pdf.AddPage()
// Per page attachment
file, err := os.ReadFile(example.RepoFile("document", "grid.go"))
if err != nil {
pdf.SetError(err)
}
a := document.Attachment{Content: file, Filename: "grid.go", Description: "Some amazing code !"}
pdf.SetXY(5, 10)
pdf.Rect(2, 10, 50, 15, "D")
pdf.AddAttachmentAnnotation(&a, 2, 10, 50, 15)
pdf.Cell(50, 15, "A first link")
pdf.SetXY(5, 80)
pdf.Rect(2, 80, 50, 15, "D")
pdf.AddAttachmentAnnotation(&a, 2, 80, 50, 15)
pdf.Cell(50, 15, "A second link (no copy)")
fileStr := example.Filename("Document_FileAnnotations")
err = pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_FileAnnotations.pdf
func (*Document) AddFont ¶
AddFont imports a TrueType, OpenType or Type1 font and makes it available. It is necessary to generate a font definition file first with the fontmaker utility. You do not need to call this function for the core PDF fonts (courier, helvetica, times, zapfdingbats).
The JSON definition file (and the font file itself when embedding) must be present in the font directory. If it is not found, the error "Could not include font definition file" is set.
family specifies the font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font. This string is used to subsequently set the font with the SetFont method.
style specifies the font style. Acceptable values are (case insensitive) the empty string for regular style, "B" for bold, "I" for italic, or "BI" or "IB" for bold and italic combined.
fileStr specifies the base name with ".json" extension of the font definition file to be added. The file will be loaded from the font directory specified in the call to New() or SetFontLocation().
Example ¶
ExampleDocument_AddFont demonstrates the use of a non-standard font.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", example.FontDir())
pdf.AddFont("Calligrapher", "", "calligra.json")
pdf.AddPage()
pdf.SetFont("Calligrapher", "", 35)
pdf.Cell(0, 10, "Enjoy new fonts with Document!")
fileStr := example.Filename("Document_AddFont")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_AddFont.pdf
func (*Document) AddFontFromBytes ¶
AddFontFromBytes imports a TrueType, OpenType or Type1 font from static bytes within the executable and makes it available for use in the generated document.
family specifies the font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font. This string is used to subsequently set the font with the SetFont method.
style specifies the font style. Acceptable values are (case insensitive) the empty string for regular style, "B" for bold, "I" for italic, or "BI" or "IB" for bold and italic combined.
jsonFileBytes contains all bytes of the JSON definition file.
zFileBytes contains all bytes of the zlib-compressed font file.
Example ¶
ExampleDocument_AddFontFromBytes demonstrate how to use embedded fonts from byte array
package main
import (
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
jsonBytes, err := os.ReadFile(example.FontFile("calligra.json"))
var zBytes []byte
if err == nil {
zBytes, err = os.ReadFile(example.FontFile("calligra.z"))
}
if err == nil {
pdf.AddFontFromBytes("calligra", "", jsonBytes, zBytes)
pdf.SetFont("calligra", "", 16)
pdf.Cell(40, 10, "Hello World With Embedded Font!")
}
fileStr := example.Filename("Document_EmbeddedFont")
if err == nil {
err = pdf.OutputFileAndClose(fileStr)
}
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_EmbeddedFont.pdf
func (*Document) AddFontFromReader ¶
AddFontFromReader imports a TrueType, OpenType or Type1 font and makes it available using a reader that satisfies the io.Reader interface. See AddFont() for details about familyStr and styleStr.
func (*Document) AddLayer ¶
AddLayer defines a layer that can be shown or hidden when the document is displayed. name specifies the layer name that the document reader will display in the layer list. visible specifies whether the layer will be initially visible. The returned integer ID is used in a call to BeginLayer.
Example ¶
ExampleDocument_AddLayer demonstrates document layers. The initial visibility of a layer is specified with the second parameter to AddLayer(). The layer list displayed by the document reader allows layer visibility to be controlled interactively.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 15)
pdf.Write(8, "This line doesn't belong to any layer.\n")
// Define layers
l1 := pdf.AddLayer("Layer 1", true)
l2 := pdf.AddLayer("Layer 2", true)
// Open layer pane in PDF viewer
pdf.OpenLayerPane()
// First layer
pdf.BeginLayer(l1)
pdf.Write(8, "This line belongs to layer 1.\n")
pdf.EndLayer()
// Second layer
pdf.BeginLayer(l2)
pdf.Write(8, "This line belongs to layer 2.\n")
pdf.EndLayer()
// First layer again
pdf.BeginLayer(l1)
pdf.Write(8, "This line belongs to layer 1 again.\n")
pdf.EndLayer()
fileStr := example.Filename("Document_AddLayer")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_AddLayer.pdf
func (*Document) AddLink ¶
AddLink creates a new internal link and returns its identifier. An internal link is a clickable area that points to another place within the document. The identifier can then be passed to Cell, Write, ImageOptions, or Link. The destination is defined with SetLink.
func (*Document) AddPage ¶
func (f *Document) AddPage()
AddPage adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer. Then the page is added, the current position set to the top-left corner according to the left and top margins, and Header() is called to display the header.
The font which was set before calling is automatically restored. There is no need to call SetFont() again if you want to continue with the same font. The same is true for colors and line width.
The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
See AddPageFormat() for a version of this method that allows the page size and orientation to be different than the default.
Example ¶
ExampleDocument_AddPage demonsrates the generation of headers, footers and page breaks.
package main
import (
"fmt"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetTopMargin(30)
pdf.SetHeaderFuncMode(func() {
pdf.ImageOptions(example.ImageFile("logo.png"), 10, 6, 30, 0, false, document.ImageOptions{}, 0, "")
pdf.SetY(5)
pdf.SetFont("Arial", "B", 15)
pdf.Cell(80, 0, "")
pdf.CellFormat(30, 10, "Title", "1", 0, "C", false, 0, "")
pdf.Ln(20)
}, true)
pdf.SetFooterFunc(func() {
pdf.SetY(-15)
pdf.SetFont("Arial", "I", 8)
pdf.CellFormat(0, 10, fmt.Sprintf("Page %d/{nb}", pdf.PageNo()),
"", 0, "C", false, 0, "")
})
pdf.AliasNbPages("")
pdf.AddPage()
pdf.SetFont("Times", "", 12)
for j := 1; j <= 40; j++ {
pdf.CellFormat(0, 10, fmt.Sprintf("Printing line number %d", j),
"", 1, "", false, 0, "")
}
fileStr := example.Filename("Document_AddPage")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_AddPage.pdf
func (*Document) AddPageFormat ¶
AddPageFormat adds a new page with non-default orientation or size. See AddPage() for more details.
See New() for a description of orientationStr.
size specifies the size of the new page in the units established in New().
The PageSize() example demonstrates this method.
func (*Document) AddPageFormatRotation ¶
AddPageFormatRotation adds a new page with non-default orientation, size, or page dictionary rotation. The rotation must be a multiple of 90 degrees.
func (*Document) AddPageRotation ¶
AddPageRotation adds a new page with the default orientation and size and sets its page dictionary rotation. The rotation must be a multiple of 90 degrees.
func (*Document) AddSpotColor ¶
AddSpotColor adds an ink-based CMYK color to the document and associates it with the specified name. The individual components specify percentages ranging from 0 to 100. Values above this range are quietly capped to 100. An error occurs if the specified name is already associated with a color.
Example ¶
ExampleDocument_AddSpotColor demonstrates spot color use
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.AddSpotColor("PANTONE 145 CVC", 0, 42, 100, 25)
pdf.AddPage()
pdf.SetFillSpotColor("PANTONE 145 CVC", 90)
pdf.Rect(80, 40, 50, 50, "F")
fileStr := example.Filename("Document_AddSpotColor")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_AddSpotColor.pdf
func (*Document) AddTextWatermark ¶
AddTextWatermark draws a centered, translucent text watermark on the current page.
func (*Document) AddUTF8Font ¶
AddUTF8Font imports a TrueType font with UTF-8 symbols and makes it available. It is necessary to generate a font definition file first with the fontmaker utility. You do not need to call this function for the core PDF fonts (courier, helvetica, times, zapfdingbats).
The JSON definition file (and the font file itself when embedding) must be present in the font directory. If it is not found, the error "Could not include font definition file" is set.
family specifies the font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font. This string is used to subsequently set the font with the SetFont method.
style specifies the font style. Acceptable values are (case insensitive) the empty string for regular style, "B" for bold, "I" for italic, or "BI" or "IB" for bold and italic combined.
fileStr specifies the base name with ".ttf" or ".otf" extension of the font file to be added. OpenType files with TrueType outlines are supported. CFF OpenType files are supported by font.Make/AddFont for single-byte encodings, not by this UTF-8 subsetting path.
Example ¶
ExampleDocument_AddUTF8Font demonstrates how use the font with utf-8 mode
package main
import (
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
var fileStr string
var txtStr []byte
var err error
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.AddUTF8Font("dejavu", "", example.FontFile("DejaVuSansCondensed.ttf"))
pdf.AddUTF8Font("dejavu", "B", example.FontFile("DejaVuSansCondensed-Bold.ttf"))
pdf.AddUTF8Font("dejavu", "I", example.FontFile("DejaVuSansCondensed-Oblique.ttf"))
pdf.AddUTF8Font("dejavu", "BI", example.FontFile("DejaVuSansCondensed-BoldOblique.ttf"))
fileStr = example.Filename("Document_AddUTF8Font")
txtStr, err = os.ReadFile(example.TextFile("utf-8test.txt"))
if err == nil {
pdf.SetFont("dejavu", "B", 17)
pdf.MultiCell(100, 8, "Text in different languages :", "", "C", false)
pdf.SetFont("dejavu", "", 14)
pdf.MultiCell(100, 5, string(txtStr), "", "C", false)
pdf.Ln(15)
txtStr, err = os.ReadFile(example.TextFile("utf-8test2.txt"))
if err == nil {
pdf.SetFont("dejavu", "BI", 17)
pdf.MultiCell(100, 8, "Greek text with alignStr = \"J\":", "", "C", false)
pdf.SetFont("dejavu", "I", 14)
pdf.MultiCell(100, 5, string(txtStr), "", "J", false)
err = pdf.OutputFileAndClose(fileStr)
}
}
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_AddUTF8Font.pdf
func (*Document) AddUTF8FontFromBytes ¶
AddUTF8FontFromBytes imports a TrueType font with UTF-8 symbols from static bytes within the executable and makes it available for use in the generated document.
family specifies the font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font. This string is used to subsequently set the font with the SetFont method.
style specifies the font style. Acceptable values are (case insensitive) the empty string for regular style, "B" for bold, "I" for italic, or "BI" or "IB" for bold and italic combined.
utf8Bytes contains all bytes of the UTF-8 font file.
func (*Document) AddUTF8FontFromCache ¶
AddUTF8FontFromCache imports a cached UTF-8 TrueType font into this document.
func (*Document) AliasNbPages ¶
AliasNbPages defines an alias for the total number of pages. It will be substituted as the document is closed. An empty string is replaced with the string "{nb}".
See the example for AddPage for a demonstration of this method.
func (*Document) Arc ¶
Arc draws an elliptical arc centered at point (x, y). rx and ry specify its horizontal and vertical radii.
degRotate specifies the angle that the arc will be rotated. degStart and degEnd specify the starting and ending angle of the arc. All angles are specified in degrees and measured counter-clockwise from the 3 o'clock position.
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color, line width, and cap style centered on the arc's path. Filling uses the current fill color.
The Circle() example demonstrates this method.
func (*Document) ArcTo ¶
ArcTo draws an elliptical arc centered at point (x, y). rx and ry specify its horizontal and vertical radii. If the start of the arc is not at the current position, a connecting line will be drawn.
degRotate specifies the angle that the arc will be rotated. degStart and degEnd specify the starting and ending angle of the arc. All angles are specified in degrees and measured counter-clockwise from the 3 o'clock position.
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color, line width, and cap style centered on the arc's path. Filling uses the current fill color.
The MoveTo() example demonstrates this method.
func (*Document) BeginArtifact ¶ added in v0.5.0
func (f *Document) BeginArtifact()
BeginArtifact marks subsequent low-level drawing operations as artifact content until EndArtifact is called.
func (*Document) BeginLayer ¶
BeginLayer is called to begin adding content to the specified layer. All content added to the page between BeginLayer and EndLayer is added to the layer specified by id. See AddLayer for more details.
func (*Document) BeginStructure ¶ added in v0.5.0
BeginStructure starts a tagged PDF structure container. Containers define reading order and semantic grouping for subsequent marked content.
func (*Document) Beziergon ¶
Beziergon draws a closed figure defined by a series of cubic Bézier curve segments. The first point in the slice defines the starting point of the figure. Each three following points p1, p2, p3 represent a curve segment to the point p3 using p1 and p2 as the Bézier control points.
The x and y fields of the points use the units established in New().
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color and line width centered on the path's perimeter. Filling uses the current fill color.
Example ¶
ExampleDocument_Beziergon demonstrates the Beziergon function.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const (
margin = 10
wd = 210
unit = (wd - 2*margin) / 6
ht = 297
fontSize = 15
msgStr = `Demonstration of Beziergon function`
coefficient = 0.6
delta = coefficient * unit
ln = fontSize * 25.4 / 72
offsetX = (wd - 4*unit) / 2.0
offsetY = offsetX + 2*ln
)
srcList := []document.Point{
{X: 0, Y: 0},
{X: 1, Y: 0},
{X: 1, Y: 1},
{X: 2, Y: 1},
{X: 2, Y: 2},
{X: 3, Y: 2},
{X: 3, Y: 3},
{X: 4, Y: 3},
{X: 4, Y: 4},
{X: 1, Y: 4},
{X: 1, Y: 3},
{X: 0, Y: 3},
}
ctrlList := []document.Point{
{X: 1, Y: -1},
{X: 1, Y: 1},
{X: 1, Y: 1},
{X: 1, Y: 1},
{X: 1, Y: 1},
{X: 1, Y: 1},
{X: 1, Y: 1},
{X: 1, Y: 1},
{X: -1, Y: 1},
{X: -1, Y: -1},
{X: -1, Y: -1},
{X: -1, Y: -1},
}
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Helvetica", "", fontSize)
for j, src := range srcList {
srcList[j].X = offsetX + src.X*unit
srcList[j].Y = offsetY + src.Y*unit
}
for j, ctrl := range ctrlList {
ctrlList[j].X = ctrl.X * delta
ctrlList[j].Y = ctrl.Y * delta
}
jPrev := len(srcList) - 1
srcPrev := srcList[jPrev]
curveList := []document.Point{srcPrev} // point [, control 0, control 1, point]*
control := func(x, y float64) {
curveList = append(curveList, document.Point{X: x, Y: y})
}
for j, src := range srcList {
ctrl := ctrlList[jPrev]
control(srcPrev.X+ctrl.X, srcPrev.Y+ctrl.Y) // Control 0
ctrl = ctrlList[j]
control(src.X-ctrl.X, src.Y-ctrl.Y) // Control 1
curveList = append(curveList, src) // Destination
jPrev = j
srcPrev = src
}
pdf.MultiCell(wd-margin-margin, ln, msgStr, "", "C", false)
pdf.SetDashPattern([]float64{0.8, 0.8}, 0)
pdf.SetDrawColor(160, 160, 160)
pdf.Polygon(srcList, "D")
pdf.SetDashPattern([]float64{}, 0)
pdf.SetDrawColor(64, 64, 128)
pdf.SetLineWidth(pdf.GetLineWidth() * 3)
pdf.Beziergon(curveList, "D")
fileStr := example.Filename("Document_Beziergon")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_Beziergon.pdf
func (*Document) Bookmark ¶
Bookmark sets a bookmark that will be displayed in a sidebar outline. txtStr is the title of the bookmark. level specifies the level of the bookmark in the outline; 0 is the top level, 1 is just below, and so on. y specifies the vertical position of the bookmark destination in the current page; -1 indicates the current position.
Example ¶
ExampleDocument_Bookmark demonstrates the Bookmark method.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 15)
pdf.Bookmark("Page 1", 0, 0)
pdf.Bookmark("Paragraph 1", 1, -1)
pdf.Cell(0, 6, "Paragraph 1")
pdf.Ln(50)
pdf.Bookmark("Paragraph 2", 1, -1)
pdf.Cell(0, 6, "Paragraph 2")
pdf.AddPage()
pdf.Bookmark("Page 2", 0, 0)
pdf.Bookmark("Paragraph 3", 1, -1)
pdf.Cell(0, 6, "Paragraph 3")
fileStr := example.Filename("Document_Bookmark")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_Bookmark.pdf
func (*Document) Cell ¶
Cell is a simpler version of CellFormat with no fill, border, links or special alignment. The Cell_strikeout() example demonstrates this method.
Example (Strikeout) ¶
ExampleDocument_Cell_strikeout demonstrates striked-out text
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "") // 210mm x 297mm
pdf.AddPage()
for fontSize := 4; fontSize < 40; fontSize += 10 {
pdf.SetFont("Arial", "S", float64(fontSize))
pdf.SetXY(0, float64(fontSize))
pdf.Cell(40, 10, "Hello World")
}
fileStr := example.Filename("Document_Cell_strikeout")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_Cell_strikeout.pdf
func (*Document) CellFormat ¶
func (f *Document) CellFormat(w, h float64, txtStr, borderStr string, ln int, alignStr string, fill bool, link int, linkStr string)
CellFormat prints a rectangular cell with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.
An error will be returned if a call to SetFont() has not already taken place before this method is called.
If automatic page breaking is enabled and the cell goes beyond the limit, a page break is performed before output.
w and h specify the width and height of the cell. If w is 0, the cell extends up to the right margin. Specifying 0 for h will result in no output, but the current position will be advanced by w.
txtStr specifies the text to display.
borderStr specifies how the cell border will be drawn. An empty string indicates no border, "1" indicates a full border, and one or more of "L", "T", "R" and "B" indicate the left, top, right and bottom sides of the border.
ln indicates where the current position should go after the call. Possible values are 0 (to the right), 1 (to the beginning of the next line), and 2 (below). Using 1 is equivalent to using 0 and calling Ln() immediately after.
alignStr specifies how the text is to be positioned within the cell. Horizontal alignment is controlled by including "L", "C" or "R" (left, center, right) in alignStr. Vertical alignment is controlled by including "T", "M", "B" or "A" (top, middle, bottom, baseline) in alignStr. The default alignment is left middle.
fill is true to paint the cell background or false to leave it transparent.
link is the identifier returned by AddLink() or 0 for no internal link.
linkStr is a target URL or empty for no external link. A non-zero value for link takes precedence over linkStr.
Example (Align) ¶
ExampleDocument_CellFormat_align demonstrates Stefan Schroeder's code to control vertical alignment.
package main
import (
"bytes"
"fmt"
"io"
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
type fontResourceType struct {
}
func (f fontResourceType) Open(name string) (rdr io.Reader, err error) {
var buf []byte
buf, err = os.ReadFile(example.FontFile(name))
if err == nil {
rdr = bytes.NewReader(buf)
fmt.Printf("Generalized font loader reading %s\n", name)
}
return
}
func main() {
type recType struct {
align, txt string
}
recList := []recType{
{"TL", "top left"},
{"TC", "top center"},
{"TR", "top right"},
{"LM", "middle left"},
{"CM", "middle center"},
{"RM", "middle right"},
{"BL", "bottom left"},
{"BC", "bottom center"},
{"BR", "bottom right"},
}
recListBaseline := []recType{
{"AL", "baseline left"},
{"AC", "baseline center"},
{"AR", "baseline right"},
}
var formatRect = func(pdf *document.Document, recList []recType) {
linkStr := ""
for range 2 {
pdf.AddPage()
pdf.SetMargins(10, 10, 10)
pdf.SetAutoPageBreak(false, 0)
borderStr := "1"
for _, rec := range recList {
pdf.SetXY(20, 20)
pdf.CellFormat(170, 257, rec.txt, borderStr, 0, rec.align, false, 0, linkStr)
borderStr = ""
}
linkStr = "https://github.com/cssbruno/gopdfkit"
}
}
pdf := document.New("P", "mm", "A4", "") // A4 210.0 x 297.0
pdf.SetFont("Helvetica", "", 16)
formatRect(pdf, recList)
formatRect(pdf, recListBaseline)
var fr fontResourceType
pdf.SetFontLoader(fr)
pdf.AddFont("Calligrapher", "", "calligra.json")
pdf.SetFont("Calligrapher", "", 16)
formatRect(pdf, recListBaseline)
fileStr := example.Filename("Document_CellFormat_align")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Generalized font loader reading calligra.json Generalized font loader reading calligra.z Successfully generated assets/generated/pdf/Document_CellFormat_align.pdf
Example (Codepage) ¶
ExampleDocument_CellFormat_codepage demonstrates the automatic conversion of UTF-8 strings to an 8-bit font encoding.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", example.FontDir()) // A4 210.0 x 297.0
// See documentation for details on how to generate fonts
pdf.AddFont("Helvetica-1251", "", "helvetica_1251.json")
pdf.AddFont("Helvetica-1253", "", "helvetica_1253.json")
fontSize := 16.0
pdf.SetFont("Helvetica", "", fontSize)
ht := pdf.PointConvert(fontSize)
tr := pdf.UnicodeTranslatorFromDescriptor("") // "" defaults to "cp1252"
write := func(str string) {
// pdf.CellFormat(190, ht, tr(str), "", 1, "C", false, 0, "")
pdf.MultiCell(190, ht, tr(str), "", "C", false)
pdf.Ln(ht)
}
pdf.AddPage()
str := `Document provides a translator that will convert any UTF-8 code point ` +
`that is present in the specified code page.`
pdf.MultiCell(190, ht, str, "", "L", false)
pdf.Ln(2 * ht)
write("Voix ambiguë d'un cœur qui au zéphyr préfère les jattes de kiwi.")
write("Falsches Üben von Xylophonmusik quält jeden größeren Zwerg.")
write("Heizölrückstoßabdämpfung")
write("Forårsjævndøgn / Efterårsjævndøgn")
write("À noite, vovô Kowalsky vê o ímã cair no pé do pingüim queixoso e vovó" +
"põe açúcar no chá de tâmaras do jabuti feliz.")
pdf.SetFont("Helvetica-1251", "", fontSize) // Name matches one specified in AddFont()
tr = pdf.UnicodeTranslatorFromDescriptor("cp1251")
write("Съешь же ещё этих мягких французских булок, да выпей чаю.")
pdf.SetFont("Helvetica-1253", "", fontSize)
tr = pdf.UnicodeTranslatorFromDescriptor("cp1253")
write("Θέλει αρετή και τόλμη η ελευθερία. (Ανδρέας Κάλβος)")
fileStr := example.Filename("Document_CellFormat_codepage")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_CellFormat_codepage.pdf
Example (Codepageescape) ¶
ExampleDocument_CellFormat_codepageescape demonstrates the use of characters in the high range of the Windows-1252 code page (gofdpf default). See the example for CellFormat (4) for a way to do this automatically.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "") // A4 210.0 x 297.0
fontSize := 16.0
pdf.SetFont("Helvetica", "", fontSize)
ht := pdf.PointConvert(fontSize)
write := func(str string) {
pdf.CellFormat(190, ht, str, "", 1, "C", false, 0, "")
pdf.Ln(ht)
}
pdf.AddPage()
htmlStr := `Until gopdfkit supports UTF-8 encoded source text, source text needs ` +
`to be specified with all special characters escaped to match the code page ` +
`layout of the currently selected font. By default, gofdpf uses code page 1252.` +
` See <a href="http://en.wikipedia.org/wiki/Windows-1252">Wikipedia</a> for ` +
`a table of this layout.`
html := pdf.HTMLNew()
html.Write(ht, htmlStr)
pdf.Ln(2 * ht)
write("Voix ambigu\xeb d'un c\x9cur qui au z\xe9phyr pr\xe9f\xe8re les jattes de kiwi.")
write("Falsches \xdcben von Xylophonmusik qu\xe4lt jeden gr\xf6\xdferen Zwerg.")
write("Heiz\xf6lr\xfccksto\xdfabd\xe4mpfung")
write("For\xe5rsj\xe6vnd\xf8gn / Efter\xe5rsj\xe6vnd\xf8gn")
fileStr := example.Filename("Document_CellFormat_codepageescape")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_CellFormat_codepageescape.pdf
Example (Tables) ¶
ExampleDocument_CellFormat_tables demonstrates various table styles.
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func init() {
cleanup()
}
func cleanup() {
_ = filepath.Walk(example.PdfDir(),
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil {
return nil
}
if info.Mode().IsRegular() {
if len(path) > 3 {
if path[len(path)-4:] == ".pdf" {
_ = os.Remove(path)
}
}
}
return nil
})
}
// strDelimit converts 'ABCDEFG' to, for example, 'A,BCD,EFG'
func strDelimit(str string, sepstr string, sepcount int) string {
pos := len(str) - sepcount
for pos > 0 {
str = str[:pos] + sepstr + str[pos:]
pos -= sepcount
}
return str
}
func main() {
pdf := document.New("P", "mm", "A4", "")
type countryType struct {
nameStr, capitalStr, areaStr, popStr string
}
countryList := make([]countryType, 0, 8)
header := []string{"Country", "Capital", "Area (sq km)", "Pop. (thousands)"}
loadData := func(fileStr string) {
fl, err := os.Open(fileStr)
if err == nil {
scanner := bufio.NewScanner(fl)
var c countryType
for scanner.Scan() {
// Austria;Vienna;83859;8075
lineStr := scanner.Text()
list := strings.Split(lineStr, ";")
if len(list) == 4 {
c.nameStr = list[0]
c.capitalStr = list[1]
c.areaStr = list[2]
c.popStr = list[3]
countryList = append(countryList, c)
} else {
err = fmt.Errorf("error tokenizing %s", lineStr)
}
}
_ = fl.Close()
if len(countryList) == 0 {
err = fmt.Errorf("error loading data from %s", fileStr)
}
}
if err != nil {
pdf.SetError(err)
}
}
// Simple table
basicTable := func() {
left := (210.0 - 4*40) / 2
pdf.SetX(left)
for _, str := range header {
pdf.CellFormat(40, 7, str, "1", 0, "", false, 0, "")
}
pdf.Ln(-1)
for _, c := range countryList {
pdf.SetX(left)
pdf.CellFormat(40, 6, c.nameStr, "1", 0, "", false, 0, "")
pdf.CellFormat(40, 6, c.capitalStr, "1", 0, "", false, 0, "")
pdf.CellFormat(40, 6, c.areaStr, "1", 0, "", false, 0, "")
pdf.CellFormat(40, 6, c.popStr, "1", 0, "", false, 0, "")
pdf.Ln(-1)
}
}
// Better table
improvedTable := func() {
// Column widths
w := []float64{40.0, 35.0, 40.0, 45.0}
wSum := 0.0
for _, v := range w {
wSum += v
}
left := (210 - wSum) / 2
// Header
pdf.SetX(left)
for j, str := range header {
pdf.CellFormat(w[j], 7, str, "1", 0, "C", false, 0, "")
}
pdf.Ln(-1)
// Data
for _, c := range countryList {
pdf.SetX(left)
pdf.CellFormat(w[0], 6, c.nameStr, "LR", 0, "", false, 0, "")
pdf.CellFormat(w[1], 6, c.capitalStr, "LR", 0, "", false, 0, "")
pdf.CellFormat(w[2], 6, strDelimit(c.areaStr, ",", 3),
"LR", 0, "R", false, 0, "")
pdf.CellFormat(w[3], 6, strDelimit(c.popStr, ",", 3),
"LR", 0, "R", false, 0, "")
pdf.Ln(-1)
}
pdf.SetX(left)
pdf.CellFormat(wSum, 0, "", "T", 0, "", false, 0, "")
}
// Colored table
fancyTable := func() {
// Colors, line width and bold font
pdf.SetFillColor(255, 0, 0)
pdf.SetTextColor(255, 255, 255)
pdf.SetDrawColor(128, 0, 0)
pdf.SetLineWidth(.3)
pdf.SetFont("", "B", 0)
// Header
w := []float64{40, 35, 40, 45}
wSum := 0.0
for _, v := range w {
wSum += v
}
left := (210 - wSum) / 2
pdf.SetX(left)
for j, str := range header {
pdf.CellFormat(w[j], 7, str, "1", 0, "C", true, 0, "")
}
pdf.Ln(-1)
// Color and font restoration
pdf.SetFillColor(224, 235, 255)
pdf.SetTextColor(0, 0, 0)
pdf.SetFont("", "", 0)
// Data
fill := false
for _, c := range countryList {
pdf.SetX(left)
pdf.CellFormat(w[0], 6, c.nameStr, "LR", 0, "", fill, 0, "")
pdf.CellFormat(w[1], 6, c.capitalStr, "LR", 0, "", fill, 0, "")
pdf.CellFormat(w[2], 6, strDelimit(c.areaStr, ",", 3),
"LR", 0, "R", fill, 0, "")
pdf.CellFormat(w[3], 6, strDelimit(c.popStr, ",", 3),
"LR", 0, "R", fill, 0, "")
pdf.Ln(-1)
fill = !fill
}
pdf.SetX(left)
pdf.CellFormat(wSum, 0, "", "T", 0, "", false, 0, "")
}
loadData(example.TextFile("countries.txt"))
pdf.SetFont("Arial", "", 14)
pdf.AddPage()
basicTable()
pdf.AddPage()
improvedTable()
pdf.AddPage()
fancyTable()
fileStr := example.Filename("Document_CellFormat_tables")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_CellFormat_tables.pdf
func (*Document) Cellf ¶
Cellf is a simpler printf-style version of CellFormat with no fill, border, links or special alignment. See documentation for the fmt package for details on fmtStr and args.
func (*Document) Circle ¶
Circle draws a circle centered on point (x, y) with radius r.
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color and line width centered on the circle's perimeter. Filling uses the current fill color.
Example ¶
ExampleDocument_Circle demonstrates the construction of various geometric figures,
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const (
thin = 0.2
thick = 3.0
)
pdf := document.New("", "", "", "")
pdf.SetFont("Helvetica", "", 12)
pdf.SetFillColor(200, 200, 220)
pdf.AddPage()
y := 15.0
pdf.Text(10, y, "Circles")
pdf.SetFillColor(200, 200, 220)
pdf.SetLineWidth(thin)
pdf.Circle(20, y+15, 10, "D")
pdf.Circle(45, y+15, 10, "F")
pdf.Circle(70, y+15, 10, "FD")
pdf.SetLineWidth(thick)
pdf.Circle(95, y+15, 10, "FD")
pdf.SetLineWidth(thin)
y += 40.0
pdf.Text(10, y, "Ellipses")
pdf.SetFillColor(220, 200, 200)
pdf.Ellipse(30, y+15, 20, 10, 0, "D")
pdf.Ellipse(75, y+15, 20, 10, 0, "F")
pdf.Ellipse(120, y+15, 20, 10, 0, "FD")
pdf.SetLineWidth(thick)
pdf.Ellipse(165, y+15, 20, 10, 0, "FD")
pdf.SetLineWidth(thin)
y += 40.0
pdf.Text(10, y, "Curves (quadratic)")
pdf.SetFillColor(220, 220, 200)
pdf.Curve(10, y+30, 15, y-20, 40, y+30, "D")
pdf.Curve(45, y+30, 50, y-20, 75, y+30, "F")
pdf.Curve(80, y+30, 85, y-20, 110, y+30, "FD")
pdf.SetLineWidth(thick)
pdf.Curve(115, y+30, 120, y-20, 145, y+30, "FD")
pdf.SetLineCapStyle("round")
pdf.Curve(150, y+30, 155, y-20, 180, y+30, "FD")
pdf.SetLineWidth(thin)
pdf.SetLineCapStyle("butt")
y += 40.0
pdf.Text(10, y, "Curves (cubic)")
pdf.SetFillColor(220, 200, 220)
pdf.CurveBezierCubic(10, y+30, 15, y-20, 10, y+30, 40, y+30, "D")
pdf.CurveBezierCubic(45, y+30, 50, y-20, 45, y+30, 75, y+30, "F")
pdf.CurveBezierCubic(80, y+30, 85, y-20, 80, y+30, 110, y+30, "FD")
pdf.SetLineWidth(thick)
pdf.CurveBezierCubic(115, y+30, 120, y-20, 115, y+30, 145, y+30, "FD")
pdf.SetLineCapStyle("round")
pdf.CurveBezierCubic(150, y+30, 155, y-20, 150, y+30, 180, y+30, "FD")
pdf.SetLineWidth(thin)
pdf.SetLineCapStyle("butt")
y += 40.0
pdf.Text(10, y, "Arcs")
pdf.SetFillColor(200, 220, 220)
pdf.SetLineWidth(thick)
pdf.Arc(45, y+35, 20, 10, 0, 0, 180, "FD")
pdf.SetLineWidth(thin)
pdf.Arc(45, y+35, 25, 15, 0, 90, 270, "D")
pdf.SetLineWidth(thick)
pdf.Arc(45, y+35, 30, 20, 0, 0, 360, "D")
pdf.SetLineCapStyle("round")
pdf.Arc(135, y+35, 20, 10, 135, 0, 180, "FD")
pdf.SetLineWidth(thin)
pdf.Arc(135, y+35, 25, 15, 135, 90, 270, "D")
pdf.SetLineWidth(thick)
pdf.Arc(135, y+35, 30, 20, 135, 0, 360, "D")
pdf.SetLineWidth(thin)
pdf.SetLineCapStyle("butt")
fileStr := example.Filename("Document_Circle_figures")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_Circle_figures.pdf
func (*Document) ClearError ¶
func (f *Document) ClearError()
ClearError unsets the internal Document error. This method should be used with care, as an internal error condition usually indicates an unrecoverable problem with the generation of a document. It is intended to deal with cases in which an error is used to select an alternate form of the document.
func (*Document) ClipCircle ¶
ClipCircle begins a circular clipping operation. The circle is centered at (x, y) and has radius r. outline is true to draw a border with the current draw color and line width centered on the circle's perimeter. Only the outer half of the border will be shown. After calling this method, all rendering operations (for example, ImageOptions(), LinearGradient(), etc.) will be clipped by the specified circle. Call ClipEnd() to restore unclipped operations.
The ClipText() example demonstrates this method.
func (*Document) ClipEllipse ¶
ClipEllipse begins an elliptical clipping operation. The ellipse is centered at (x, y). Its horizontal and vertical radii are specified by rx and ry. outline is true to draw a border with the current draw color and line width centered on the ellipse's perimeter. Only the outer half of the border will be shown. After calling this method, all rendering operations (for example, ImageOptions(), LinearGradient(), etc.) will be clipped by the specified ellipse. Call ClipEnd() to restore unclipped operations.
This ClipText() example demonstrates this method.
func (*Document) ClipEnd ¶
func (f *Document) ClipEnd()
ClipEnd ends a clipping operation that was started with a call to ClipRect(), ClipRoundedRect(), ClipText(), ClipEllipse(), ClipCircle() or ClipPolygon(). Clipping operations can be nested. The document cannot be output successfully while a clipping operation is active.
The ClipText() example demonstrates this method.
func (*Document) ClipPolygon ¶
ClipPolygon begins a clipping operation within a polygon. The figure is defined by a series of vertices specified by points. The x and y fields of the points use the units established in New(). The last point in the slice will be implicitly joined to the first to close the polygon. outline is true to draw a border with the current draw color and line width centered on the polygon's perimeter. Only the outer half of the border will be shown. After calling this method, all rendering operations (for example, ImageOptions(), LinearGradient(), etc.) will be clipped by the specified polygon. Call ClipEnd() to restore unclipped operations.
The ClipText() example demonstrates this method.
func (*Document) ClipRect ¶
ClipRect begins a rectangular clipping operation. The rectangle has width w and height h. Its upper-left corner is positioned at (x, y). outline is true to draw a border with the current draw color and line width centered on the rectangle's perimeter. Only the outer half of the border will be shown. After calling this method, all rendering operations (for example, ImageOptions(), LinearGradient(), etc.) will be clipped by the specified rectangle. Call ClipEnd() to restore unclipped operations.
This ClipText() example demonstrates this method.
Example ¶
This example demonstrate Clipped table cells
package main
import (
"fmt"
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
marginCell := 2. // margin of top/bottom of cell
pdf := document.New("P", "mm", "A4", "")
pdf.SetFont("Arial", "", 12)
pdf.AddPage()
pagew, pageh := pdf.GetPageSize()
mleft, mright, _, mbottom := pdf.GetMargins()
cols := []float64{60, 100, pagew - mleft - mright - 100 - 60}
rows := [][]string{}
for i := 1; i <= 50; i++ {
word := fmt.Sprintf("%d:%s", i, strings.Repeat("A", i%100))
rows = append(rows, []string{word, word, word})
}
for _, row := range rows {
_, lineHt := pdf.GetFontSize()
height := lineHt + marginCell
x, y := pdf.GetXY()
// add a new page if the height of the row doesn't fit on the page
if y+height >= pageh-mbottom {
pdf.AddPage()
x, y = pdf.GetXY()
}
for i, txt := range row {
width := cols[i]
pdf.Rect(x, y, width, height, "")
pdf.ClipRect(x, y, width, height, false)
pdf.Cell(width, height, txt)
pdf.ClipEnd()
x += width
}
pdf.Ln(-1)
}
fileStr := example.Filename("Document_ClippedTableCells")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_ClippedTableCells.pdf
func (*Document) ClipRoundedRect ¶
ClipRoundedRect begins a rectangular clipping operation. The rectangle has width w and height h. Its upper-left corner is positioned at (x, y). The rounded corners of the rectangle are specified by radius r. outline is true to draw a border with the current draw color and line width centered on the rectangle's perimeter. Only the outer half of the border will be shown. After calling this method, all rendering operations (for example, ImageOptions(), LinearGradient(), etc.) will be clipped by the specified rectangle. Call ClipEnd() to restore unclipped operations.
This ClipText() example demonstrates this method.
func (*Document) ClipRoundedRectExt ¶
ClipRoundedRectExt behaves the same as ClipRoundedRect() but supports a different radius for each corner, given by rTL (top-left), rTR (top-right), rBR (bottom-right), rBL (bottom-left). See ClipRoundedRect() for more details. This method is demonstrated in the ClipText() example.
func (*Document) ClipText ¶
ClipText begins a clipping operation in which rendering is confined to the character string specified by txtStr. The origin (x, y) is at the left side of the first character's baseline. The current font is used. outline is true to draw a border with the current draw color and line width centered on the perimeters of the text characters. Only the outer half of the border will be shown. After calling this method, all rendering operations (for example, ImageOptions(), LinearGradient(), etc.) will be clipped. Call ClipEnd() to restore unclipped operations.
Example ¶
ExampleDocument_ClipText demonstrates clipping.
package main
import (
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func loremList() []string {
return []string{
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " +
"tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " +
"aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum " +
"dolore eu fugiat nulla pariatur.",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " +
"officia deserunt mollit anim id est laborum.",
}
}
func lorem() string {
return strings.Join(loremList(), " ")
}
func main() {
pdf := document.New("", "", "", "")
y := 10.0
pdf.AddPage()
pdf.SetFont("Helvetica", "", 24)
pdf.SetXY(0, y)
pdf.ClipText(10, y+12, "Clipping examples", false)
pdf.RadialGradient(10, y, 100, 20, 128, 128, 160, 32, 32, 48,
0.25, 0.5, 0.25, 0.5, 0.2)
pdf.ClipEnd()
y += 12
pdf.SetFont("Helvetica", "B", 120)
pdf.SetDrawColor(64, 80, 80)
pdf.SetLineWidth(.5)
pdf.ClipText(10, y+40, pdf.String(), true)
pdf.RadialGradient(10, y, 200, 50, 220, 220, 250, 80, 80, 220,
0.25, 0.5, 0.25, 0.5, 1)
pdf.ClipEnd()
y += 55
pdf.ClipRect(10, y, 105, 20, true)
pdf.SetFillColor(255, 255, 255)
pdf.Rect(10, y, 105, 20, "F")
pdf.ClipCircle(40, y+10, 15, false)
pdf.RadialGradient(25, y, 30, 30, 220, 250, 220, 40, 60, 40, 0.3,
0.85, 0.3, 0.85, 0.5)
pdf.ClipEnd()
pdf.ClipEllipse(80, y+10, 20, 15, false)
pdf.RadialGradient(60, y, 40, 30, 250, 220, 220, 60, 40, 40, 0.3,
0.85, 0.3, 0.85, 0.5)
pdf.ClipEnd()
pdf.ClipEnd()
y += 28
pdf.ClipEllipse(26, y+10, 16, 10, true)
pdf.ImageOptions(example.ImageFile("logo.jpg"), 10, y, 32, 0, false, document.ImageOptions{ImageType: "JPG"}, 0, "")
pdf.ClipEnd()
pdf.ClipCircle(60, y+10, 10, true)
pdf.RadialGradient(50, y, 20, 20, 220, 220, 250, 40, 40, 60, 0.3,
0.7, 0.3, 0.7, 0.5)
pdf.ClipEnd()
pdf.ClipPolygon([]document.Point{{X: 80, Y: y + 20}, {X: 90, Y: y},
{X: 100, Y: y + 20}}, true)
pdf.LinearGradient(80, y, 20, 20, 250, 220, 250, 60, 40, 60, 0.5,
1, 0.5, 0.5)
pdf.ClipEnd()
y += 30
pdf.SetLineWidth(.1)
pdf.SetDrawColor(180, 180, 180)
pdf.ClipRoundedRect(10, y, 120, 20, 5, true)
pdf.RadialGradient(10, y, 120, 20, 255, 255, 255, 240, 240, 220,
0.25, 0.75, 0.25, 0.75, 0.5)
pdf.SetXY(5, y-5)
pdf.SetFont("Times", "", 12)
pdf.MultiCell(130, 5, lorem(), "", "", false)
pdf.ClipEnd()
y += 30
pdf.SetDrawColor(180, 100, 180)
pdf.ClipRoundedRectExt(10, y, 120, 20, 5, 10, 5, 10, true)
pdf.RadialGradient(10, y, 120, 20, 255, 255, 255, 240, 240, 220,
0.25, 0.75, 0.25, 0.75, 0.5)
pdf.SetXY(5, y-5)
pdf.SetFont("Times", "", 12)
pdf.MultiCell(130, 5, lorem(), "", "", false)
pdf.ClipEnd()
fileStr := example.Filename("Document_ClipText")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_ClipText.pdf
func (*Document) Close ¶
func (f *Document) Close()
Close terminates the PDF document. It is not necessary to call this method explicitly because Output, OutputAndClose, and OutputFileAndClose do it automatically. If the document contains no page, AddPage is called to prevent the generation of an invalid document.
func (*Document) ClosePath ¶
func (f *Document) ClosePath()
ClosePath creates a line from the current location to the last MoveTo point (if not the same) and marks the path as closed so the first and last lines join nicely.
The MoveTo() example demonstrates this method.
func (*Document) CreateTemplate ¶
CreateTemplate defines a new template using the current page size.
Example ¶
ExampleDocument_CreateTemplate demonstrates creating and using templates
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetCompression(false)
// pdf.SetFont("Times", "", 12)
template := pdf.CreateTemplate(func(tpl *document.Tpl) {
tpl.ImageOptions(example.ImageFile("logo.png"), 6, 6, 30, 0, false, document.ImageOptions{}, 0, "")
tpl.SetFont("Arial", "B", 16)
tpl.Text(40, 20, "Template says hello")
tpl.SetDrawColor(0, 100, 200)
tpl.SetLineWidth(2.5)
tpl.Line(95, 12, 105, 22)
})
_, tplSize := template.Size()
// fmt.Println("Size:", tplSize)
// fmt.Println("Scaled:", tplSize.ScaleBy(1.5))
template2 := pdf.CreateTemplate(func(tpl *document.Tpl) {
tpl.UseTemplate(template)
subtemplate := tpl.CreateTemplate(func(tpl2 *document.Tpl) {
tpl2.ImageOptions(example.ImageFile("logo.png"), 6, 86, 30, 0, false, document.ImageOptions{}, 0, "")
tpl2.SetFont("Arial", "B", 16)
tpl2.Text(40, 100, "Subtemplate says hello")
tpl2.SetDrawColor(0, 200, 100)
tpl2.SetLineWidth(2.5)
tpl2.Line(102, 92, 112, 102)
})
tpl.UseTemplate(subtemplate)
})
pdf.SetDrawColor(200, 100, 0)
pdf.SetLineWidth(2.5)
pdf.SetFont("Arial", "B", 16)
// serialize and deserialize template
b, _ := template2.Serialize()
template3, _ := document.DeserializeTemplate(b)
pdf.AddPage()
pdf.UseTemplate(template3)
pdf.UseTemplateScaled(template3, document.Point{X: 0, Y: 30}, tplSize)
pdf.Line(40, 210, 60, 210)
pdf.Text(40, 200, "Template example page 1")
pdf.AddPage()
pdf.UseTemplate(template2)
pdf.UseTemplateScaled(template3, document.Point{X: 0, Y: 30}, tplSize.ScaleBy(1.4))
pdf.Line(60, 210, 80, 210)
pdf.Text(40, 200, "Template example page 2")
fileStr := example.Filename("Document_CreateTemplate")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_CreateTemplate.pdf
func (*Document) CreateTemplateCustom ¶
CreateTemplateCustom starts a template, using the given bounds.
func (*Document) Curve ¶
Curve draws a single-segment quadratic Bézier curve. The curve starts at the point (x0, y0) and ends at the point (x1, y1). The control point (cx, cy) specifies the curvature. At the start point, the curve is tangent to the straight line between the start point and the control point. At the end point, the curve is tangent to the straight line between the end point and the control point.
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color, line width, and cap style centered on the curve's path. Filling uses the current fill color.
The Circle() example demonstrates this method.
func (*Document) CurveBezierCubic ¶
CurveBezierCubic draws a single-segment cubic Bézier curve. The curve starts at the point (x0, y0) and ends at the point (x1, y1). The control points (cx0, cy0) and (cx1, cy1) specify the curvature. At the start point, the curve is tangent to the straight line between the start point and the control point (cx0, cy0). At the end point, the curve is tangent to the straight line between the end point and the control point (cx1, cy1).
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color, line width, and cap style centered on the curve's path. Filling uses the current fill color.
This routine performs the same function as CurveCubic() but uses standard argument order.
The Circle() example demonstrates this method.
func (*Document) CurveBezierCubicTo ¶
CurveBezierCubicTo creates a single-segment cubic Bézier curve. The curve starts at the current stylus location and ends at the point (x, y). The control points (cx0, cy0) and (cx1, cy1) specify the curvature. At the current stylus location, the curve is tangent to the straight line between the current stylus location and the control point (cx0, cy0). At the end point, the curve is tangent to the straight line between the end point and the control point (cx1, cy1).
The MoveTo() example demonstrates this method.
func (*Document) CurveCubic ¶
CurveCubic draws a single-segment cubic Bézier curve. This routine performs the same function as CurveBezierCubic() but has a nonstandard argument order. It is retained to preserve backward compatibility.
func (*Document) CurveTo ¶
CurveTo creates a single-segment quadratic Bézier curve. The curve starts at the current stylus location and ends at the point (x, y). The control point (cx, cy) specifies the curvature. At the start point, the curve is tangent to the straight line between the current stylus location and the control point. At the end point, the curve is tangent to the straight line between the end point and the control point.
The MoveTo() example demonstrates this method.
func (*Document) DrawPath ¶
DrawPath actually draws the path on the page.
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Path-painting operators as defined in the PDF specification are also allowed: "S" (Stroke the path), "s" (Close and stroke the path), "f" (Fill the path, using the nonzero winding number), "f*" (Fill the path, using the even-odd rule), "B" (Fill and then stroke the path, using the nonzero winding number rule), "B*" (Fill and then stroke the path, using the even-odd rule), "b" (Close, fill, and then stroke the path, using the nonzero winding number rule), and "b*" (Close, fill, and then stroke the path, using the even-odd rule). Drawing uses the current draw color, line width, and cap style centered on the path. Filling uses the current fill color.
The MoveTo() example demonstrates this method.
Example ¶
ExampleDocument_DrawPath demonstrates various fill modes.
package main
import (
"math"
"strconv"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetDrawColor(0xff, 0x00, 0x00)
pdf.SetFillColor(0x99, 0x99, 0x99)
pdf.SetFont("Helvetica", "", 15)
pdf.AddPage()
pdf.SetAlpha(1, "Multiply")
var (
polygon = func(cx, cy, r, n, dir float64) {
da := 2 * math.Pi / n
pdf.MoveTo(cx+r, cy)
pdf.Text(cx+r, cy, "0")
i := 1
for a := da; a < 2*math.Pi; a += da {
x, y := cx+r*math.Cos(dir*a), cy+r*math.Sin(dir*a)
pdf.LineTo(x, y)
pdf.Text(x, y, strconv.Itoa(i))
i++
}
pdf.ClosePath()
}
polygons = func(cx, cy, r, n, dir float64) {
d := 1.0
for rf := r; rf > 0; rf -= 10 {
polygon(cx, cy, rf, n, d)
d *= dir
}
}
star = func(cx, cy, r, n float64) {
da := 4 * math.Pi / n
pdf.MoveTo(cx+r, cy)
for a := da; a < 4*math.Pi+da; a += da {
x, y := cx+r*math.Cos(a), cy+r*math.Sin(a)
pdf.LineTo(x, y)
}
pdf.ClosePath()
}
)
// triangle
polygons(55, 45, 40, 3, 1)
pdf.DrawPath("B")
pdf.Text(15, 95, "B (same direction, non zero winding)")
// square
polygons(155, 45, 40, 4, 1)
pdf.DrawPath("B*")
pdf.Text(115, 95, "B* (same direction, even odd)")
// pentagon
polygons(55, 145, 40, 5, -1)
pdf.DrawPath("B")
pdf.Text(15, 195, "B (different direction, non zero winding)")
// hexagon
polygons(155, 145, 40, 6, -1)
pdf.DrawPath("B*")
pdf.Text(115, 195, "B* (different direction, even odd)")
// star
star(55, 245, 40, 5)
pdf.DrawPath("B")
pdf.Text(15, 290, "B (non zero winding)")
// star
star(155, 245, 40, 5)
pdf.DrawPath("B*")
pdf.Text(115, 290, "B* (even odd)")
fileStr := example.Filename("Document_DrawPath_fill")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_DrawPath_fill.pdf
func (*Document) Ellipse ¶
Ellipse draws an ellipse centered at point (x, y). rx and ry specify its horizontal and vertical radii.
degRotate specifies the counter-clockwise angle in degrees that the ellipse will be rotated.
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color and line width centered on the ellipse's perimeter. Filling uses the current fill color.
The Circle() example demonstrates this method.
func (*Document) EnableTaggedPDF ¶ added in v0.5.0
func (f *Document) EnableTaggedPDF()
EnableTaggedPDF enables structure-tree and marked-content output. PDF/UA-2 metadata enables this automatically.
func (*Document) EndArtifact ¶ added in v0.5.0
func (f *Document) EndArtifact()
EndArtifact closes an artifact content span started with BeginArtifact.
func (*Document) EndLayer ¶
func (f *Document) EndLayer()
EndLayer is called to stop adding content to the currently active layer. See BeginLayer for more details.
func (*Document) EndStructure ¶ added in v0.5.0
func (f *Document) EndStructure()
EndStructure closes the most recent structure container.
func (*Document) Error ¶
Error returns the internal Document error; this will be nil if no error has occurred.
func (*Document) GetAlpha ¶
GetAlpha returns the alpha blending channel, which consists of the alpha transparency value and the blend mode. See SetAlpha for more details.
func (*Document) GetAutoPageBreak ¶
GetAutoPageBreak returns true if automatic pages breaks are enabled, false otherwise. This is followed by the triggering limit from the bottom of the page. This value applies only if automatic page breaks are enabled.
func (*Document) GetCellMargin ¶
GetCellMargin returns the cell margin. This is the amount of space before and after the text within a cell that's left blank, and is in units passed to New(). It defaults to 1mm.
func (*Document) GetConversionRatio ¶
GetConversionRatio returns the conversion ratio based on the unit given when creating the PDF.
func (*Document) GetDrawColor ¶
GetDrawColor returns the most recently set draw color as RGB components (0-255). This will not be the current value if a draw color of some other type (for example, spot) has been more recently set.
func (*Document) GetDrawSpotColor ¶
GetDrawSpotColor returns the most recently used spot color information for drawing. This will not be the current drawing color if some other color type such as RGB is active. If no spot color has been set for drawing, zero values are returned.
func (*Document) GetFillColor ¶
GetFillColor returns the most recently set fill color as RGB components (0-255). This will not be the current value if a fill color of some other type (for example, spot) has been more recently set.
func (*Document) GetFillSpotColor ¶
GetFillSpotColor returns the most recently used spot color information for fill output. This will not be the current fill color if some other color type such as RGB is active. If no fill spot color has been set, zero values are returned.
func (*Document) GetFontDesc ¶
func (f *Document) GetFontDesc(familyStr, styleStr string) FontDescriptor
GetFontDesc returns the font descriptor, which can be used, for example, to find the baseline of a font. If familyStr is empty, the current font descriptor is returned. See FontDescriptor for documentation about the font descriptor. See AddFont for details about familyStr and styleStr.
func (*Document) GetFontSize ¶
GetFontSize returns the size of the current font in points followed by the size in the unit of measure specified in New(). The second value can be used as a line height value in drawing operations.
func (*Document) GetImageInfo ¶
GetImageInfo returns information about the registered image specified by imageStr. If the image has not been registered, nil is returned. The internal error is not modified by this method.
func (*Document) GetLineWidth ¶
GetLineWidth returns the current line thickness.
func (*Document) GetMargins ¶
GetMargins returns the left, top, right, and bottom margins. The first three are set with the SetMargins() method. The bottom margin is set with the SetAutoPageBreak() method.
func (*Document) GetPageHeight ¶
GetPageHeight returns the current page height in the units established in New().
func (*Document) GetPageSize ¶
GetPageSize returns the current page's width and height. This is the paper's size. To compute the size of the area being used, subtract the margins (see GetMargins()).
func (*Document) GetPageSizeStr ¶
GetPageSizeStr returns the Size for the given sizeStr (that is A4, A3, etc..)
func (*Document) GetPageSizes ¶
GetPageSizes returns the available page box sizes for a PDF source and stores any import error on the document. Sizes are reported in PDF points.
func (*Document) GetPageWidth ¶
GetPageWidth returns the current page width in the units established in New().
func (*Document) GetStringSymbolWidth ¶
GetStringSymbolWidth returns the length of a string in glyph units. A font must be currently selected.
func (*Document) GetStringWidth ¶
GetStringWidth returns the length of a string in user units. A font must be currently selected.
func (*Document) GetTextColor ¶
GetTextColor returns the most recently set text color as RGB components (0-255). This will not be the current value if a text color of some other type (for example, spot) has been more recently set.
func (*Document) GetTextSpotColor ¶
GetTextSpotColor returns the most recently used spot color information for text output. This will not be the current text color if some other color type such as RGB is active. If no spot color has been set for text, zero values are returned.
func (*Document) GetX ¶
GetX returns the abscissa of the current position.
Note: the value returned will be affected by the current cell margin. To account for this, you may need to either add the value returned by GetCellMargin() to it or call SetCellMargin(0) to remove the cell margin.
func (*Document) GetXY ¶
GetXY returns the abscissa and ordinate of the current position.
Note: the value returned for the abscissa will be affected by the current cell margin. To account for this, you may need to either add the value returned by GetCellMargin() to it or call SetCellMargin(0) to remove the cell margin.
func (*Document) HTMLNew ¶
HTMLNew returns an instance that writes HTML into the current PDF document.
Example ¶
ExampleDocument_HTMLNew demonstrates internal and external links with HTML.
package main
import (
"os"
"path/filepath"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func init() {
cleanup()
}
func cleanup() {
_ = filepath.Walk(example.PdfDir(),
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil {
return nil
}
if info.Mode().IsRegular() {
if len(path) > 3 {
if path[len(path)-4:] == ".pdf" {
_ = os.Remove(path)
}
}
}
return nil
})
}
func main() {
pdf := document.New("P", "mm", "A4", "")
// First page: manual local link
pdf.AddPage()
pdf.SetFont("Helvetica", "", 20)
_, lineHt := pdf.GetFontSize()
pdf.Write(lineHt, "To find out what's new in this tutorial, click ")
pdf.SetFont("", "U", 0)
link := pdf.AddLink()
pdf.WriteLinkID(lineHt, "here", link)
pdf.SetFont("", "", 0)
// Second page: image link and HTML with link
pdf.AddPage()
pdf.SetLink(link, 0, -1)
pdf.ImageOptions(example.ImageFile("logo.png"), 10, 12, 30, 0, false, document.ImageOptions{}, 0, "http://www.fpdf.org")
pdf.SetLeftMargin(45)
pdf.SetFontSize(14)
_, lineHt = pdf.GetFontSize()
htmlStr := `You can now easily print text mixing different styles: <b>bold</b>, ` +
`<i>italic</i>, <u>underlined</u>, or <b><i><u>all at once</u></i></b>!<br><br>` +
`<center>You can also center text.</center>` +
`<right>Or align it to the right.</right>` +
`You can also insert links on text, such as ` +
`<a href="http://www.fpdf.org">www.fpdf.org</a>, or on an image: click on the logo.`
html := pdf.HTMLNew()
html.Write(lineHt, htmlStr)
fileStr := example.Filename("Document_HTMLNew")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_HTMLNew.pdf
func (*Document) ImageFromCache ¶ added in v0.5.0
func (f *Document) ImageFromCache(name string, cache *ImageCache, x, y, w, h float64, flow bool, options ImageOptions, link int, linkStr string)
ImageFromCache places a cached image on the current page.
func (*Document) ImageOptions ¶
func (f *Document) ImageOptions(imageNameStr string, x, y, w, h float64, flow bool, options ImageOptions, link int, linkStr string)
ImageOptions puts a JPEG, PNG, GIF, or WebP image on the current page. The size it takes on the page can be specified in different ways. If both w and h are 0, the image is rendered at 96 DPI. If either w or h is zero, it is calculated from the other dimension so the aspect ratio is maintained. If w and/or h are -1, the DPI for that dimension will be read from the ImageInfo object. PNG files can contain DPI information, and if present, this information will be populated in the ImageInfo object and used in Width, Height, and Extent calculations. Otherwise, the SetDpi function can be used to change the DPI from the default of 72.
If w and h are any other negative value, their absolute values indicate their DPI extents.
Supported JPEG formats are 24-bit, 32-bit, and grayscale. Supported PNG formats are 24-bit, indexed color, and 8-bit indexed grayscale. GIF and WebP images are converted to PNG before embedding. If a GIF image is animated, only the first frame is rendered. Transparency is supported. It is possible to put a link on the image.
imageNameStr may be the name of an image as registered with a call to either RegisterImageOptionsReader() or RegisterImageOptions(). In the first case, the image is loaded using an io.Reader. This is generally useful when the image is obtained from a source other than a disk-based file. In the second case, the image is loaded as a file. Alternatively, imageNameStr may directly specify a sufficiently qualified filename.
However the image is loaded, if it is used more than once only one copy is embedded in the file.
If x is negative, the current abscissa is used.
If flow is true, the current y value is advanced after placing the image and a page break may be made if necessary.
If link refers to an internal page anchor (that is, it is non-zero; see AddLink()), the image will be a clickable internal link. Otherwise, if linkStr specifies a URL, the image will be a clickable external link.
Example ¶
ExampleDocument_ImageOptions demonstrates how the AllowNegativePosition field of the ImageOption struct can be used to affect horizontal image placement.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
var opt document.ImageOptions
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 11)
pdf.SetX(60)
opt.ImageType = "png"
pdf.ImageOptions(example.ImageFile("logo.png"), -10, 10, 30, 0, false, opt, 0, "")
opt.AllowNegativePosition = true
pdf.ImageOptions(example.ImageFile("logo.png"), -10, 50, 30, 0, false, opt, 0, "")
fileStr := example.Filename("Document_ImageOptions")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_ImageOptions.pdf
Example (Formats) ¶
ExampleDocument_ImageOptions_formats demonstrates how images are included in documents.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 11)
pdf.ImageOptions(example.ImageFile("logo.png"), 10, 10, 30, 0, false, document.ImageOptions{}, 0, "")
pdf.Text(50, 20, "logo.png")
pdf.ImageOptions(example.ImageFile("logo.gif"), 10, 40, 30, 0, false, document.ImageOptions{}, 0, "")
pdf.Text(50, 50, "logo.gif")
pdf.ImageOptions(example.ImageFile("logo-gray.png"), 10, 70, 30, 0, false, document.ImageOptions{}, 0, "")
pdf.Text(50, 80, "logo-gray.png")
pdf.ImageOptions(example.ImageFile("logo-rgb.png"), 10, 100, 30, 0, false, document.ImageOptions{}, 0, "")
pdf.Text(50, 110, "logo-rgb.png")
pdf.ImageOptions(example.ImageFile("logo.jpg"), 10, 130, 30, 0, false, document.ImageOptions{}, 0, "")
pdf.Text(50, 140, "logo.jpg")
fileStr := example.Filename("Document_ImageOptions_formats")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_ImageOptions_formats.pdf
func (*Document) ImageOptionsExtended ¶
func (f *Document) ImageOptionsExtended(name string, opts ExtendedImageOptions)
ImageOptionsExtended places an image with optional rotation, flipping, cropping, and an external soft-mask image.
func (*Document) ImageTypeFromMime ¶
ImageTypeFromMime returns the image type used in various image-related functions, such as ImageOptions(), for the specified MIME type. For example, "jpg" is returned if mimeStr is "image/jpeg". An error is set if the specified MIME type is not supported.
func (*Document) ImportObjPos ¶
ImportObjPos imports external template object hash positions.
func (*Document) ImportObjects ¶
ImportObjects imports external template objects into the current document.
func (*Document) ImportPage ¶
ImportPage imports one page from a PDF file and returns its imported page ID.
This built-in importer intentionally has a small dependency-free scope: classic xref-table PDFs, unencrypted documents, and pages whose content streams are unfiltered or FlateDecode-compressed. PDFs using xref streams or object streams are reported as unsupported.
func (*Document) ImportPageStream ¶
ImportPageStream imports one page from a PDF stream and returns its imported page ID. The stream is read into memory, so callers may pass any io.Reader.
func (*Document) ImportPagesFromSource ¶
ImportPagesFromSource imports every page from source and returns the imported page IDs. source may be a file path string, []byte, or io.Reader.
func (*Document) ImportTemplates ¶
ImportTemplates imports external template names for inclusion in the ProcSet dictionary.
func (*Document) Line ¶
Line draws a line between points (x1, y1) and (x2, y2) using the current draw color, line width, and cap style.
func (*Document) LineTo ¶
LineTo creates a line from the current stylus location to (x, y), which becomes the new stylus location. Note that this only creates the line in the path; it does not actually draw the line on the page.
The MoveTo() example demonstrates this method.
func (*Document) LinearGradient ¶
func (f *Document) LinearGradient(x, y, w, h float64, r1, g1, b1, r2, g2, b2 int, x1, y1, x2, y2 float64)
LinearGradient draws a rectangular area with a blend from one color to another. The rectangle has width w and height h. Its upper-left corner is positioned at (x, y).
Each color is specified with three component values, one each for red, green and blue. The values range from 0 to 255. The first color is specified by (r1, g1, b1) and the second color by (r2, g2, b2).
The blending is controlled with a gradient vector that uses normalized coordinates in which the lower-left corner is at position (0, 0) and the upper-right corner is (1, 1). The vector's origin and destination are specified by the points (x1, y1) and (x2, y2). In a linear gradient, blending occurs perpendicularly to the vector. The vector does not necessarily need to be anchored on the rectangle edge. Color 1 is used up to the origin of the vector and color 2 is used beyond the vector's end point. Between the points the colors are gradually blended.
Example ¶
ExampleDocument_LinearGradient deomstrates various gradients.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("", "", "", "")
pdf.SetFont("Helvetica", "", 12)
pdf.AddPage()
pdf.LinearGradient(0, 0, 210, 100, 250, 250, 255, 220, 220, 225, 0, 0, 0, .5)
pdf.LinearGradient(20, 25, 75, 75, 220, 220, 250, 80, 80, 220, 0, .2, 0, .8)
pdf.Rect(20, 25, 75, 75, "D")
pdf.LinearGradient(115, 25, 75, 75, 220, 220, 250, 80, 80, 220, 0, 0, 1, 1)
pdf.Rect(115, 25, 75, 75, "D")
pdf.RadialGradient(20, 120, 75, 75, 220, 220, 250, 80, 80, 220,
0.25, 0.75, 0.25, 0.75, 1)
pdf.Rect(20, 120, 75, 75, "D")
pdf.RadialGradient(115, 120, 75, 75, 220, 220, 250, 80, 80, 220,
0.25, 0.75, 0.75, 0.75, 0.75)
pdf.Rect(115, 120, 75, 75, "D")
fileStr := example.Filename("Document_LinearGradient_gradient")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_LinearGradient_gradient.pdf
func (*Document) Link ¶
Link puts a link on a rectangular area of the page. Text or image links are generally put via Cell, Write, or ImageOptions, but this method can be useful to define a clickable area inside an image. link is the value returned by AddLink.
func (*Document) LinkString ¶
LinkString puts a link on a rectangular area of the page. Text or image links are generally put via Cell, Write, or ImageOptions, but this method can be useful to define a clickable area inside an image. linkStr is the target URL.
func (*Document) Ln ¶
Ln performs a line break. The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter. A negative value of h indicates the height of the last printed cell.
This method is demonstrated in the example for MultiCell.
func (*Document) MoveTo ¶
MoveTo moves the stylus to (x, y) without drawing from the previous point. Paths must start with MoveTo to set the original stylus location; otherwise, the result is undefined.
Create a path by moving a virtual stylus around the page with MoveTo(), LineTo(), CurveTo(), CurveBezierCubicTo(), ArcTo(), and ClosePath(), then draw or fill it with DrawPath(). Path drawing routines produce proper PDF line joins at angles instead of overlaying separate line segments.
Example ¶
ExampleDocument_MoveTo demonstrates the Path Drawing functions, such as: MoveTo, LineTo, CurveTo, ..., ClosePath and DrawPath.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.MoveTo(20, 20)
pdf.LineTo(170, 20)
pdf.ArcTo(170, 40, 20, 20, 0, 90, 0)
pdf.CurveTo(190, 100, 105, 100)
pdf.CurveBezierCubicTo(20, 100, 105, 200, 20, 200)
pdf.ClosePath()
pdf.SetFillColor(200, 200, 200)
pdf.SetLineWidth(3)
pdf.DrawPath("DF")
fileStr := example.Filename("Document_MoveTo_path")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_MoveTo_path.pdf
func (*Document) MultiCell ¶
MultiCell prints text with automatic line breaks. The text is placed in cells of width w and line height h. Each line is bordered according to borderStr, aligned according to alignStr, and optionally filled when fill is true. When w is 0, the cell extends to the right margin.
Example ¶
ExampleDocument_MultiCell demonstrates word-wrapping, line justification and page-breaking.
package main
import (
"fmt"
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
titleStr := "20000 Leagues Under the Seas"
pdf.SetTitle(titleStr, false)
pdf.SetAuthor("Jules Verne", false)
pdf.SetHeaderFunc(func() {
// Arial bold 15
pdf.SetFont("Arial", "B", 15)
// Calculate width of title and position
wd := pdf.GetStringWidth(titleStr) + 6
pdf.SetX((210 - wd) / 2)
// Colors of frame, background and text
pdf.SetDrawColor(0, 80, 180)
pdf.SetFillColor(230, 230, 0)
pdf.SetTextColor(220, 50, 50)
// Thickness of frame (1 mm)
pdf.SetLineWidth(1)
// Title
pdf.CellFormat(wd, 9, titleStr, "1", 1, "C", true, 0, "")
// Line break
pdf.Ln(10)
})
pdf.SetFooterFunc(func() {
// Position at 1.5 cm from bottom
pdf.SetY(-15)
// Arial italic 8
pdf.SetFont("Arial", "I", 8)
// Text color in gray
pdf.SetTextColor(128, 128, 128)
// Page number
pdf.CellFormat(0, 10, fmt.Sprintf("Page %d", pdf.PageNo()),
"", 0, "C", false, 0, "")
})
chapterTitle := func(chapNum int, titleStr string) {
// // Arial 12
pdf.SetFont("Arial", "", 12)
// Background color
pdf.SetFillColor(200, 220, 255)
// Title
pdf.CellFormat(0, 6, fmt.Sprintf("Chapter %d : %s", chapNum, titleStr),
"", 1, "L", true, 0, "")
// Line break
pdf.Ln(4)
}
chapterBody := func(fileStr string) {
// Read text file
txtStr, err := os.ReadFile(fileStr)
if err != nil {
pdf.SetError(err)
}
// Times 12
pdf.SetFont("Times", "", 12)
// Output justified text
pdf.MultiCell(0, 5, string(txtStr), "", "", false)
// Line break
pdf.Ln(-1)
// Mention in italics
pdf.SetFont("", "I", 0)
pdf.Cell(0, 5, "(end of excerpt)")
}
printChapter := func(chapNum int, titleStr, fileStr string) {
pdf.AddPage()
chapterTitle(chapNum, titleStr)
chapterBody(fileStr)
}
printChapter(1, "A RUNAWAY REEF", example.TextFile("20k_c1.txt"))
printChapter(2, "THE PROS AND CONS", example.TextFile("20k_c2.txt"))
fileStr := example.Filename("Document_MultiCell")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_MultiCell.pdf
Example (TextAlignments) ¶
ExampleDocument_MultiCell_textAlignments demonstrates repeated paragraph layout with the same fixture rendered in multiple alignments.
package main
import (
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
fileStr := example.Filename("Document_TextAlignments")
txt, err := os.ReadFile(example.TextFile("paragraph-alignments.txt"))
pdf := document.New("P", "mm", "A4", "")
pdf.SetMargins(18, 18, 18)
pdf.AddPage()
if err == nil {
alignments := []struct {
label string
align string
}{
{"Left aligned", "L"},
{"Centered", "C"},
{"Right aligned", "R"},
{"Justified", "J"},
}
for _, alignment := range alignments {
pdf.SetFont("Helvetica", "B", 12)
pdf.CellFormat(0, 7, alignment.label, "", 1, "L", false, 0, "")
pdf.SetFont("Helvetica", "", 10)
pdf.MultiCell(0, 5, string(txt), "1", alignment.align, false)
pdf.Ln(5)
}
err = pdf.OutputFileAndClose(fileStr)
}
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_TextAlignments.pdf
func (*Document) OpenLayerPane ¶
func (f *Document) OpenLayerPane()
OpenLayerPane advises the document reader to open the layer pane when the document is initially displayed.
func (*Document) Output ¶
Output sends the PDF document to the writer specified by w. No output will be written if an error has occurred in the document generation process. w remains open after this function returns. After returning, f is in a closed state and its methods should not be called.
func (*Document) OutputAndClose ¶
func (f *Document) OutputAndClose(w io.WriteCloser) error
OutputAndClose sends the PDF document to the writer specified by w. This method will close both f and w, even if an error is detected and no document is produced.
func (*Document) OutputFileAndClose ¶
OutputFileAndClose creates or truncates the file specified by fileStr and writes the PDF document to it. This method will close f and the newly written file, even if an error is detected and no document is produced.
Most examples demonstrate the use of this method.
func (*Document) OutputSigned ¶
OutputSigned writes the current document as a signed PDF.
func (*Document) OutputSignedFile ¶
OutputSignedFile creates or truncates fileStr and writes the current document as a signed PDF.
func (*Document) PageCount ¶
PageCount returns the number of pages currently in the document. Since page numbers in gopdfkit are one-based, the page count is the same as the page number of the current last page.
func (*Document) PageNo ¶
PageNo returns the current page number.
See the example for AddPage() for a demonstration of this method.
func (*Document) PageSize ¶
PageSize returns the width and height of the specified page in the units established in New(). These return values are followed by the unit of measure itself. If pageNum is zero or otherwise out of bounds, it returns the default page size, that is, the size of the page that would be added by AddPage().
Example ¶
ExampleDocument_PageSize generates a PDF document with various page sizes.
package main
import (
"fmt"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.NewWithOptions(document.Options{
UnitStr: "in",
Size: document.Size{Wd: 6, Ht: 6},
FontDirStr: example.FontDir(),
})
pdf.SetMargins(0.5, 1, 0.5)
pdf.SetFont("Times", "", 14)
pdf.AddPageFormat("L", document.Size{Wd: 3, Ht: 12})
pdf.SetXY(0.5, 1.5)
pdf.CellFormat(11, 0.2, "12 in x 3 in", "", 0, "C", false, 0, "")
pdf.AddPage() // Default size established in NewWithOptions()
pdf.SetXY(0.5, 3)
pdf.CellFormat(5, 0.2, "6 in x 6 in", "", 0, "C", false, 0, "")
pdf.AddPageFormat("P", document.Size{Wd: 3, Ht: 12})
pdf.SetXY(0.5, 6)
pdf.CellFormat(2, 0.2, "3 in x 12 in", "", 0, "C", false, 0, "")
for j := 0; j <= 3; j++ {
wd, ht, u := pdf.PageSize(j)
fmt.Printf("%d: %6.2f %s, %6.2f %s\n", j, wd, u, ht, u)
}
fileStr := example.Filename("Document_PageSize")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: 0: 6.00 in, 6.00 in 1: 12.00 in, 3.00 in 2: 6.00 in, 6.00 in 3: 3.00 in, 12.00 in Successfully generated assets/generated/pdf/Document_PageSize.pdf
func (*Document) PointConvert ¶
PointConvert returns the value of pt, expressed in points (1/72 inch), as a value expressed in the unit of measure specified in New(). Since font management in Document uses points, this method can help with line height calculations and other methods that require user units.
func (*Document) PointToUnitConvert ¶
PointToUnitConvert is an alias for PointConvert.
func (*Document) Polygon ¶
Polygon draws a closed figure defined by a series of vertices specified by points. The x and y fields of the points use the units established in New(). The last point in the slice will be implicitly joined to the first to close the polygon.
styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color and line width centered on the polygon's perimeter. Filling uses the current fill color.
Example ¶
ExampleDocument_Polygon displays equilateral polygons in a demonstration of the Polygon function.
package main
import (
"math"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const rowCount = 5
const colCount = 4
const ptSize = 36
var x, y, radius, gap, advance float64
var rgVal int
var pts []document.Point
vertices := func(count int) (res []document.Point) {
var pt document.Point
res = make([]document.Point, 0, count)
mlt := 2.0 * math.Pi / float64(count)
for j := range count {
pt.Y, pt.X = math.Sincos(float64(j) * mlt)
res = append(res, document.Point{
X: x + radius*pt.X,
Y: y + radius*pt.Y})
}
return
}
pdf := document.New("P", "mm", "A4", "") // A4 210.0 x 297.0
pdf.AddPage()
pdf.SetFont("Helvetica", "", ptSize)
pdf.SetDrawColor(0, 80, 180)
gap = 12.0
pdf.SetY(gap)
pdf.CellFormat(190.0, gap, "Equilateral polygons", "", 1, "C", false, 0, "")
radius = (210.0 - float64(colCount+1)*gap) / (2.0 * float64(colCount))
advance = gap + 2.0*radius
y = 2*gap + pdf.PointConvert(ptSize) + radius
rgVal = 230
for row := range rowCount {
pdf.SetFillColor(rgVal, rgVal, 0)
rgVal -= 12
x = gap + radius
for col := range colCount {
pts = vertices(row*colCount + col + 3)
pdf.Polygon(pts, "FD")
x += advance
}
y += advance
}
fileStr := example.Filename("Document_Polygon")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_Polygon.pdf
func (*Document) RTL ¶
func (f *Document) RTL()
RTL enables right-to-left text layout mode.
Example (UnicodeTextFixture) ¶
ExampleDocument_RTL_unicodeTextFixture demonstrates UTF-8 text and explicit right-to-left sections from a text fixture.
package main
import (
"fmt"
"os"
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
fileStr := example.Filename("Document_TextUnicodeRTL")
txt, err := os.ReadFile(example.TextFile("unicode-rtl.txt"))
pdf := document.New("P", "mm", "A4", "")
pdf.SetMargins(20, 20, 20)
pdf.AddPage()
pdf.AddUTF8Font("dejavu", "", example.FontFile("DejaVuSansCondensed.ttf"))
pdf.AddUTF8Font("dejavu", "B", example.FontFile("DejaVuSansCondensed-Bold.ttf"))
pdf.SetFont("dejavu", "", 13)
if err == nil {
for block := range strings.SplitSeq(strings.TrimSpace(string(txt)), "\n\n") {
lines := strings.SplitN(block, "\n", 2)
if len(lines) != 2 {
err = fmt.Errorf("invalid unicode fixture block: %q", block)
break
}
label := strings.TrimSuffix(lines[0], ":")
body := strings.TrimSpace(lines[1])
pdf.SetFont("dejavu", "B", 13)
pdf.LTR()
pdf.CellFormat(0, 7, label, "", 1, "L", false, 0, "")
pdf.SetFont("dejavu", "", 13)
if label == "Hebrew" || label == "Arabic" {
pdf.RTL()
pdf.MultiCell(0, 7, body, "1", "R", false)
pdf.LTR()
} else {
pdf.MultiCell(0, 7, body, "1", "L", false)
}
pdf.Ln(5)
}
}
if err == nil {
err = pdf.OutputFileAndClose(fileStr)
}
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_TextUnicodeRTL.pdf
func (*Document) RadialGradient ¶
func (f *Document) RadialGradient(x, y, w, h float64, r1, g1, b1, r2, g2, b2 int, x1, y1, x2, y2, r float64)
RadialGradient draws a rectangular area with a blend from one color to another. The rectangle has width w and height h. Its upper-left corner is positioned at (x, y).
Each color is specified with three component values, one each for red, green and blue. The values range from 0 to 255. The first color is specified by (r1, g1, b1) and the second color by (r2, g2, b2).
The blending is controlled with a point and a circle, both specified with normalized coordinates in which the lower-left corner of the rendered rectangle is at position (0, 0) and the upper-right corner is (1, 1). Color 1 begins at the origin point specified by (x1, y1). Color 2 begins at the circle specified by the center point (x2, y2) and radius r. Colors are gradually blended from the origin to the circle. The origin and the circle's center do not necessarily have to coincide, but the origin must be within the circle to avoid rendering problems.
The LinearGradient() example demonstrates this method.
func (*Document) RawWriteArtifactBuf ¶ added in v0.5.0
RawWriteArtifactBuf writes raw PDF content marked as an artifact when tagged PDF output is enabled.
func (*Document) RawWriteArtifactStr ¶ added in v0.5.0
RawWriteArtifactStr writes raw PDF content marked as an artifact when tagged PDF output is enabled.
func (*Document) RawWriteBuf ¶
RawWriteBuf writes the contents of the specified buffer directly to the PDF generation buffer. This is a low-level function that is not required for normal PDF construction. An understanding of the PDF specification is needed to use this method correctly.
func (*Document) RawWriteStr ¶
RawWriteStr writes a string directly to the PDF generation buffer. This is a low-level function that is not required for normal PDF construction. An understanding of the PDF specification is needed to use this method correctly.
func (*Document) Rect ¶
Rect outputs a rectangle of width w and height h with the upper-left corner positioned at (x, y).
It can be drawn (border only), filled (with no border) or both. styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color and line width centered on the rectangle's perimeter. Filling uses the current fill color.
Example ¶
This example demonstrate wrapped table cells
package main
import (
"fmt"
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
marginCell := 2. // margin of top/bottom of cell
pdf := document.New("P", "mm", "A4", "")
pdf.SetFont("Arial", "", 12)
pdf.AddPage()
pagew, pageh := pdf.GetPageSize()
mleft, mright, _, mbottom := pdf.GetMargins()
cols := []float64{60, 100, pagew - mleft - mright - 100 - 60}
rows := [][]string{}
for i := 1; i <= 30; i++ {
word := fmt.Sprintf("%d:%s", i, strings.Repeat("A", i%100))
rows = append(rows, []string{word, word, word})
}
for _, row := range rows {
curx, y := pdf.GetXY()
x := curx
height := 0.
_, lineHt := pdf.GetFontSize()
for i, txt := range row {
lines := pdf.SplitLines([]byte(txt), cols[i])
h := float64(len(lines))*lineHt + marginCell*float64(len(lines))
if h > height {
height = h
}
}
// add a new page if the height of the row doesn't fit on the page
if pdf.GetY()+height > pageh-mbottom {
pdf.AddPage()
y = pdf.GetY()
}
for i, txt := range row {
width := cols[i]
pdf.Rect(x, y, width, height, "")
pdf.MultiCell(width, lineHt+marginCell, txt, "", "", false)
x += width
pdf.SetXY(x, y)
}
pdf.SetXY(curx, y+height)
}
fileStr := example.Filename("Document_WrappedTableCells")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_WrappedTableCells.pdf
func (*Document) RegisterAlias ¶
RegisterAlias adds an (alias, replacement) pair to the document so we can replace all occurrences of that alias after writing but before the document is closed. Functions ExampleDocument_RegisterAlias() and ExampleDocument_RegisterAlias_utf8() in document_test.go demonstrate this method.
Example ¶
ExampleDocument_RegisterAlias demonstrates how to use `RegisterAlias` to create a table of contents.
package main
import (
"fmt"
"strconv"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetFont("Arial", "", 12)
pdf.AliasNbPages("")
pdf.AddPage()
// Write the table of contents. We use aliases instead of the page number
// because we don't know which page the section will begin on.
numSections := 3
for i := 1; i <= numSections; i++ {
pdf.Cell(0, 10, fmt.Sprintf("Section %d begins on page {mark %d}", i, i))
pdf.Ln(10)
}
// Write the sections. Before we start writing, we use `RegisterAlias` to
// ensure that the alias written in the table of contents will be replaced
// by the current page number.
for i := 1; i <= numSections; i++ {
pdf.AddPage()
pdf.RegisterAlias(fmt.Sprintf("{mark %d}", i), strconv.Itoa(pdf.PageNo()))
pdf.Write(10, fmt.Sprintf("Section %d, page %d of {nb}", i, pdf.PageNo()))
}
fileStr := example.Filename("Document_RegisterAlias")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_RegisterAlias.pdf
Example (Utf8) ¶
ExampleDocument_RegisterAlias_utf8 demonstrates how to use `RegisterAlias` to create a table of contents. This particular example demonstrates the use of UTF-8 aliases.
package main
import (
"fmt"
"strconv"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.AddUTF8Font("dejavu", "", example.FontFile("DejaVuSansCondensed.ttf"))
pdf.SetFont("dejavu", "", 12)
pdf.AliasNbPages("{entute}")
pdf.AddPage()
// Write the table of contents. We use aliases instead of the page number
// because we don't know which page the section will begin on.
numSections := 3
for i := 1; i <= numSections; i++ {
pdf.Cell(0, 10, fmt.Sprintf("Sekcio %d komenciĝas ĉe paĝo {ĉi tiu marko %d}", i, i))
pdf.Ln(10)
}
// Write the sections. Before we start writing, we use `RegisterAlias` to
// ensure that the alias written in the table of contents will be replaced
// by the current page number.
for i := 1; i <= numSections; i++ {
pdf.AddPage()
pdf.RegisterAlias(fmt.Sprintf("{ĉi tiu marko %d}", i), strconv.Itoa(pdf.PageNo()))
pdf.Write(10, fmt.Sprintf("Sekcio %d, paĝo %d de {entute}", i, pdf.PageNo()))
}
fileStr := example.Filename("Document_RegisterAliasUTF8")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_RegisterAliasUTF8.pdf
func (*Document) RegisterImageFromCache ¶ added in v0.5.0
func (f *Document) RegisterImageFromCache(name string, cache *ImageCache) *ImageInfo
RegisterImageFromCache registers a cached image with this document. The returned ImageInfo can be used with ImageOptions using the same name.
func (*Document) RegisterImageOptions ¶
func (f *Document) RegisterImageOptions(fileStr string, options ImageOptions) (info *ImageInfo)
RegisterImageOptions registers an image, adding it to the PDF file but not adding it to the page. Use ImageOptions() with the same filename to add the image to the page. ImageOptions() calls this function, so this function is only necessary if you need information about the image before placing it. See ImageOptions() for restrictions on the image and options parameters.
Example ¶
ExampleDocument_RegisterImageOptions demonstrates Lawrence Kesteloot's image registration code.
package main
import (
"fmt"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const (
margin = 10
wd = 210
ht = 297
)
fileList := []string{
"logo-gray.png",
"logo.jpg",
"logo.png",
"logo-rgb.png",
"logo-progressive.jpg",
}
var infoPtr *document.ImageInfo
var imageFileStr string
var imgWd, imgHt, lf, tp float64
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetMargins(10, 10, 10)
pdf.SetFont("Helvetica", "", 15)
for j, str := range fileList {
imageFileStr = example.ImageFile(str)
infoPtr = pdf.RegisterImageOptions(imageFileStr, document.ImageOptions{})
imgWd, imgHt = infoPtr.Extent()
switch j {
case 0:
lf = margin
tp = margin
case 1:
lf = wd - margin - imgWd
tp = margin
case 2:
lf = (wd - imgWd) / 2.0
tp = (ht - imgHt) / 2.0
case 3:
lf = margin
tp = ht - imgHt - margin
case 4:
lf = wd - imgWd - margin
tp = ht - imgHt - margin
}
pdf.ImageOptions(imageFileStr, lf, tp, imgWd, imgHt, false, document.ImageOptions{}, 0, "")
}
fileStr := example.Filename("Document_RegisterImageOptions")
// Test the image information retrieval method
infoShow := func(imageStr string) {
imageStr = example.ImageFile(imageStr)
info := pdf.GetImageInfo(imageStr)
if info != nil {
if info.Width() > 0.0 {
fmt.Printf("Image %s is registered\n", example.DisplayPath(imageStr))
} else {
fmt.Printf("Incorrect information for image %s\n", example.DisplayPath(imageStr))
}
} else {
fmt.Printf("Image %s is not registered\n", example.DisplayPath(imageStr))
}
}
infoShow(fileList[0])
infoShow("foo.png")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Image assets/static/image/logo-gray.png is registered Image assets/static/image/foo.png is not registered Successfully generated assets/generated/pdf/Document_RegisterImageOptions.pdf
func (*Document) RegisterImageOptionsReader ¶
func (f *Document) RegisterImageOptionsReader(imgName string, options ImageOptions, r io.Reader) (info *ImageInfo)
RegisterImageOptionsReader registers an image by reading it from r, adding it to the PDF file but not adding it to the page. Use ImageOptions() with the same name to add the image to the page. Note that ImageType should be specified in this case.
See ImageOptions() for restrictions on the image and the options parameters.
Example ¶
ExampleDocument_RegisterImageOptionsReader demonstrates how to load an image from a io.Reader (in this case, a file) and register it with options.
package main
import (
"os"
"path/filepath"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func init() {
cleanup()
}
func cleanup() {
_ = filepath.Walk(example.PdfDir(),
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil {
return nil
}
if info.Mode().IsRegular() {
if len(path) > 3 {
if path[len(path)-4:] == ".pdf" {
_ = os.Remove(path)
}
}
}
return nil
})
}
func main() {
var (
opt document.ImageOptions
pdfStr string
fl *os.File
err error
)
pdfStr = example.Filename("Document_RegisterImageOptionsReader")
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 11)
fl, err = os.Open(example.ImageFile("logo.png"))
if err == nil {
opt.ImageType = "png"
opt.AllowNegativePosition = true
_ = pdf.RegisterImageOptionsReader("logo", opt, fl)
_ = fl.Close()
for x := -20.0; x <= 40.0; x += 5 {
pdf.ImageOptions("logo", x, x+30, 0, 0, false, opt, 0, "")
}
err = pdf.OutputFileAndClose(pdfStr)
}
example.Summary(err, pdfStr)
}
Output: Successfully generated assets/generated/pdf/Document_RegisterImageOptionsReader.pdf
Example (Flow) ¶
ExampleDocument_RegisterImageOptionsReader_flow demonstrates the use of an image loaded from an io.Reader in flowing page content.
package main
import (
"os"
"path/filepath"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func init() {
cleanup()
}
func cleanup() {
_ = filepath.Walk(example.PdfDir(),
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil {
return nil
}
if info.Mode().IsRegular() {
if len(path) > 3 {
if path[len(path)-4:] == ".pdf" {
_ = os.Remove(path)
}
}
}
return nil
})
}
func main() {
const (
margin = 10
wd = 210
ht = 297
fontSize = 15
imageStr = "gopdfkit-reader"
msgStr = `Images can be embedded from any reader when a PDF document is generated.`
)
var (
fl *os.File
err error
)
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Helvetica", "", fontSize)
ln := pdf.PointConvert(fontSize)
pdf.MultiCell(wd-margin-margin, ln, msgStr, "", "L", false)
fl, err = os.Open(example.ImageFile("go_pdf_kit.png"))
if err == nil {
defer func() { _ = fl.Close() }()
infoPtr := pdf.RegisterImageOptionsReader(imageStr, document.ImageOptions{ImageType: "png"}, fl)
if pdf.Ok() {
imgWd, imgHt := infoPtr.Extent()
pdf.ImageOptions(imageStr, (wd-imgWd)/2.0, pdf.GetY()+ln,
imgWd, imgHt, false, document.ImageOptions{ImageType: "png"}, 0, "")
}
} else {
pdf.SetError(err)
}
fileStr := example.Filename("Document_RegisterImageOptionsReader_flow")
err = pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_RegisterImageOptionsReader_flow.pdf
func (*Document) RegisterQRCodePNG ¶ added in v0.3.0
RegisterQRCodePNG registers a QR code as a PNG image and returns its image name for subsequent ImageOptions calls.
func (*Document) RegisterThumbnail ¶
func (f *Document) RegisterThumbnail(name string, r io.Reader, options ThumbnailOptions) (*ImageInfo, error)
RegisterThumbnail creates a thumbnail from r and registers it on this PDF document under name.
Example ¶
package main
import (
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetFont("Helvetica", "", 12)
pdf.AddPage()
file, err := os.Open(example.ImageFile("logo.png"))
if err == nil {
_, err = pdf.RegisterThumbnail("logo-thumb", file, document.ThumbnailOptions{MaxWidth: 96, MaxHeight: 96})
_ = file.Close()
}
if err == nil {
pdf.Cell(0, 8, "Generated thumbnail")
pdf.Ln(12)
pdf.ImageOptions("logo-thumb", 10, 22, 32, 0, false, document.ImageOptions{}, 0, "")
}
fileStr := example.Filename("thumb_Register")
if err == nil {
err = pdf.OutputFileAndClose(fileStr)
}
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/thumb_Register.pdf
func (*Document) RoundedRect ¶
RoundedRect outputs a rectangle of width w and height h with the upper-left corner positioned at (x, y). It can be drawn (border only), filled (with no border) or both. styleStr can be "F" for filled, "D" for outlined only, or "DF" or "FD" for outlined and filled. An empty string will be replaced with "D". Drawing uses the current draw color and line width centered on the rectangle's perimeter. Filling uses the current fill color. The rounded corners of the rectangle are specified by radius r. corners is a string that includes "1" to round the upper-left corner, "2" to round the upper right corner, "3" to round the lower right corner, and "4" to round the lower-left corner. A zero radius means a square corner. The RoundedRect example demonstrates this method.
Example ¶
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const (
wd = 40.0
hgap = 10.0
radius = 10.0
ht = 60.0
vgap = 10.0
)
corner := func(b1, b2, b3, b4 bool) (cstr string) {
if b1 {
cstr = "1"
}
if b2 {
cstr += "2"
}
if b3 {
cstr += "3"
}
if b4 {
cstr += "4"
}
return
}
pdf := document.New("P", "mm", "A4", "") // 210 x 297
pdf.AddPage()
pdf.SetLineWidth(0.5)
y := vgap
r := 40
g := 30
b := 20
for row := range 4 {
x := hgap
for col := range 4 {
pdf.SetFillColor(r, g, b)
pdf.RoundedRect(x, y, wd, ht, radius, corner(row&1 == 1, row&2 == 2, col&1 == 1, col&2 == 2), "FD")
r += 8
g += 10
b += 12
x += wd + hgap
}
y += ht + vgap
}
pdf.AddPage()
pdf.RoundedRectExt(10, 20, 40, 80, 4., 0., 20, 0., "FD")
fileStr := example.Filename("Document_RoundedRect")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_RoundedRect.pdf
func (*Document) RoundedRectExt ¶
RoundedRectExt behaves the same as RoundedRect() but supports a different radius for each corner. A zero radius means a square corner. See RoundedRect() for more details. This method is demonstrated in the RoundedRect() example.
func (*Document) SVGWrite ¶
SVGWrite renders the SVG image described by sb. The scale value converts SVG coordinates to the unit of measure specified in New(). The current position, as set with SetXY(), is used as the image origin.
Example ¶
ExampleDocument_SVGWrite demonstrates how to render a simple SVG image with paths and shapes.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const (
fontPtSize = 16.0
wd = 100.0
)
var (
sig document.SVG
err error
)
pdf := document.New("P", "mm", "A4", "") // A4 210.0 x 297.0
pdf.SetFont("Times", "", fontPtSize)
lineHt := pdf.PointConvert(fontPtSize)
pdf.AddPage()
pdf.SetMargins(10, 10, 10)
htmlStr := `This example renders a simple ` +
`<a href="http://www.w3.org/TR/SVG/">SVG</a> (scalable vector graphics) ` +
`image that contains paths and shapes without any styling, ` +
`color fill, reflection or transforms. In particular, the ` +
`type of vector graphic returned from a ` +
`<a href="http://willowsystems.github.io/jSignature/#/demo/">jSignature</a> ` +
`web control is supported and is used in this example.`
html := pdf.HTMLNew()
html.Write(lineHt, htmlStr)
sig, err = document.SVGParse([]byte(`<svg width="240" height="80" viewBox="0 0 240 80">
<path d="M8 50 C34 18 51 18 61 45 S89 72 112 40 C128 18 143 21 153 44 C162 64 176 62 189 42 C201 23 215 22 232 36" fill="none"/>
</svg>`))
if err == nil {
scale := 100 / sig.Wd
scaleY := 30 / sig.Ht
if scale > scaleY {
scale = scaleY
}
pdf.SetLineCapStyle("round")
pdf.SetLineWidth(0.25)
pdf.SetDrawColor(0, 0, 128)
pdf.SetXY((210.0-scale*sig.Wd)/2.0, pdf.GetY()+10)
pdf.SVGWrite(&sig, scale)
} else {
pdf.SetError(err)
}
fileStr := example.Filename("Document_SVGWrite")
err = pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SVGWrite.pdf
func (*Document) SetAcceptPageBreakFunc ¶
SetAcceptPageBreakFunc allows the application to control where page breaks occur.
fnc is an application function (typically a closure) called by the library whenever a page break condition is met. The break is issued if fnc returns true. The default implementation returns a value according to the mode selected by SetAutoPageBreak. The function provided should not be called by the application.
See the example for SetLeftMargin() to see how this function can be used to manage multiple columns.
Example ¶
This example demonstrates Landscape mode with images.
package main
import (
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func loremList() []string {
return []string{
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " +
"tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " +
"aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum " +
"dolore eu fugiat nulla pariatur.",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " +
"officia deserunt mollit anim id est laborum.",
}
}
func lorem() string {
return strings.Join(loremList(), " ")
}
func main() {
var y0 float64
var crrntCol int
loremStr := lorem()
pdf := document.New("L", "mm", "A4", "")
const (
pageWd = 297.0 // A4 210.0 x 297.0
margin = 10.0
gutter = 4
colNum = 3
colWd = (pageWd - 2*margin - (colNum-1)*gutter) / colNum
)
setCol := func(col int) {
crrntCol = col
x := margin + float64(col)*(colWd+gutter)
pdf.SetLeftMargin(x)
pdf.SetX(x)
}
pdf.SetHeaderFunc(func() {
titleStr := "gopdfkit"
pdf.SetFont("Helvetica", "B", 48)
wd := pdf.GetStringWidth(titleStr) + 6
pdf.SetX((pageWd - wd) / 2)
pdf.SetTextColor(128, 128, 160)
pdf.Write(12, titleStr[:2])
pdf.SetTextColor(128, 128, 128)
pdf.Write(12, titleStr[2:])
pdf.Ln(20)
y0 = pdf.GetY()
})
pdf.SetAcceptPageBreakFunc(func() bool {
if crrntCol < colNum-1 {
setCol(crrntCol + 1)
pdf.SetY(y0)
// Start new column, not new page
return false
}
setCol(0)
return true
})
pdf.AddPage()
pdf.SetFont("Times", "", 12)
for j := range 20 {
switch j {
case 1:
pdf.ImageOptions(example.ImageFile("go_pdf_kit.png"), -1, 0, colWd, 0, true, document.ImageOptions{}, 0, "")
case 5:
pdf.ImageOptions(example.ImageFile("golang-gopher.png"),
-1, 0, colWd, 0, true, document.ImageOptions{}, 0, "")
}
pdf.MultiCell(colWd, 5, loremStr, "", "", false)
pdf.Ln(-1)
}
fileStr := example.Filename("Document_SetAcceptPageBreakFunc_landscape")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetAcceptPageBreakFunc_landscape.pdf
func (*Document) SetAlpha ¶
SetAlpha sets the alpha blending channel. The blending effect applies to text, drawings and images.
alpha must be a value from 0.0 (fully transparent) to 1.0 (fully opaque). Values outside of this range result in an error.
blendModeStr must be one of "Normal", "Multiply", "Screen", "Overlay", "Darken", "Lighten", "ColorDodge", "ColorBurn", "HardLight", "SoftLight", "Difference", "Exclusion", "Hue", "Saturation", "Color", or "Luminosity". An empty string is replaced with "Normal".
To reset normal rendering after applying a blending mode, call this method with alpha set to 1.0 and blendModeStr set to "Normal".
Example ¶
ExampleDocument_SetAlpha demonstrates alpha transparency.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const (
gapX = 10.0
gapY = 9.0
rectW = 40.0
rectH = 58.0
pageW = 210
pageH = 297
)
modeList := []string{"Normal", "Multiply", "Screen", "Overlay",
"Darken", "Lighten", "ColorDodge", "ColorBurn", "HardLight", "SoftLight",
"Difference", "Exclusion", "Hue", "Saturation", "Color", "Luminosity"}
pdf := document.New("", "", "", "")
pdf.SetLineWidth(2)
pdf.SetAutoPageBreak(false, 0)
pdf.AddPage()
pdf.SetFont("Helvetica", "", 18)
pdf.SetXY(0, gapY)
pdf.SetTextColor(0, 0, 0)
pdf.CellFormat(pageW, gapY, "Alpha Blending Modes", "", 0, "C", false, 0, "")
j := 0
y := 3 * gapY
for range 4 {
x := gapX
for range 4 {
pdf.Rect(x, y, rectW, rectH, "D")
pdf.SetFont("Helvetica", "B", 12)
pdf.SetFillColor(0, 0, 0)
pdf.SetTextColor(250, 250, 230)
pdf.SetXY(x, y+rectH-4)
pdf.CellFormat(rectW, 5, modeList[j], "", 0, "C", true, 0, "")
pdf.SetFont("Helvetica", "I", 150)
pdf.SetTextColor(80, 80, 120)
pdf.SetXY(x, y+2)
pdf.CellFormat(rectW, rectH, "A", "", 0, "C", false, 0, "")
pdf.SetAlpha(0.5, modeList[j])
pdf.ImageOptions(example.ImageFile("golang-gopher.png"),
x-gapX, y, rectW+2*gapX, 0, false, document.ImageOptions{}, 0, "")
pdf.SetAlpha(1.0, "Normal")
x += rectW + gapX
j++
}
y += rectH + gapY
}
fileStr := example.Filename("Document_SetAlpha_transparency")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetAlpha_transparency.pdf
func (*Document) SetAttachments ¶
func (f *Document) SetAttachments(as []Attachment)
SetAttachments writes attachments as embedded files attached to the document. These attachments are global; see AddAttachmentAnnotation() for links anchored on a page. Only the last call to SetAttachments is used; previous calls are discarded. Be aware that not all PDF readers support document attachments. See the SetAttachment example for a demonstration of this method.
Example ¶
ExampleDocument_SetTextRenderingMode demonstrates embedding files in PDFs, at the top-level.
package main
import (
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
// Global attachments
file, err := os.ReadFile(example.RepoFile("document", "grid.go"))
if err != nil {
pdf.SetError(err)
}
a1 := document.Attachment{Content: file, Filename: "grid.go"}
file, err = os.ReadFile(example.RepoFile("LICENSE"))
if err != nil {
pdf.SetError(err)
}
a2 := document.Attachment{Content: file, Filename: "License"}
pdf.SetAttachments([]document.Attachment{a1, a2})
fileStr := example.Filename("Document_EmbeddedFiles")
err = pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_EmbeddedFiles.pdf
func (*Document) SetAuthor ¶
SetAuthor sets the document author. isUTF8 indicates whether authorStr is encoded as ISO-8859-1 (false) or UTF-8 (true).
func (*Document) SetAutoPageBreak ¶
SetAutoPageBreak enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
func (*Document) SetCatalogSort ¶
SetCatalogSort sets a flag that will be used, if true, to consistently order the document's internal resource catalogs. This method is typically only used for test purposes to facilitate PDF comparison.
func (*Document) SetCellMargin ¶
SetCellMargin sets the cell margin. This is the amount of space before and after the text within a cell that's left blank, and is in units passed to New().
func (*Document) SetComplianceMetadata ¶ added in v0.5.0
func (f *Document) SetComplianceMetadata(profile ComplianceMetadata)
SetComplianceMetadata enables generated XMP standards identifiers and basic catalog markers for standards-oriented output. It does not replace external validation with veraPDF, a PDF/UA checker, or the Arlington PDF Model checker.
func (*Document) SetCompression ¶
SetCompression activates or deactivates page compression with zlib. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default.
func (*Document) SetCompressionLevel ¶
SetCompressionLevel sets the zlib level used when PDF streams are compressed. Valid values are the constants accepted by compress/zlib.NewWriterLevel, including zlib.HuffmanOnly, zlib.DefaultCompression, zlib.NoCompression and levels 1 through 9. Passing zlib.NoCompression disables Flate compression for page and template streams, matching SetCompression(false).
func (*Document) SetCreationDate ¶
SetCreationDate fixes the document's internal CreationDate value. By default, the time when the document is generated is used for this value. This method is typically only used for testing purposes to facilitate PDF comparison. Specify a zero-value time to revert to the default behavior.
func (*Document) SetCreator ¶
SetCreator sets the document creator. isUTF8 indicates whether creatorStr is encoded as ISO-8859-1 (false) or UTF-8 (true).
func (*Document) SetDashPattern ¶
SetDashPattern sets the dash pattern that is used to draw lines. The dashArray elements are numbers that specify the lengths, in units established in New(), of alternating dashes and gaps. The dash phase specifies the distance into the dash pattern at which to start the dash. The dash pattern is retained from page to page. Call this method with an empty array to restore solid line drawing.
The Beziergon() example demonstrates this method.
func (*Document) SetDisplayMode ¶
SetDisplayMode sets advisory display directives for the document viewer. Pages can be displayed entirely on screen, occupy the full width of the window, use real size, be scaled by a specific zoom factor, or use the viewer default (configured in the Preferences menu of Adobe Reader). The page layout can be specified so that pages are displayed individually or in pairs.
zoomStr can be "fullpage" to display the entire page on screen, "fullwidth" to use the maximum window width, "real" to use real size (equivalent to 100% zoom), or "default" to use the viewer default mode.
layoutStr can be "single" (or "SinglePage") to display one page at once, "continuous" (or "OneColumn") to display pages continuously, "two" (or "TwoColumnLeft") to display two pages on two columns with odd-numbered pages on the left, or "TwoColumnRight" to display two pages on two columns with odd-numbered pages on the right, or "TwoPageLeft" to display pages two at a time with odd-numbered pages on the left, or "TwoPageRight" to display pages two at a time with odd-numbered pages on the right, or "default" to use the viewer default mode.
func (*Document) SetDrawColor ¶
SetDrawColor defines the color used for all drawing operations (lines, rectangles and cell borders). It is expressed in RGB components (0-255). The method can be called before the first page is created. The value is retained from page to page.
func (*Document) SetDrawSpotColor ¶
SetDrawSpotColor sets the current draw color to the spot color associated with name. An error occurs if the name is not associated with a color. The value for tint ranges from 0 (no intensity) to 100 (full intensity). It is quietly capped to this range.
func (*Document) SetError ¶
SetError sets an error to halt PDF generation. This may facilitate error handling by an application. See also Ok(), Err(), and Error().
func (*Document) SetErrorf ¶
SetErrorf sets the internal Document error with formatted text to halt PDF generation; this may facilitate error handling by an application. If an error condition is already set, this call is ignored.
See the documentation for printing in the standard fmt package for details about fmtStr and args.
func (*Document) SetFillColor ¶
SetFillColor defines the color used for all filling operations (filled rectangles and cell backgrounds). It is expressed in RGB components (0-255). The method can be called before the first page is created and the value is retained from page to page.
Example ¶
ExampleDocument_SetFillColor demonstrates how graphic attributes are properly assigned within multiple transformations. See issue #234.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 8)
draw := func(trX, trY float64) {
pdf.TransformBegin()
pdf.TransformTranslateX(trX)
pdf.TransformTranslateY(trY)
pdf.SetLineJoinStyle("round")
pdf.SetLineWidth(0.5)
pdf.SetDrawColor(128, 64, 0)
pdf.SetFillColor(255, 127, 0)
pdf.SetAlpha(0.5, "Normal")
pdf.SetDashPattern([]float64{5, 10}, 0)
pdf.Rect(0, 0, 40, 40, "FD")
pdf.SetFontSize(12)
pdf.SetXY(5, 5)
pdf.Write(0, "Test")
pdf.TransformEnd()
}
draw(5, 5)
draw(50, 50)
fileStr := example.Filename("Document_SetFillColor")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetFillColor.pdf
func (*Document) SetFillSpotColor ¶
SetFillSpotColor sets the current fill color to the spot color associated with name. An error occurs if the name is not associated with a color. The value for tint ranges from 0 (no intensity) to 100 (full intensity). It is quietly capped to this range.
func (*Document) SetFont ¶
SetFont sets the font used to print character strings. It is mandatory to call this method at least once before printing text or the resulting document will not be valid.
The font can be either a standard one or a font added with AddFont() or AddFontFromReader(). Standard fonts use Windows code page 1252 (Western Europe).
The method can be called before the first page is created and the font is kept from page to page. If you just wish to change the current font size, it is simpler to call SetFontSize().
Note: the font definition file must be accessible. An error is set if the file cannot be read.
familyStr specifies the font family. It can be either a name defined by AddFont(), AddFontFromReader() or one of the standard families (case insensitive): "Courier" for fixed-width, "Helvetica" or "Arial" for sans serif, "Times" for serif, "Symbol" or "ZapfDingbats" for symbolic.
styleStr can be "B" (bold), "I" (italic), "U" (underscore), "S" (strike-out) or any combination. The default value (specified with an empty string) is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats.
size is the font size measured in points. The default value is the current size. If no size has been specified since the beginning of the document, this uses 12.
func (*Document) SetFontLoader ¶
func (f *Document) SetFontLoader(loader FontLoader)
SetFontLoader sets a loader used to read font files (.json and .z) from an arbitrary source. If a font loader has been specified, it is used to load the named font resources when AddFont() is called. If this operation fails, an attempt is made to load the resources from the configured font directory (see SetFontLocation()).
Example ¶
ExampleDocument_SetFontLoader demonstrates loading a non-standard font using a generalized font loader. fontResourceType implements the FontLoader interface and is defined locally in the test source code.
package main
import (
"bytes"
"fmt"
"io"
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
type fontResourceType struct {
}
func (f fontResourceType) Open(name string) (rdr io.Reader, err error) {
var buf []byte
buf, err = os.ReadFile(example.FontFile(name))
if err == nil {
rdr = bytes.NewReader(buf)
fmt.Printf("Generalized font loader reading %s\n", name)
}
return
}
func main() {
var fr fontResourceType
pdf := document.New("P", "mm", "A4", "")
pdf.SetFontLoader(fr)
pdf.AddFont("Calligrapher", "", "calligra.json")
pdf.AddPage()
pdf.SetFont("Calligrapher", "", 35)
pdf.Cell(0, 10, "Load fonts from any source")
fileStr := example.Filename("Document_SetFontLoader")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Generalized font loader reading calligra.json Generalized font loader reading calligra.z Successfully generated assets/generated/pdf/Document_SetFontLoader.pdf
func (*Document) SetFontLocation ¶
SetFontLocation sets the filesystem location of the font and font definition files.
func (*Document) SetFontSize ¶
SetFontSize defines the size of the current font. Size is specified in points (1/72 inch). See also SetFontUnitSize().
func (*Document) SetFontStyle ¶
SetFontStyle sets the style of the current font. See also SetFont().
func (*Document) SetFontUnitSize ¶
SetFontUnitSize defines the size of the current font. Size is specified in the unit of measure specified in New(). See also SetFontSize().
func (*Document) SetFooterFunc ¶
func (f *Document) SetFooterFunc(fnc func())
SetFooterFunc sets the function that lets the application render the page footer. The specified function is automatically called by AddPage() and Close() and should not be called directly by the application. The implementation in Document is empty, so you have to provide an appropriate function if you want page footers. fnc will typically be a closure that has access to the Document instance and other document generation variables. See SetFooterFuncLpi for a similar function that passes a last page indicator.
This method is demonstrated in the example for AddPage().
func (*Document) SetFooterFuncLpi ¶
SetFooterFuncLpi sets the function that lets the application render the page footer. The specified function is automatically called by AddPage() and Close() and should not be called directly by the application. It is passed a boolean that is true if the last page of the document is being rendered. The implementation in Document is empty, so you have to provide an appropriate function if you want page footers. fnc will typically be a closure that has access to the Document instance and other document generation variables.
func (*Document) SetHeaderFunc ¶
func (f *Document) SetHeaderFunc(fnc func())
SetHeaderFunc sets the function that lets the application render the page header. The specified function is automatically called by AddPage() and should not be called directly by the application. The implementation in Document is empty, so you have to provide an appropriate function if you want page headers. fnc will typically be a closure that has access to the Document instance and other document generation variables.
A header is a convenient place to put background content that repeats on each page such as a watermark. When this is done, remember to reset the X and Y values so the normal content begins where expected. Including a watermark on each page is demonstrated in the example for TransformRotate.
This method is demonstrated in the example for AddPage().
func (*Document) SetHeaderFuncMode ¶
SetHeaderFuncMode sets the function that lets the application render the page header. See SetHeaderFunc() for more details. The value for homeMode should be set to true to have the current position set to the left and top margin after the header function is called.
func (*Document) SetHomeXY ¶
func (f *Document) SetHomeXY()
SetHomeXY is a convenience method that sets the current position to the left and top margins.
func (*Document) SetJavascript ¶
SetJavascript adds Adobe JavaScript to the document.
Example ¶
ExampleDocument_SetJavascript demonstrates including JavaScript in the document.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetJavascript("print(true);")
pdf.AddPage()
pdf.SetFont("Arial", "", 12)
pdf.Write(10, "Auto-print.")
fileStr := example.Filename("Document_SetJavascript")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetJavascript.pdf
func (*Document) SetKeywords ¶
SetKeywords sets the document keywords. keywordsStr is a space-delimited string, for example "invoice August". isUTF8 indicates whether keywordsStr is encoded as ISO-8859-1 (false) or UTF-8 (true).
Example ¶
This example tests corner cases as reported by the gocov tool.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/font"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
var err error
fileStr := example.Filename("Document_SetKeywords")
err = font.Make(example.FontFile("CalligrapherRegular.pfb"),
example.FontFile("cp1252.map"), example.FontDir(), nil, true)
if err == nil {
pdf := document.New("", "", "", "")
pdf.SetFontLocation(example.FontDir())
pdf.SetTitle("世界", true)
pdf.SetAuthor("世界", true)
pdf.SetSubject("世界", true)
pdf.SetCreator("世界", true)
pdf.SetKeywords("世界", true)
pdf.AddFont("Calligrapher", "", "CalligrapherRegular.json")
pdf.AddPage()
pdf.SetFont("Calligrapher", "", 16)
pdf.Writef(5, "\x95 %s \x95", pdf)
err = pdf.OutputFileAndClose(fileStr)
}
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetKeywords.pdf
func (*Document) SetLeftMargin ¶
SetLeftMargin defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin.
Example ¶
ExampleDocument_SetLeftMargin demonstrates the generation of a PDF document that has multiple columns. This is accomplished with the SetLeftMargin() and Cell() methods.
package main
import (
"fmt"
"os"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
var y0 float64
var crrntCol int
pdf := document.New("P", "mm", "A4", "")
pdf.SetDisplayMode("fullpage", "TwoColumnLeft")
titleStr := "20000 Leagues Under the Seas"
pdf.SetTitle(titleStr, false)
pdf.SetAuthor("Jules Verne", false)
setCol := func(col int) {
// Set position at a given column
crrntCol = col
x := 10.0 + float64(col)*65.0
pdf.SetLeftMargin(x)
pdf.SetX(x)
}
chapterTitle := func(chapNum int, titleStr string) {
// Arial 12
pdf.SetFont("Arial", "", 12)
// Background color
pdf.SetFillColor(200, 220, 255)
// Title
pdf.CellFormat(0, 6, fmt.Sprintf("Chapter %d : %s", chapNum, titleStr),
"", 1, "L", true, 0, "")
// Line break
pdf.Ln(4)
y0 = pdf.GetY()
}
chapterBody := func(fileStr string) {
// Read text file
txtStr, err := os.ReadFile(fileStr)
if err != nil {
pdf.SetError(err)
}
// Font
pdf.SetFont("Times", "", 12)
// Output text in a 6 cm width column
pdf.MultiCell(60, 5, string(txtStr), "", "", false)
pdf.Ln(-1)
// Mention
pdf.SetFont("", "I", 0)
pdf.Cell(0, 5, "(end of excerpt)")
// Go back to first column
setCol(0)
}
printChapter := func(num int, titleStr, fileStr string) {
// Add chapter
pdf.AddPage()
chapterTitle(num, titleStr)
chapterBody(fileStr)
}
pdf.SetAcceptPageBreakFunc(func() bool {
// Method accepting or not automatic page break
if crrntCol < 2 {
// Go to next column
setCol(crrntCol + 1)
// Set ordinate to top
pdf.SetY(y0)
// Keep on page
return false
}
// Go back to first column
setCol(0)
// Page break
return true
})
pdf.SetHeaderFunc(func() {
// Arial bold 15
pdf.SetFont("Arial", "B", 15)
// Calculate width of title and position
wd := pdf.GetStringWidth(titleStr) + 6
pdf.SetX((210 - wd) / 2)
// Colors of frame, background and text
pdf.SetDrawColor(0, 80, 180)
pdf.SetFillColor(230, 230, 0)
pdf.SetTextColor(220, 50, 50)
// Thickness of frame (1 mm)
pdf.SetLineWidth(1)
// Title
pdf.CellFormat(wd, 9, titleStr, "1", 1, "C", true, 0, "")
// Line break
pdf.Ln(10)
// Save ordinate
y0 = pdf.GetY()
})
pdf.SetFooterFunc(func() {
// Position at 1.5 cm from bottom
pdf.SetY(-15)
// Arial italic 8
pdf.SetFont("Arial", "I", 8)
// Text color in gray
pdf.SetTextColor(128, 128, 128)
// Page number
pdf.CellFormat(0, 10, fmt.Sprintf("Page %d", pdf.PageNo()),
"", 0, "C", false, 0, "")
})
printChapter(1, "A RUNAWAY REEF", example.TextFile("20k_c1.txt"))
printChapter(2, "THE PROS AND CONS", example.TextFile("20k_c2.txt"))
fileStr := example.Filename("Document_SetLeftMargin_multicolumn")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetLeftMargin_multicolumn.pdf
func (*Document) SetLineCapStyle ¶
SetLineCapStyle defines the line cap style. styleStr should be "butt", "round" or "square". A square style projects from the end of the line. The method can be called before the first page is created. The value is retained from page to page.
func (*Document) SetLineJoinStyle ¶
SetLineJoinStyle defines the line join style. styleStr should be "miter", "round" or "bevel". The method can be called before the first page is created. The value is retained from page to page.
Example ¶
ExampleDocument_SetLineJoinStyle demonstrates various line cap and line join styles.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const offset = 75.0
pdf := document.New("L", "mm", "A4", "")
pdf.AddPage()
var draw = func(cap, join string, x0, y0, x1, y1 float64) {
// transform begin & end needed to isolate caps and joins
pdf.SetLineCapStyle(cap)
pdf.SetLineJoinStyle(join)
// Draw thick line
pdf.SetDrawColor(0x33, 0x33, 0x33)
pdf.SetLineWidth(30.0)
pdf.MoveTo(x0, y0)
pdf.LineTo((x0+x1)/2+offset, (y0+y1)/2)
pdf.LineTo(x1, y1)
pdf.DrawPath("D")
// Draw thin helping line
pdf.SetDrawColor(0xFF, 0x33, 0x33)
pdf.SetLineWidth(2.56)
pdf.MoveTo(x0, y0)
pdf.LineTo((x0+x1)/2+offset, (y0+y1)/2)
pdf.LineTo(x1, y1)
pdf.DrawPath("D")
}
x := 35.0
caps := []string{"butt", "square", "round"}
joins := []string{"bevel", "miter", "round"}
for i := range caps {
draw(caps[i], joins[i], x, 50, x, 160)
x += offset
}
fileStr := example.Filename("Document_SetLineJoinStyle_caps")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetLineJoinStyle_caps.pdf
func (*Document) SetLineWidth ¶
SetLineWidth defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created. The value is retained from page to page.
func (*Document) SetMargins ¶
SetMargins defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them. If the value of the right margin is less than zero, it is set to the same as the left margin.
func (*Document) SetModificationDate ¶
SetModificationDate fixes the document's internal ModDate value. See SetCreationDate() for more details.
Example ¶
package main
import (
"time"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
// pdfinfo (from http://www.xpdfreader.com) reports the following for this example :
// ~ pdfinfo -box assets/generated/pdf/Document_PageBox.pdf
// Producer: Document 1.9
// CreationDate: Sat Jan 1 00:00:00 2000
// ModDate: Sun Jan 2 10:22:30 2000
pdf := document.New("", "", "", "")
pdf.AddPage()
pdf.SetModificationDate(time.Date(2000, 1, 2, 10, 22, 30, 0, time.UTC))
fileStr := example.Filename("Document_SetModificationDate")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetModificationDate.pdf
func (*Document) SetNextTextArtifact ¶ added in v0.5.0
func (f *Document) SetNextTextArtifact()
SetNextTextArtifact marks the next text operation as an artifact.
func (*Document) SetNextTextRole ¶ added in v0.5.0
SetNextTextRole sets the structure role for the next text operation. Common values are P, H1-H6, L, LI, Lbl, LBody, Caption, Span, and Link.
func (*Document) SetNoCompression ¶
func (f *Document) SetNoCompression()
SetNoCompression disables Flate compression for page and template streams.
func (*Document) SetOutputIntent ¶ added in v0.5.0
SetOutputIntent embeds an ICC output profile and references it from the document catalog. PDF/A output requires a real output intent; callers should pass a valid ICC profile, such as an sRGB profile for DeviceRGB workflows.
func (*Document) SetPage ¶
SetPage sets the current page to that of a valid page in the PDF document. pageNum is one-based. The SetPage() example demonstrates this method.
Example ¶
ExampleDocument_SetPage demomstrates the SetPage() method, allowing content generation to be deferred until all pages have been added.
package main
import (
"math/rand"
"strconv"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
rnd := rand.New(rand.NewSource(0)) // Make reproducible documents
pdf := document.New("L", "cm", "A4", "")
pdf.SetFont("Times", "", 12)
time := []float64{}
temperaturesFromSensors := make([][]float64, 5)
maxs := []float64{25, 41, 89, 62, 11}
for i := range temperaturesFromSensors {
temperaturesFromSensors[i] = make([]float64, 0)
}
for i := 0.0; i < 100; i += 0.5 {
time = append(time, i)
for j, sensor := range temperaturesFromSensors {
dataValue := rnd.Float64() * maxs[j]
sensor = append(sensor, dataValue)
temperaturesFromSensors[j] = sensor
}
}
graphs := []document.GridType{}
pageNums := []int{}
xMax := time[len(time)-1]
for i := range temperaturesFromSensors {
// Create a new page and graph for each sensor we want to graph.
pdf.AddPage()
pdf.Ln(1)
// Custom label per sensor
pdf.WriteAligned(0, 0, "Temperature Sensor "+strconv.Itoa(i+1)+" (C) vs Time (min)", "C")
pdf.Ln(0.5)
graph := document.NewGrid(pdf.GetX(), pdf.GetY(), 20, 10)
graph.TickmarksContainX(0, xMax)
// Custom Y axis
graph.TickmarksContainY(0, maxs[i])
graph.Grid(pdf)
// Save references and locations.
graphs = append(graphs, graph)
pageNums = append(pageNums, pdf.PageNo())
}
// For each X, graph the Y in each sensor.
for i, currTime := range time {
for j, sensor := range temperaturesFromSensors {
pdf.SetPage(pageNums[j])
graph := graphs[j]
temperature := sensor[i]
pdf.Circle(graph.X(currTime), graph.Y(temperature), 0.04, "D")
}
}
fileStr := example.Filename("Document_SetPage")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetPage.pdf
func (*Document) SetPageBox ¶
SetPageBox sets the page box for the current page, and any following pages. Allowable types are trim, trimbox, crop, cropbox, bleed, bleedbox, art and artbox box types are case insensitive.
Example ¶
ExampleDocument_SetPageBox demonstrates the use of a page box
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
// pdfinfo (from http://www.xpdfreader.com) reports the following for this example:
// ~ pdfinfo -box assets/generated/pdf/Document_PageBox.pdf
// Producer: Document 1.9
// CreationDate: Sat Jan 1 00:00:00 2000
// ModDate: Sat Jan 1 00:00:00 2000
// Tagged: no
// Form: none
// Pages: 1
// Encrypted: no
// Page size: 493.23 x 739.85 pts (rotated 0 degrees)
// MediaBox: 0.00 0.00 595.28 841.89
// CropBox: 51.02 51.02 544.25 790.87
// BleedBox: 51.02 51.02 544.25 790.87
// TrimBox: 51.02 51.02 544.25 790.87
// ArtBox: 51.02 51.02 544.25 790.87
// File size: 1053 bytes
// Optimized: no
// PDF version: 1.3
const (
wd = 210
ht = 297
fontsize = 6
boxmargin = 3 * fontsize
)
pdf := document.New("P", "mm", "A4", "") // 210mm x 297mm
pdf.SetPageBox("crop", boxmargin, boxmargin, wd-2*boxmargin, ht-2*boxmargin)
pdf.SetFont("Arial", "", pdf.UnitToPointConvert(fontsize))
pdf.AddPage()
pdf.MoveTo(fontsize, fontsize)
pdf.Write(fontsize, "This will be cropped from printed output")
pdf.MoveTo(boxmargin+fontsize, boxmargin+fontsize)
pdf.Write(fontsize, "This will be displayed in cropped output")
fileStr := example.Filename("Document_PageBox")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_PageBox.pdf
func (*Document) SetPageBoxRec ¶
SetPageBoxRec sets the page box for the current page, and any following pages. Allowable types are trim, trimbox, crop, cropbox, bleed, bleedbox, art and artbox box types are case insensitive. See SetPageBox() for a method that specifies the coordinates and extent of the page box individually.
func (*Document) SetProducer ¶
SetProducer sets the document producer. isUTF8 indicates whether producerStr is encoded as ISO-8859-1 (false) or UTF-8 (true).
func (*Document) SetProtection ¶
SetProtection applies certain constraints on the finished PDF document.
actionFlag is a bit flag that controls various document operations. CnProtectPrint allows the document to be printed. CnProtectModify allows a document to be modified by a PDF editor. CnProtectCopy allows text and images to be copied into the system clipboard. CnProtectAnnotForms allows annotations and forms to be added by a PDF editor. These values can be combined by ORing them together, for example, CnProtectCopy|CnProtectModify. This flag is advisory; not all PDF readers implement the constraints that this argument attempts to control.
userPassStr specifies the password that will need to be provided to view the contents of the PDF. The permissions specified by actionFlag will apply.
ownerPassStr specifies the password that will need to be provided to gain full access to the document regardless of the actionFlag value. An empty string for this argument is replaced with a random value, effectively preventing owner-level access without the generated password.
Example ¶
ExampleDocument_SetProtection demonstrates password protection for documents.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetProtection(document.CnProtectPrint, "123", "abc")
pdf.AddPage()
pdf.SetFont("Arial", "", 12)
pdf.Write(10, "Password-protected.")
fileStr := example.Filename("Document_SetProtection")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SetProtection.pdf
func (*Document) SetRightMargin ¶
SetRightMargin defines the right margin. The method can be called before creating the first page.
func (*Document) SetSubject ¶
SetSubject sets the document subject. isUTF8 indicates whether subjectStr is encoded as ISO-8859-1 (false) or UTF-8 (true).
func (*Document) SetTextColor ¶
SetTextColor defines the color used for text. It is expressed in RGB components (0-255). The method can be called before the first page is created. The value is retained from page to page.
func (*Document) SetTextRenderingMode ¶
SetTextRenderingMode sets the rendering mode of following text. The mode can be as follows: 0: Fill text 1: Stroke text 2: Fill, then stroke text 3: Neither fill nor stroke text (invisible) 4: Fill text and add to path for clipping 5: Stroke text and add to path for clipping 6: Fill, then stroke text and add to path for clipping 7: Add text to path for clipping This method is demonstrated in the SetTextRenderingMode example.
Example ¶
ExampleDocument_SetTextRenderingMode demonstrates rendering modes in PDFs.
package main
import (
"fmt"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "") // 210mm x 297mm
pdf.AddPage()
fontSz := float64(16)
lineSz := pdf.PointToUnitConvert(fontSz)
pdf.SetFont("Times", "", fontSz)
pdf.Write(lineSz, "This document demonstrates various modes of text rendering. Search for \"Mode 3\" "+
"to locate text that has been rendered invisibly. This selection can be copied "+
"into the clipboard as usual and is useful for overlaying onto non-textual elements such "+
"as images to make them searchable.\n\n")
fontSz = float64(125)
lineSz = pdf.PointToUnitConvert(fontSz)
pdf.SetFontSize(fontSz)
pdf.SetTextColor(170, 170, 190)
pdf.SetDrawColor(50, 60, 90)
write := func(mode int) {
pdf.SetTextRenderingMode(mode)
pdf.CellFormat(210, lineSz, fmt.Sprintf("Mode %d", mode), "", 1, "", false, 0, "")
}
for mode := range 4 {
write(mode)
}
write(0)
fileStr := example.Filename("Document_TextRenderingMode")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_TextRenderingMode.pdf
func (*Document) SetTextSpotColor ¶
SetTextSpotColor sets the current text color to the spot color associated with name. An error occurs if the name is not associated with a color. The value for tint ranges from 0 (no intensity) to 100 (full intensity). It is quietly capped to this range.
func (*Document) SetTitle ¶
SetTitle sets the document title. isUTF8 indicates whether titleStr is encoded as ISO-8859-1 (false) or UTF-8 (true).
func (*Document) SetTopMargin ¶
SetTopMargin defines the top margin. The method can be called before creating the first page.
func (*Document) SetUnderlineThickness ¶
SetUnderlineThickness accepts a multiplier for adjusting the text underline thickness, defaulting to 1. See SetUnderlineThickness example.
Example ¶
ExampleDocument_SetUnderlineThickness demonstrates how to adjust the text underline thickness.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "") // 210mm x 297mm
pdf.AddPage()
pdf.SetFont("Arial", "U", 12)
pdf.SetUnderlineThickness(0.5)
pdf.CellFormat(0, 10, "Thin underline", "", 1, "", false, 0, "")
pdf.SetUnderlineThickness(1)
pdf.CellFormat(0, 10, "Normal underline", "", 1, "", false, 0, "")
pdf.SetUnderlineThickness(2)
pdf.CellFormat(0, 10, "Thicker underline", "", 1, "", false, 0, "")
fileStr := example.Filename("Document_UnderlineThickness")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_UnderlineThickness.pdf
func (*Document) SetWordSpacing ¶
SetWordSpacing sets spacing between words of following text. See the WriteAligned() example for a demonstration of its use.
func (*Document) SetX ¶
SetX defines the abscissa of the current position. If the passed value is negative, it is relative to the right of the page.
func (*Document) SetXY ¶
SetXY defines the abscissa and ordinate of the current position. If the passed values are negative, they are relative respectively to the right and bottom of the page.
func (*Document) SetXmpMetadata ¶
SetXmpMetadata defines XMP metadata that will be embedded with the document.
func (*Document) SetY ¶
SetY moves the current abscissa back to the left margin and sets the ordinate. If the passed value is negative, it is relative to the bottom of the page.
func (*Document) SetYWithResetX ¶
SetYWithResetX sets the ordinate and optionally moves the current abscissa back to the left margin. This is the Go-friendly equivalent of FPDF 1.8+'s SetY($y, $resetX) parameter.
func (*Document) SplitLines ¶
SplitLines splits text into several lines using the current font. Each line has its length limited to a maximum width given by w. This function can be used to determine the total height of wrapped text for vertical placement purposes.
This method is useful for codepage-based fonts only. For UTF-8 encoded text, use SplitText().
You can use MultiCell if you want to print text on several lines in a simple way.
Example ¶
ExampleDocument_SplitLines demonstrates Bruno Michel's line splitting function.
package main
import (
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func loremList() []string {
return []string{
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " +
"tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " +
"aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum " +
"dolore eu fugiat nulla pariatur.",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " +
"officia deserunt mollit anim id est laborum.",
}
}
func lorem() string {
return strings.Join(loremList(), " ")
}
func main() {
const (
fontPtSize = 18.0
wd = 100.0
)
pdf := document.New("P", "mm", "A4", "") // A4 210.0 x 297.0
pdf.SetFont("Times", "", fontPtSize)
_, lineHt := pdf.GetFontSize()
pdf.AddPage()
pdf.SetMargins(10, 10, 10)
lines := pdf.SplitLines([]byte(lorem()), wd)
ht := float64(len(lines)) * lineHt
y := (297.0 - ht) / 2.0
pdf.SetDrawColor(128, 128, 128)
pdf.SetFillColor(255, 255, 210)
x := (210.0 - (wd + 40.0)) / 2.0
pdf.Rect(x, y-20.0, wd+40.0, ht+40.0, "FD")
pdf.SetY(y)
for _, line := range lines {
pdf.CellFormat(190.0, lineHt, string(line), "", 1, "C", false, 0, "")
}
fileStr := example.Filename("Document_Splitlines")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_Splitlines.pdf
Example (Tables) ¶
ExampleDocument_SplitLines_tables demonstrates word-wrapped table cells
package main
import (
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func loremList() []string {
return []string{
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " +
"tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " +
"aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum " +
"dolore eu fugiat nulla pariatur.",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " +
"officia deserunt mollit anim id est laborum.",
}
}
func main() {
const (
colCount = 3
colWd = 60.0
marginH = 15.0
lineHt = 5.5
cellGap = 2.0
)
// var colStrList [colCount]string
type cellType struct {
str string
list [][]byte
ht float64
}
var (
cellList [colCount]cellType
cell cellType
)
pdf := document.New("P", "mm", "A4", "") // 210 x 297
header := [colCount]string{"Column A", "Column B", "Column C"}
alignList := [colCount]string{"L", "C", "R"}
strList := loremList()
pdf.SetMargins(marginH, 15, marginH)
pdf.SetFont("Arial", "", 14)
pdf.AddPage()
// Headers
pdf.SetTextColor(224, 224, 224)
pdf.SetFillColor(64, 64, 64)
for colJ := range colCount {
pdf.CellFormat(colWd, 10, header[colJ], "1", 0, "CM", true, 0, "")
}
pdf.Ln(-1)
pdf.SetTextColor(24, 24, 24)
pdf.SetFillColor(255, 255, 255)
// Rows
y := pdf.GetY()
count := 0
for range 2 {
maxHt := lineHt
// Cell height calculation loop
for colJ := range colCount {
count++
if count > len(strList) {
count = 1
}
cell.str = strings.Join(strList[0:count], " ")
cell.list = pdf.SplitLines([]byte(cell.str), colWd-cellGap-cellGap)
cell.ht = float64(len(cell.list)) * lineHt
if cell.ht > maxHt {
maxHt = cell.ht
}
cellList[colJ] = cell
}
// Cell render loop
x := marginH
for colJ := range colCount {
pdf.Rect(x, y, colWd, maxHt+cellGap+cellGap, "D")
cell = cellList[colJ]
cellY := y + cellGap + (maxHt-cell.ht)/2
for splitJ := 0; splitJ < len(cell.list); splitJ++ {
pdf.SetXY(x+cellGap, cellY)
pdf.CellFormat(colWd-cellGap-cellGap, lineHt, string(cell.list[splitJ]), "", 0,
alignList[colJ], false, 0, "")
cellY += lineHt
}
x += colWd
}
y += maxHt + cellGap + cellGap
}
fileStr := example.Filename("Document_SplitLines_tables")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SplitLines_tables.pdf
Example (TextNotesTable) ¶
ExampleDocument_SplitLines_textNotesTable demonstrates wrapped table cells from a pipe-delimited text fixture.
package main
import (
"fmt"
"os"
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
fileStr := example.Filename("Document_TextNotesTable")
txt, err := os.ReadFile(example.TextFile("text-table-notes.txt"))
pdf := document.New("P", "mm", "A4", "")
pdf.SetMargins(18, 18, 18)
pdf.AddPage()
pdf.SetFont("Helvetica", "", 10)
lineHt := 5.0
topicWd := 32.0
detailWd := 130.0
if err == nil {
rows := strings.Split(strings.TrimSpace(string(txt)), "\n")
for rowIndex, row := range rows {
parts := strings.Split(row, "|")
if len(parts) != 2 {
err = fmt.Errorf("invalid text table fixture row: %q", row)
break
}
detailLines := pdf.SplitLines([]byte(parts[1]), detailWd-4)
rowHt := float64(max(1, len(detailLines))) * lineHt
x := pdf.GetX()
y := pdf.GetY()
fill := rowIndex == 0
if fill {
pdf.SetFont("Helvetica", "B", 10)
pdf.SetFillColor(225, 230, 235)
} else {
pdf.SetFont("Helvetica", "", 10)
pdf.SetFillColor(255, 255, 255)
}
pdf.MultiCell(topicWd, lineHt, parts[0], "1", "L", fill)
pdf.SetXY(x+topicWd, y)
pdf.MultiCell(detailWd, lineHt, parts[1], "1", "L", fill)
pdf.SetXY(x, y+rowHt)
}
}
if err == nil {
err = pdf.OutputFileAndClose(fileStr)
}
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_TextNotesTable.pdf
func (*Document) SplitText ¶
SplitText splits UTF-8 encoded text into several lines using the current font. Each line has its length limited to a maximum width given by w. This function can be used to determine the total height of wrapped text for vertical placement purposes.
func (*Document) String ¶
String satisfies the fmt.Stringer interface and summarizes the Document instance.
func (*Document) SubWrite ¶
func (f *Document) SubWrite(ht float64, str string, subFontSize, subOffset float64, link int, linkStr string)
SubWrite prints text from the current position in the same way as Write(). ht is the line height in the unit of measure specified in New(). str specifies the text to write. subFontSize is the size of the font in points. subOffset is the vertical offset of the text in points; a positive value indicates a superscript, a negative value indicates a subscript. link is the identifier returned by AddLink() or 0 for no internal link. linkStr is a target URL or empty for no external link. A non-zero value for link takes precedence over linkStr.
The SubWrite example demonstrates this method.
Example ¶
ExampleDocument_SubWrite demonstrates subscripted and superscripted text Adapted from http://www.fpdf.org/en/script/script61.php
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const (
fontSize = 12
halfX = 105
)
pdf := document.New("P", "mm", "A4", "") // 210mm x 297mm
pdf.AddPage()
pdf.SetFont("Arial", "", fontSize)
_, lineHt := pdf.GetFontSize()
pdf.Write(lineHt, "Hello World!")
pdf.SetX(halfX)
pdf.Write(lineHt, "This is standard text.\n")
pdf.Ln(lineHt * 2)
pdf.SubWrite(10, "H", 33, 0, 0, "")
pdf.Write(10, "ello World!")
pdf.SetX(halfX)
pdf.Write(10, "This is text with a capital first letter.\n")
pdf.Ln(lineHt * 2)
pdf.SubWrite(lineHt, "Y", 6, 0, 0, "")
pdf.Write(lineHt, "ou can also begin the sentence with a small letter. And word wrap also works if the line is too long, like this one is.")
pdf.SetX(halfX)
pdf.Write(lineHt, "This is text with a small first letter.\n")
pdf.Ln(lineHt * 2)
pdf.Write(lineHt, "The world has a lot of km")
pdf.SubWrite(lineHt, "2", 6, 4, 0, "")
pdf.SetX(halfX)
pdf.Write(lineHt, "This is text with a superscripted letter.\n")
pdf.Ln(lineHt * 2)
pdf.Write(lineHt, "The world has a lot of H")
pdf.SubWrite(lineHt, "2", 6, -3, 0, "")
pdf.Write(lineHt, "O")
pdf.SetX(halfX)
pdf.Write(lineHt, "This is text with a subscripted letter.\n")
fileStr := example.Filename("Document_SubWrite")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_SubWrite.pdf
func (*Document) Text ¶
Text prints a character string. The origin (x, y) is at the left edge of the first character's baseline. This method allows a string to be placed precisely on the page, but it is usually easier to use Cell(), MultiCell() or Write(), which are the standard methods for printing text.
func (*Document) Transform ¶
func (f *Document) Transform(tm TransformMatrix)
Transform generally transforms the following text, drawings and images according to the specified matrix. It is typically easier to use the various methods such as TransformRotate() and TransformMirrorVertical() instead.
func (*Document) TransformBegin ¶
func (f *Document) TransformBegin()
TransformBegin sets up a transformation context for subsequent text, drawings and images. The typical usage is to immediately follow a call to this method with a call to one or more of the transformation methods such as TransformScale(), TransformSkew(), etc. This is followed by text, drawing or image output and finally a call to TransformEnd(). All transformation contexts must be properly ended prior to outputting the document.
Example ¶
ExampleDocument_TransformBegin demonstrates various transformations. It is adapted from an example script by Moritz Wagner and Andreas Würmser.
package main
import (
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
const (
light = 200
dark = 0
)
var refX, refY float64
var refStr string
pdf := document.New("P", "mm", "A4", "")
pdf.AddPage()
color := func(val int) {
pdf.SetDrawColor(val, val, val)
pdf.SetTextColor(val, val, val)
}
reference := func(str string, x, y float64, val int) {
color(val)
pdf.Rect(x, y, 40, 10, "D")
pdf.Text(x, y-1, str)
}
refDraw := func(str string, x, y float64) {
refStr = str
refX = x
refY = y
reference(str, x, y, light)
}
refDupe := func() {
reference(refStr, refX, refY, dark)
}
titleStr := "Transformations"
titlePt := 36.0
titleHt := pdf.PointConvert(titlePt)
pdf.SetFont("Helvetica", "", titlePt)
titleWd := pdf.GetStringWidth(titleStr)
titleX := (210 - titleWd) / 2
pdf.Text(titleX, 10+titleHt, titleStr)
pdf.TransformBegin()
pdf.TransformMirrorVertical(10 + titleHt + 0.5)
pdf.ClipText(titleX, 10+titleHt, titleStr, false)
// Remember that the transform will mirror the gradient box too
pdf.LinearGradient(titleX, 10, titleWd, titleHt+4, 120, 120, 120,
255, 255, 255, 0, 0, 0, 0.6)
pdf.ClipEnd()
pdf.TransformEnd()
pdf.SetFont("Helvetica", "", 12)
// Scale by 150% centered by lower left corner of the rectangle
refDraw("Scale", 50, 60)
pdf.TransformBegin()
pdf.TransformScaleXY(150, 50, 70)
refDupe()
pdf.TransformEnd()
// Translate 7 to the right, 5 to the bottom
refDraw("Translate", 125, 60)
pdf.TransformBegin()
pdf.TransformTranslate(7, 5)
refDupe()
pdf.TransformEnd()
// Rotate 20 degrees counter-clockwise centered by the lower left corner of
// the rectangle
refDraw("Rotate", 50, 110)
pdf.TransformBegin()
pdf.TransformRotate(20, 50, 120)
refDupe()
pdf.TransformEnd()
// Skew 30 degrees along the x-axis centered by the lower left corner of the
// rectangle
refDraw("Skew", 125, 110)
pdf.TransformBegin()
pdf.TransformSkewX(30, 125, 110)
refDupe()
pdf.TransformEnd()
// Mirror horizontally with axis of reflection at left side of the rectangle
refDraw("Mirror horizontal", 50, 160)
pdf.TransformBegin()
pdf.TransformMirrorHorizontal(50)
refDupe()
pdf.TransformEnd()
// Mirror vertically with axis of reflection at bottom side of the rectangle
refDraw("Mirror vertical", 125, 160)
pdf.TransformBegin()
pdf.TransformMirrorVertical(170)
refDupe()
pdf.TransformEnd()
// Reflect against a point at the lower left point of rectangle
refDraw("Mirror point", 50, 210)
pdf.TransformBegin()
pdf.TransformMirrorPoint(50, 220)
refDupe()
pdf.TransformEnd()
// Mirror against a straight line described by a point and an angle
angle := -20.0
px := 120.0
py := 220.0
refDraw("Mirror line", 125, 210)
pdf.TransformBegin()
pdf.TransformRotate(angle, px, py)
pdf.Line(px-1, py-1, px+1, py+1)
pdf.Line(px-1, py+1, px+1, py-1)
pdf.Line(px-5, py, px+60, py)
pdf.TransformEnd()
pdf.TransformBegin()
pdf.TransformMirrorLine(angle, px, py)
refDupe()
pdf.TransformEnd()
fileStr := example.Filename("Document_TransformBegin")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_TransformBegin.pdf
func (*Document) TransformEnd ¶
func (f *Document) TransformEnd()
TransformEnd ends a transformation that was begun with TransformBegin().
The TransformBegin() example demonstrates this method.
func (*Document) TransformMirrorHorizontal ¶
TransformMirrorHorizontal horizontally mirrors the following text, drawings and images. x is the axis of reflection.
The TransformBegin() example demonstrates this method.
func (*Document) TransformMirrorLine ¶
TransformMirrorLine symmetrically mirrors the following text, drawings and images on the line defined by angle and the point (x, y). angle is specified in degrees and measured counter-clockwise from the 3 o'clock position.
The TransformBegin() example demonstrates this method.
func (*Document) TransformMirrorPoint ¶
TransformMirrorPoint symmetrically mirrors the following text, drawings and images on the point specified by (x, y).
The TransformBegin() example demonstrates this method.
func (*Document) TransformMirrorVertical ¶
TransformMirrorVertical vertically mirrors the following text, drawings and images. y is the axis of reflection.
The TransformBegin() example demonstrates this method.
func (*Document) TransformRotate ¶
TransformRotate rotates the following text, drawings and images around the center point (x, y). angle is specified in degrees and measured counter-clockwise from the 3 o'clock position.
The TransformBegin() example demonstrates this method.
Example ¶
ExampleDocument_TransformRotate demonstrates how to rotate text within a header to make a watermark that appears on each page.
package main
import (
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func loremList() []string {
return []string{
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " +
"tempor incididunt ut labore et dolore magna aliqua.",
"Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " +
"aliquip ex ea commodo consequat.",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum " +
"dolore eu fugiat nulla pariatur.",
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui " +
"officia deserunt mollit anim id est laborum.",
}
}
func lorem() string {
return strings.Join(loremList(), " ")
}
func main() {
loremStr := lorem() + "\n\n"
pdf := document.New("P", "mm", "A4", "")
margin := 25.0
pdf.SetMargins(margin, margin, margin)
fontHt := 13.0
lineHt := pdf.PointToUnitConvert(fontHt)
markFontHt := 50.0
markLineHt := pdf.PointToUnitConvert(markFontHt)
markY := (297.0 - markLineHt) / 2.0
ctrX := 210.0 / 2.0
ctrY := 297.0 / 2.0
pdf.SetHeaderFunc(func() {
pdf.SetFont("Arial", "B", markFontHt)
pdf.SetTextColor(206, 216, 232)
pdf.SetXY(margin, markY)
pdf.TransformBegin()
pdf.TransformRotate(45, ctrX, ctrY)
pdf.CellFormat(0, markLineHt, "W A T E R M A R K D E M O", "", 0, "C", false, 0, "")
pdf.TransformEnd()
pdf.SetXY(margin, margin)
})
pdf.AddPage()
pdf.SetFont("Arial", "", 8)
for range 25 {
pdf.MultiCell(0, lineHt, loremStr, "", "L", false)
}
fileStr := example.Filename("Document_RotateText")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_RotateText.pdf
func (*Document) TransformScale ¶
TransformScale generally scales the following text, drawings and images. scaleWd and scaleHt are the percentage scaling factors for width and height. (x, y) is at the center of scaling.
The TransformBegin() example demonstrates this method.
func (*Document) TransformScaleX ¶
TransformScaleX scales the width of the following text, drawings and images. scaleWd is the percentage scaling factor. (x, y) is at the center of scaling.
The TransformBegin() example demonstrates this method.
func (*Document) TransformScaleXY ¶
TransformScaleXY uniformly scales the width and height of the following text, drawings and images. s is the percentage scaling factor for both width and height. (x, y) is at the center of scaling.
The TransformBegin() example demonstrates this method.
func (*Document) TransformScaleY ¶
TransformScaleY scales the height of the following text, drawings and images. scaleHt is the percentage scaling factor. (x, y) is at the center of scaling.
The TransformBegin() example demonstrates this method.
func (*Document) TransformSkew ¶
TransformSkew generally skews the following text, drawings and images keeping the point (x, y) stationary. angleX ranges from -90 degrees (skew to the left) to 90 degrees (skew to the right). angleY ranges from -90 degrees (skew to the bottom) to 90 degrees (skew to the top).
The TransformBegin() example demonstrates this method.
func (*Document) TransformSkewX ¶
TransformSkewX horizontally skews the following text, drawings and images keeping the point (x, y) stationary. angleX ranges from -90 degrees (skew to the left) to 90 degrees (skew to the right).
The TransformBegin() example demonstrates this method.
func (*Document) TransformSkewY ¶
TransformSkewY vertically skews the following text, drawings and images keeping the point (x, y) stationary. angleY ranges from -90 degrees (skew to the bottom) to 90 degrees (skew to the top).
The TransformBegin() example demonstrates this method.
func (*Document) TransformTranslate ¶
TransformTranslate moves the following text, drawings and images horizontally and vertically by the amounts specified by tx and ty.
The TransformBegin() example demonstrates this method.
func (*Document) TransformTranslateX ¶
TransformTranslateX moves the following text, drawings and images horizontally by the amount specified by tx.
The TransformBegin() example demonstrates this method.
func (*Document) TransformTranslateY ¶
TransformTranslateY moves the following text, drawings and images vertically by the amount specified by ty.
The TransformBegin() example demonstrates this method.
func (*Document) UnicodeTranslatorFromDescriptor ¶
UnicodeTranslatorFromDescriptor returns a function that can be used to translate, where possible, UTF-8 strings to a form that is compatible with the specified code page. See UnicodeTranslator for more details.
cpStr identifies a code page. A descriptor file in the font directory, set with the fontDirStr argument in the call to New(), should have this name plus the extension ".map". If cpStr is empty, it will be replaced with "cp1252", the gopdfkit code page default.
If an error occurs reading the descriptor, the returned function is valid but does not perform any rune translation.
The CellFormat_codepage example demonstrates this method.
func (*Document) UnitToPointConvert ¶
UnitToPointConvert returns the value of u, expressed in the unit of measure specified in New(), as a value expressed in points (1/72 inch). Since font management in Document uses points, this method can help with setting font sizes based on the sizes of other non-font page elements.
func (*Document) UseImportedPage ¶
UseImportedPage draws a page imported by ImportPage, ImportPageStream, or ImportPagesFromSource. Coordinates and dimensions use the document unit. Passing zero for one dimension preserves the imported page aspect ratio; passing zero for both draws the page at its native size.
func (*Document) UseImportedTemplate ¶
func (f *Document) UseImportedTemplate(tplName string, scaleX float64, scaleY float64, tX float64, tY float64)
UseImportedTemplate draws an imported PDF template onto the current page.
func (*Document) UseTemplate ¶
UseTemplate adds a template to the current page or another template, using the size and position at which it was originally written.
func (*Document) UseTemplateScaled ¶
UseTemplateScaled adds a template to the current page or another template, using the given page coordinates.
func (*Document) Write ¶
Write prints text from the current position. When the right margin is reached (or the \n character is encountered), a line break occurs and text continues from the left margin. When the method returns, the current position is just after the end of the text.
It is possible to put a link on the text.
h indicates the line height in the unit of measure specified in New().
func (*Document) WriteAligned ¶
WriteAligned is an implementation of Write that makes it possible to align text.
width indicates the width of the box the text will be drawn in. This is in the unit of measure specified in New(). If it is set to 0, the bounding box of the page is used (pageWidth - leftMargin - rightMargin).
lineHeight indicates the line height in the unit of measure specified in New().
alignStr sets horizontal alignment of the given textStr. The options are "L", "C" and "R" (Left, Center, Right). The default is "L".
Example ¶
ExampleDocument_WriteAligned demonstrates how to align text with the Write function.
package main
import (
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", example.FontDir())
pdf.SetLeftMargin(50.0)
pdf.SetRightMargin(50.0)
pdf.AddPage()
pdf.SetFont("Helvetica", "", 12)
pdf.WriteAligned(0, 35, "This text is the default alignment, Left", "")
pdf.Ln(35)
pdf.WriteAligned(0, 35, "This text is aligned Left", "L")
pdf.Ln(35)
pdf.WriteAligned(0, 35, "This text is aligned Center", "C")
pdf.Ln(35)
pdf.WriteAligned(0, 35, "This text is aligned Right", "R")
pdf.Ln(35)
line := "This can by used to write justified text"
leftMargin, _, rightMargin, _ := pdf.GetMargins()
pageWidth, _ := pdf.GetPageSize()
pageWidth -= leftMargin + rightMargin
pdf.SetWordSpacing((pageWidth - pdf.GetStringWidth(line)) / float64(strings.Count(line, " ")))
pdf.WriteAligned(pageWidth, 35, line, "L")
fileStr := example.Filename("Document_WriteAligned")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_WriteAligned.pdf
func (*Document) WriteDocument ¶
func (f *Document) WriteDocument(doc *LayoutDocument)
WriteDocument renders a shared document model into the PDF.
func (*Document) WriteLinkID ¶
WriteLinkID writes text that when clicked jumps to another location in the PDF. linkID is an identifier returned by AddLink(). See Write() for argument details.
func (*Document) WriteLinkString ¶
WriteLinkString writes text that when clicked launches an external URL. See Write() for argument details.
Example (TextFixture) ¶
ExampleDocument_WriteLinkString_textFixture demonstrates external links described by a text fixture.
package main
import (
"fmt"
"os"
"strings"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
fileStr := example.Filename("Document_TextInlineLinks")
txt, err := os.ReadFile(example.TextFile("inline-links.txt"))
pdf := document.New("P", "mm", "A4", "")
pdf.SetMargins(20, 20, 20)
pdf.AddPage()
pdf.SetFont("Helvetica", "", 12)
_, lineHt := pdf.GetFontSize()
if err == nil {
for line := range strings.SplitSeq(strings.TrimSpace(string(txt)), "\n") {
parts := strings.Split(line, "|")
if len(parts) != 3 {
err = fmt.Errorf("invalid inline link fixture row: %q", line)
break
}
pdf.SetFont("Helvetica", "B", 12)
pdf.SetTextColor(0, 0, 0)
pdf.Write(lineHt, parts[0]+": ")
pdf.SetFont("Helvetica", "U", 12)
pdf.SetTextColor(0, 0, 180)
pdf.WriteLinkString(lineHt, parts[2], parts[1])
pdf.Ln(lineHt + 3)
}
}
if err == nil {
err = pdf.OutputFileAndClose(fileStr)
}
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_TextInlineLinks.pdf
type DocumentColor ¶
type DocumentColor struct {
R int // Red component, 0-255.
G int // Green component, 0-255.
B int // Blue component, 0-255.
Set bool // Whether this color should be applied.
}
DocumentColor stores an optional RGB color.
type DocumentKind ¶
type DocumentKind string
DocumentKind identifies the high-level purpose of a generated document.
const ( // DocumentKindGeneric is the fallback kind for documents without a more // specific category. DocumentKindGeneric DocumentKind = "generic" // DocumentKindReport identifies report-style documents. DocumentKindReport DocumentKind = "report" // DocumentKindForm identifies forms and questionnaires. DocumentKindForm DocumentKind = "form" // DocumentKindLetter identifies letter-style correspondence. DocumentKindLetter DocumentKind = "letter" // DocumentKindTransactional identifies invoices, receipts, and similar // transactional documents. DocumentKindTransactional DocumentKind = "transactional" // DocumentKindAttestation identifies certificates and attestations. DocumentKindAttestation DocumentKind = "attestation" // DocumentKindStatement identifies account or status statements. DocumentKindStatement DocumentKind = "statement" // DocumentKindLongForm identifies contract-like long-form documents. DocumentKindLongForm DocumentKind = "long-form" )
type DocumentMetadata ¶
type DocumentMetadata struct {
Subject string // Short document subject.
Author string // Document author name.
Organization string // Issuing or owning organization.
DocumentID string // Internal document identifier.
ExternalID string // External system identifier.
VerificationURL string // URL used to verify the document.
CreatedAt time.Time // Document creation timestamp.
UpdatedAt time.Time // Last document update timestamp.
Parties []DocumentParty // People, companies, or roles in the document.
Fields []MetadataField // Additional label/value metadata.
}
DocumentMetadata holds common metadata used by headers, footers, verification blocks, PDF metadata, and structured document summaries.
type DocumentParty ¶
type DocumentParty struct {
Role string // Party role, such as issuer or recipient.
Name string // Party display name.
Identifier string // Tax, account, or other party identifier.
Email string // Party email address.
Phone string // Party phone number.
Address string // Party postal address.
Fields []MetadataField // Additional party metadata.
}
DocumentParty describes a named person, company, or role shown in metadata.
type DocumentTpl ¶
type DocumentTpl struct {
// contains filtered or unexported fields
}
DocumentTpl is a concrete implementation of the Template interface.
func (*DocumentTpl) Bytes ¶
func (t *DocumentTpl) Bytes() []byte
Bytes returns the template data, not including resources.
func (*DocumentTpl) FromPage ¶
func (t *DocumentTpl) FromPage(page int) (Template, error)
FromPage creates a new template from a specific page.
func (*DocumentTpl) FromPages ¶
func (t *DocumentTpl) FromPages() []Template
FromPages creates a template slice with all the pages within a template.
func (*DocumentTpl) GobDecode ¶
func (t *DocumentTpl) GobDecode(buf []byte) error
GobDecode decodes the specified byte buffer into the receiving template.
func (*DocumentTpl) GobEncode ¶
func (t *DocumentTpl) GobEncode() ([]byte, error)
GobEncode encodes the receiving template into a byte buffer. Use GobDecode to decode the byte buffer back to a template.
func (*DocumentTpl) ID ¶
func (t *DocumentTpl) ID() string
ID returns the global template identifier.
func (*DocumentTpl) Images ¶
func (t *DocumentTpl) Images() map[string]*ImageInfo
Images returns the images used in this template.
func (*DocumentTpl) NumPages ¶
func (t *DocumentTpl) NumPages() int
NumPages returns the number of available pages within the template. Use FromPage or FromPages to access that content.
func (*DocumentTpl) Serialize ¶
func (t *DocumentTpl) Serialize() ([]byte, error)
Serialize turns a template into a byte slice for later deserialization.
func (*DocumentTpl) Size ¶
func (t *DocumentTpl) Size() (corner Point, size Size)
Size returns the bounding dimensions of this template.
func (*DocumentTpl) Templates ¶
func (t *DocumentTpl) Templates() []Template
Templates returns the templates used in this template.
type ExtendedImageOptions ¶
type ExtendedImageOptions struct {
X float64 // Image X coordinate.
Y float64 // Image Y coordinate.
W float64 // Requested image width.
H float64 // Requested image height.
Flow bool // Whether placement advances the current Y position.
Options ImageOptions // Image parsing and placement options.
Link int // Internal link identifier.
LinkString string // External link target.
Rotation float64 // Clockwise rotation in degrees.
HorizontalFlip bool // Whether to mirror the image horizontally.
VerticalFlip bool // Whether to mirror the image vertically.
Crop *ImageCrop // Optional crop rectangle.
MaskImage string // Optional soft-mask image name or path.
MaskImageOptions ImageOptions // Options for the soft-mask image.
AltText string // Alternate text for meaningful PDF/UA image content.
Artifact bool // Whether the image is decorative and should be tagged as an artifact.
}
ExtendedImageOptions configures additional image placement options.
type FontCache ¶
type FontCache struct {
// contains filtered or unexported fields
}
FontCache stores parsed UTF-8 TrueType font metrics for reuse across documents. Each Document still receives its own mutable subset state.
func NewFontCache ¶
func NewFontCache() *FontCache
NewFontCache returns an empty reusable UTF-8 font cache.
func (*FontCache) AddUTF8Font ¶
AddUTF8Font loads and parses a TrueType font file into the cache.
func (*FontCache) AddUTF8FontFromBytes ¶
AddUTF8FontFromBytes loads and parses TrueType font bytes into the cache.
type FontDescriptor ¶
type FontDescriptor struct {
// The maximum height above the baseline reached by glyphs in this
// font (for example for "S"). The height of glyphs for accented
// characters shall be excluded.
Ascent int
// The maximum depth below the baseline reached by glyphs in this
// font. The value shall be a negative number.
Descent int
// The vertical coordinate of the top of flat capital letters,
// measured from the baseline (for example "H").
CapHeight int
// A collection of flags defining various characteristics of the
// font. (See the FontFlag* constants.)
Flags int
// A rectangle, expressed in the glyph coordinate system, that
// shall specify the font bounding box. This should be the smallest
// rectangle enclosing the shape that would result if all of the
// glyphs of the font were placed with their origins coincident
// and then filled.
FontBBox fontBoxType
// The angle, expressed in degrees counterclockwise from the
// vertical, of the dominant vertical strokes of the font. (The
// 9-o’clock position is 90 degrees, and the 3-o’clock position
// is –90 degrees.) The value shall be negative for fonts that
// slope to the right, as almost all italic fonts do.
ItalicAngle int
// The thickness, measured horizontally, of the dominant vertical
// stems of glyphs in the font.
StemV int
// The width to use for character codes whose widths are not
// specified in a font dictionary’s Widths array. This shall have
// a predictable effect only if all such codes map to glyphs whose
// actual widths are the same as the value of the MissingWidth
// entry. (Default value: 0.)
MissingWidth int
}
FontDescriptor specifies metrics and other attributes of a font, as distinct from the metrics of individual glyphs, as defined in the PDF specification.
type FontLoader ¶
FontLoader reads font resources from arbitrary locations, such as files, zip archives or embedded font resources.
Open provides an io.Reader for the specified font file (.json or .z). The file name never includes a path. Open returns an error if the specified file cannot be opened.
type FooterBlock ¶
type FooterBlock struct {
}
FooterBlock stores reusable footer content.
func ExtractHTMLFooterBlock ¶
func ExtractHTMLFooterBlock(htmlStr string) (bodyHTML string, footer *FooterBlock)
ExtractHTMLFooterBlock removes the first HTML footer element from an HTML fragment and returns it as a shared FooterBlock.
type FormAnswer ¶
type FormAnswer struct {
Text string // Plain text answer.
Items []string // List answer items.
Table [][]string // Table answer rows.
}
FormAnswer stores a plain, list, or table answer.
type FormDocument ¶
type FormDocument struct {
Title string // Form title.
Sections []FormSection // Form sections in display order.
}
FormDocument describes a generic form that can be rendered as supported HTML or converted into shared document blocks.
type FormQuestion ¶
type FormQuestion struct {
Label string // Question label.
Answer FormAnswer // Question answer.
Required bool // Whether the question is required.
}
FormQuestion stores one question and its answer.
type FormSection ¶
type FormSection struct {
Title string // Section title.
Questions []FormQuestion // Questions in this section.
BreakBefore bool // Insert a page break before this section.
BreakAfter bool // Insert a page break after this section.
KeepTogether bool // Prefer to keep the section on one page.
}
FormSection groups related form questions.
type GridType ¶
type GridType struct {
XLabelIn bool // Whether X-axis labels are drawn inside the graph boundary.
YLabelIn bool // Whether Y-axis labels are drawn inside the graph boundary.
// Whether X-axis labels are rotated.
XLabelRotate bool
XTickStr TickFormatFncType // X-axis tick label formatter; nil omits labels.
YTickStr TickFormatFncType // Y-axis tick label formatter; nil omits labels.
XDiv int // X-axis subdivisions between tickmarks.
YDiv int // Y-axis subdivisions between tickmarks.
ClrText RGBAType // Label color.
ClrMain RGBAType // Main grid line color.
ClrSub RGBAType // Subdivision grid line color.
WdMain float64 // Main grid line width.
WdSub float64 // Subdivision grid line width.
// Label height in points.
TextSize float64
// contains filtered or unexported fields
}
GridType assists with the generation of graphs. It allows the application to work with logical data coordinates rather than page coordinates and assists with the drawing of a background grid.
func NewGrid ¶
NewGrid returns a variable of type GridType that is initialized to draw on a rectangle of width w and height h with the upper left corner positioned at point (x, y). The coordinates are in page units, that is, the same as those specified in New().
The returned variable is initialized with a very simple default tickmark layout that ranges from 0 to 1 in both axes. Prior to calling Grid(), the application may establish a more suitable tickmark layout by calling the methods TickmarksContainX() and TickmarksContainY(). These methods bound the data range with appropriate boundaries and divisions. Alternatively, if the exact extent and divisions of the tickmark layout are known, the methods TickmarksExtentX() and TickmarksExtentY() may be called instead.
Example ¶
ExampleNewGrid demonstrates the generation of graph grids.
package main
import (
"math"
"time"
"github.com/cssbruno/gopdfkit/document"
"github.com/cssbruno/gopdfkit/internal/testsupport/example"
)
func main() {
pdf := document.New("P", "mm", "A4", "")
pdf.SetFont("Arial", "", 12)
pdf.AddPage()
gr := document.NewGrid(13, 10, 187, 130)
gr.TickmarksExtentX(0, 10, 4)
gr.TickmarksExtentY(0, 10, 3)
gr.Grid(pdf)
gr = document.NewGrid(13, 154, 187, 128)
gr.XLabelRotate = true
gr.TickmarksExtentX(0, 1, 12)
gr.XDiv = 5
gr.TickmarksContainY(0, 1.1)
gr.YDiv = 20
// Replace X label formatter with month abbreviation
gr.XTickStr = func(val float64, precision int) string {
return time.Month(math.Mod(val, 12) + 1).String()[0:3]
}
gr.Grid(pdf)
dot := func(x, y float64) {
pdf.Circle(gr.X(x), gr.Y(y), 0.5, "F")
}
pts := []float64{0.39, 0.457, 0.612, 0.84, 0.998, 1.037, 1.015, 0.918, 0.772, 0.659, 0.593, 0.164}
for month, val := range pts {
dot(float64(month)+0.5, val)
}
pdf.SetDrawColor(255, 64, 64)
pdf.SetAlpha(0.5, "Normal")
pdf.SetLineWidth(1.2)
gr.Plot(pdf, 0.5, 11.5, 50, func(x float64) float64 {
// http://www.xuru.org/rt/PR.asp
return 0.227 * math.Exp(-0.0373*x*x+0.471*x)
})
pdf.SetAlpha(1.0, "Normal")
pdf.SetXY(gr.X(0.5), gr.Y(1.35))
pdf.SetFontSize(14)
pdf.Write(0, "Solar energy (MWh) per month, 2016")
pdf.AddPage()
gr = document.NewGrid(13, 10, 187, 274)
gr.TickmarksContainX(2.3, 3.4)
gr.TickmarksContainY(10.4, 56.8)
gr.Grid(pdf)
fileStr := example.Filename("Document_Grid")
err := pdf.OutputFileAndClose(fileStr)
example.Summary(err, fileStr)
}
Output: Successfully generated assets/generated/pdf/Document_Grid.pdf
func (GridType) Ht ¶
Ht converts dataHt, specified in logical data units, to the unit of measure specified in New().
func (GridType) HtAbs ¶
HtAbs returns the absolute value of dataHt, specified in logical data units, that has been converted to the unit of measure specified in New().
func (GridType) Plot ¶
func (g GridType) Plot(pdf *Document, xMin, xMax float64, count int, fnc func(x float64) (y float64))
Plot plots a series of count line segments from xMin to xMax. It repeatedly calls fnc(x) to retrieve the y value associated with x. The currently selected line drawing attributes are used.
func (GridType) Pos ¶
Pos returns the point, in page units, indicated by the relative positions xRel and yRel. These are values between 0 and 1. xRel specifies the relative position between the grid's left and right edges. yRel specifies the relative position between the grid's bottom and top edges.
func (*GridType) TickmarksContainX ¶
TickmarksContainX sets the tickmarks to be shown by Grid in the horizontal dimension. The arguments min and max specify the minimum and maximum values to be contained within the grid. The tickmark values that are generated are suitable for general-purpose graphs.
See TickmarksExtentX for an alternative to this method when the exact values of the tickmarks are to be set by the application.
func (*GridType) TickmarksContainY ¶
TickmarksContainY sets the tickmarks to be shown by Grid in the vertical dimension. The arguments min and max specify the minimum and maximum values to be contained within the grid. The tickmark values that are generated are suitable for general-purpose graphs.
See TickmarksExtentY for an alternative to this method when the exact values of the tickmarks are to be set by the application.
func (*GridType) TickmarksExtentX ¶
TickmarksExtentX sets the tickmarks to be shown by Grid in the horizontal dimension. count specifies the number of major tickmark subdivisions to be graphed. min specifies the leftmost data value. div specifies, in data units, the extent of each major tickmark subdivision.
See TickmarksContainX for an alternative to this method when viewer-friendly tickmarks are to be determined automatically.
func (*GridType) TickmarksExtentY ¶
TickmarksExtentY sets the tickmarks to be shown by Grid in the vertical dimension. count specifies the number of major tickmark subdivisions to be graphed. min specifies the bottommost data value. div specifies, in data units, the extent of each major tickmark subdivision.
See TickmarksContainY for an alternative to this method when viewer-friendly tickmarks are to be determined automatically.
func (GridType) Wd ¶
Wd converts dataWd, specified in logical data units, to the unit of measure specified in New().
func (GridType) WdAbs ¶
WdAbs returns the absolute value of dataWd, specified in logical data units, that has been converted to the unit of measure specified in New().
func (GridType) X ¶
X converts dataX, specified in logical data units, to the X position on the current page.
func (GridType) XRange ¶
XRange returns the minimum and maximum values for the current tickmark sequence. These correspond to the data values of the graph's left and right edges.
func (GridType) XY ¶
XY converts dataX and dataY, specified in logical data units, to the X and Y position on the current page.
type HTML ¶
type HTML struct {
// Link controls the style applied to rendered anchor text.
Link struct {
// ClrR defines the red component of rendered link text.
ClrR int
// ClrG defines the green component of rendered link text.
ClrG int
// ClrB defines the blue component of rendered link text.
ClrB int
// Bold renders link text with a bold font style.
Bold bool
// Italic renders link text with an italic font style.
Italic bool
// Underscore underlines rendered link text.
Underscore bool
}
// AllowLocalImages permits img src values that reference local file paths.
AllowLocalImages bool
// MaxDataImageBytes limits the decoded size of data URI images.
MaxDataImageBytes int
// MaxHTMLBytes limits the size of one HTML fragment.
MaxHTMLBytes int
// MaxElementDepth limits nested HTML element depth.
MaxElementDepth int
// MaxGeneratedPages limits the number of pages one Write call may create.
MaxGeneratedPages int
// MaxTableRows limits the number of rows in one rendered HTML table.
MaxTableRows int
// DebugLog receives best-effort diagnostics for unsupported HTML or CSS.
// Leave nil to keep rendering quiet.
DebugLog func(message string)
// contains filtered or unexported fields
}
HTML is used for rendering a controlled subset of HTML fragments. It supports common text tags, links, paragraphs, headings, lists, tables, images, inline SVG, alignment, font color, font size, and CSS declarations that map directly to gopdfkit text and drawing operations.
HTML is not a browser engine. It does not implement the full HTML parsing algorithm, CSS cascade, layout model, flexbox, grid, floats, positioning, paged media, or browser-grade typography. For predictable output, generate simple content that stays within the documented subset.
func (*HTML) ValidateHTML ¶
ValidateHTML returns best-effort diagnostics for unsupported HTML tags, CSS selectors, and CSS properties without writing anything to the PDF.
func (*HTML) Write ¶
Write prints text from the current position using the currently selected font. See HTMLNew to create a receiver associated with the PDF document instance. The text can use common HTML text tags and inline style declarations. When the right margin is reached, a line break occurs and text continues from the left margin. Upon method exit, the current position is left at the end of the text.
lineHt indicates the line height in the unit of measure specified in New.
func (*HTML) WriteCompiled ¶ added in v0.5.0
func (html *HTML) WriteCompiled(lineHt float64, compiled *CompiledHTML)
WriteCompiled renders a precompiled HTML fragment. Use CompileHTML when the same HTML is rendered repeatedly across documents.
type HTMLSegmentType ¶
type HTMLSegmentType struct {
// Cat identifies the token category: 'T' for text, 'O' for opening tags,
// or 'C' for closing tags.
Cat byte
// Str contains text content for 'T' tokens, or the lower-case tag name for
// 'O' and 'C' tokens.
Str string
// Attr contains lower-case attribute keys for opening tags.
Attr map[string]string
}
HTMLSegmentType identifies one token from a supported HTML fragment: literal text, an opening tag, or a closing tag.
func HTMLTokenize ¶
func HTMLTokenize(htmlStr string) []HTMLSegmentType
HTMLTokenize returns a list of supported HTML tags and literal text elements.
type HTMLTemplateImage ¶
type HTMLTemplateImage struct {
Source string
Alt string
Width string
Height string
MaxWidth string
MaxHeight string
ObjectFit string
Align string
Class string
Style string
Attributes map[string]string
}
HTMLTemplateImage renders a template value as an HTML img tag.
Source is the img src value. It may be a data URL, a registered image name, or a local path when HTML.AllowLocalImages is enabled before rendering. Width, Height, MaxWidth, MaxHeight, ObjectFit, Align, Class, and Style map to normal HTML attributes/CSS supported by HTMLNew.
type HTMLTemplateRaw ¶
type HTMLTemplateRaw string
HTMLTemplateRaw inserts trusted HTML without escaping.
type HTMLTemplateValues ¶
HTMLTemplateValues stores values used by RenderHTMLTemplate. Plain values are HTML-escaped before insertion. Use HTMLTemplateRaw only for trusted HTML.
type HeaderBlock ¶
type HeaderBlock struct {
Blocks []Block // Header content blocks.
Height float64 // Reserved header height.
Box BoxStyle // Header box style.
}
HeaderBlock stores reusable header content.
type HeadingBlock ¶
type HeadingBlock struct {
Level int // Heading level, where 1 is the highest.
Segments []TextSegment // Heading text segments.
Style TextStyle // Heading text style.
Box BoxStyle // Heading box style.
}
HeadingBlock represents a section heading.
func (HeadingBlock) DocumentBlockKind ¶
func (HeadingBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindHeading.
type ImageBlock ¶
type ImageBlock struct {
Source string // Image file path or registered image name.
Data []byte // Inline image bytes.
Format string // Image format, such as png or jpg.
Alt string // Alternative text used by fallback rendering.
Caption []TextSegment // Optional caption text.
Width float64 // Requested image width.
Height float64 // Requested image height.
MaxWidth float64 // Maximum rendered width.
MaxHeight float64 // Maximum rendered height.
Fit ImageFitMode // How the image fits inside its target box.
Align string // Horizontal alignment.
DPI float64 // Optional image DPI override.
Box BoxStyle // Image box style.
}
ImageBlock represents an image and optional caption.
func (ImageBlock) DocumentBlockKind ¶
func (ImageBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindImage.
type ImageCache ¶ added in v0.5.0
type ImageCache struct {
// contains filtered or unexported fields
}
ImageCache stores parsed image data for reuse across documents.
A Document already deduplicates images registered more than once inside that same document. ImageCache is for server-style workloads that create many documents with the same logos or other repeated assets.
func NewImageCache ¶ added in v0.5.0
func NewImageCache() *ImageCache
NewImageCache creates an empty reusable image cache.
func (*ImageCache) Get ¶ added in v0.5.0
func (c *ImageCache) Get(name string) (*ImageInfo, bool)
Get returns a copy of the parsed image stored under name.
func (*ImageCache) RegisterImageOptions ¶ added in v0.5.0
func (c *ImageCache) RegisterImageOptions(name, fileStr string, options ImageOptions) (*ImageInfo, error)
RegisterImageOptions parses and stores an image from a file.
func (*ImageCache) RegisterImageOptionsReader ¶ added in v0.5.0
func (c *ImageCache) RegisterImageOptionsReader(name string, options ImageOptions, r io.Reader) (*ImageInfo, error)
RegisterImageOptionsReader parses and stores an image read from r. ImageType must be set in options when registering from a reader.
type ImageCrop ¶
type ImageCrop struct {
X float64 // Crop origin X coordinate.
Y float64 // Crop origin Y coordinate.
W float64 // Crop width.
H float64 // Crop height.
}
ImageCrop describes a rectangular viewport in the rendered image's units.
type ImageFitMode ¶
type ImageFitMode string
ImageFitMode identifies how an image is fitted into its target box.
const ( // ImageFitAuto preserves the renderer's default image fitting behavior. ImageFitAuto ImageFitMode = "" // ImageFitContain scales the image to fit entirely inside the target box. ImageFitContain ImageFitMode = "contain" // ImageFitCover scales the image to cover the target box, cropping if needed. ImageFitCover ImageFitMode = "cover" )
type ImageInfo ¶
type ImageInfo struct {
// contains filtered or unexported fields
}
ImageInfo stores parsed image data and PDF object metadata for a registered image.
func RegisterThumbnail ¶
func RegisterThumbnail(pdf pdfImageRegistrar, name string, r io.Reader, options ThumbnailOptions) (*ImageInfo, error)
RegisterThumbnail creates a thumbnail from r and registers it with pdf under name.
func (*ImageInfo) Extent ¶
Extent returns the width and height of the image in the units of the Document object.
func (*ImageInfo) GobDecode ¶
GobDecode decodes the specified byte buffer (generated by GobEncode) into the receiving image.
func (*ImageInfo) Height ¶
Height returns the height of the image in the units of the Document object.
func (*ImageInfo) SetDpi ¶
SetDpi sets the dots per inch for an image. PNG images may have their DPI set automatically if the image specifies it. DPI information is not currently available automatically for JPEG, GIF, and WebP images, so callers can set it here when it matters. It defaults to 72 DPI.
type ImageOptions ¶
type ImageOptions struct {
ImageType string // Explicit image type: jpg, png, gif, or webp.
ReadDpi bool // Whether to read DPI metadata from the image.
AllowNegativePosition bool // Whether negative coordinates are preserved.
AltText string // Alternate text for meaningful PDF/UA image content.
Artifact bool // Whether the image is decorative and should be tagged as an artifact.
}
ImageOptions configures image parsing and placement.
ImageType's possible values are case-insensitive: "JPG", "JPEG", "PNG", "GIF", and "WEBP". If empty, the type is inferred from the file extension.
ReadDpi controls whether image DPI information is read automatically from the image file. Normally, this should be set to true, although not all images include DPI metadata. For backward compatibility with previous versions of the API, it defaults to false.
AllowNegativePosition can be set to true to prevent the default coercion of negative x values to the current x position.
type LayoutDocument ¶
type LayoutDocument struct {
Kind DocumentKind // High-level document category.
Title string // Human-readable document title.
Language string // Optional BCP 47 language tag.
Metadata DocumentMetadata // Document metadata and summary fields.
Chrome *PageChrome // Page-level header, footer, and margin settings.
Header *HeaderBlock // Legacy/default header content.
Body []Block // Main document body blocks in render order.
Signature *SignatureBlock // Optional signature block.
QR *QRBlock // Optional standalone QR block.
Attachments []AttachmentBlock // Files embedded during document output.
}
LayoutDocument is the shared model that document builders and HTML parsers can produce before PDF layout and drawing.
func FormDocumentModel ¶
func FormDocumentModel(form FormDocument) *LayoutDocument
FormDocumentModel converts a form into a shared Document.
func LongFormHTMLDocumentModel ¶
func LongFormHTMLDocumentModel(title, htmlStr string) (*LayoutDocument, []string)
LongFormHTMLDocumentModel converts supported long-form HTML into a shared document model with extracted footer configuration.
func NewAttestationDocument ¶
func NewAttestationDocument(title string, blocks ...Block) *LayoutDocument
NewAttestationDocument builds an attestation-style document model.
func NewGenericDocument ¶
func NewGenericDocument(title string, blocks ...Block) *LayoutDocument
NewGenericDocument builds a generic/free-text document model.
func NewLayoutDocument ¶
func NewLayoutDocument(kind DocumentKind) *LayoutDocument
NewLayoutDocument creates a document model with a generic kind when kind is empty.
func NewReportDocument ¶
func NewReportDocument(title string, blocks ...Block) *LayoutDocument
NewReportDocument builds a structured report document model.
func NewStatementDocument ¶
func NewStatementDocument(title string, blocks ...Block) *LayoutDocument
NewStatementDocument builds a statement-style document model.
func NewTransactionalDocument ¶
func NewTransactionalDocument(title string, blocks ...Block) *LayoutDocument
NewTransactionalDocument builds a transactional document model.
func (*LayoutDocument) AddBlock ¶
func (d *LayoutDocument) AddBlock(block Block)
AddBlock appends a non-nil block to the document body.
func (*LayoutDocument) PageChrome ¶
func (d *LayoutDocument) PageChrome() PageChrome
PageChrome returns normalized page-level header and footer configuration.
type ListBlock ¶
type ListBlock struct {
Ordered bool // Whether the list is ordered.
MarkerStyle string // Marker style, such as decimal or bullet.
Items []ListItem // List items.
Style TextStyle // List text style.
Box BoxStyle // List box style.
}
ListBlock represents an ordered or unordered list.
func (ListBlock) DocumentBlockKind ¶
DocumentBlockKind returns BlockKindList.
type ListItem ¶
type ListItem struct {
Blocks []Block // Blocks that make up the list item.
}
ListItem stores the blocks that belong to one list item.
type MeasureContext ¶
type MeasureContext struct {
PDF *Document // PDF state used for font and unit measurements.
Width float64 // Available content width.
DefaultStyle TextStyle // Default text style for measurement.
CellPadding float64 // Default table cell padding.
}
MeasureContext contains the renderer state needed to estimate block layout.
func NewMeasureContext ¶
func NewMeasureContext(pdf *Document, width float64) MeasureContext
NewMeasureContext creates a measurement context for the given content width.
type MetadataField ¶
MetadataField is a label/value pair used by metadata grids and summaries.
type MetadataGridBlock ¶
type MetadataGridBlock struct {
Fields []MetadataField // Metadata fields to render.
Columns int // Number of grid columns.
Style TextStyle // Grid text style.
Box BoxStyle // Grid box style.
}
MetadataGridBlock represents label/value metadata in a grid.
func (MetadataGridBlock) DocumentBlockKind ¶
func (MetadataGridBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindMetadataGrid.
type NoteBoxBlock ¶
type NoteBoxBlock struct {
Title string // Note title.
Body []Block // Note body blocks.
Style TextStyle // Note text style.
Box BoxStyle // Note box style.
}
NoteBoxBlock represents a callout, warning, or highlighted note.
func (NoteBoxBlock) DocumentBlockKind ¶
func (NoteBoxBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindNoteBox.
type Options ¶
type Options struct {
OrientationStr string // Default page orientation.
UnitStr string // Document unit of measure.
SizeStr string // Named page size.
Size Size // Explicit page size override.
FontDirStr string // Font resource directory.
Optimize bool // Use best-compression generation defaults.
}
Options is used with NewWithOptions to customize a Document instance. OrientationStr, UnitStr, SizeStr, and FontDirStr correspond to the arguments accepted by New. If the Wd and Ht fields of Size are each greater than zero, Size will be used to set the default page size rather than SizeStr. Wd and Ht are specified in the units of measure indicated by UnitStr. Optimize enables best-compression generation defaults for page and template streams.
type PDFAMode ¶ added in v0.5.0
type PDFAMode string
PDFAMode identifies the PDF/A metadata profile to advertise.
const ( // PDFAModeNone disables PDF/A standards metadata. PDFAModeNone PDFAMode = "" // PDFAMode4 advertises base PDF/A-4 metadata. PDFAMode4 PDFAMode = "4" // PDFAMode4F advertises PDF/A-4f metadata. PDFAMode4F PDFAMode = "4f" // PDFAMode4E advertises PDF/A-4e metadata. PDFAMode4E PDFAMode = "4e" )
type PageBreakBlock ¶
type PageBreakBlock struct {
Before bool // Insert a page break before following content.
After bool // Insert a page break after preceding content.
}
PageBreakBlock represents an explicit page break.
func (PageBreakBlock) DocumentBlockKind ¶
func (PageBreakBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindPageBreak.
type PageChrome ¶
type PageChrome struct {
Header *HeaderBlock // Default page header.
FirstPageHeader *HeaderBlock // Header used only on page one.
Margins Spacing // Page margins.
PageNumberFormat string // fmt.Sprintf format for page numbers.
TotalPageAlias string // Alias replaced with total page count.
}
PageChrome describes reusable page-level header, footer, and margin options.
func (PageChrome) FooterForPage ¶
func (pc PageChrome) FooterForPage(page int) *FooterBlock
FooterForPage returns the footer block selected for a page.
func (PageChrome) FooterReservedHeight ¶
func (pc PageChrome) FooterReservedHeight() float64
FooterReservedHeight returns the body-layout space reserved for the footer.
func (PageChrome) FooterReservedHeightForPage ¶
func (pc PageChrome) FooterReservedHeightForPage(page int) float64
FooterReservedHeightForPage returns the body-layout footer space for a page.
func (PageChrome) PageNumberText ¶
func (pc PageChrome) PageNumberText(page int) string
PageNumberText formats the footer page number label when enabled.
type ParagraphBlock ¶
type ParagraphBlock struct {
Segments []TextSegment // Paragraph text segments.
Style TextStyle // Paragraph text style.
Box BoxStyle // Paragraph box style.
}
ParagraphBlock represents a paragraph of styled text.
func (ParagraphBlock) DocumentBlockKind ¶
func (ParagraphBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindParagraph.
type Point ¶
Point fields X and Y specify the horizontal and vertical coordinates of a point, typically used in drawing.
type QRBlock ¶
type QRBlock struct {
Value string // Encoded QR value.
Label string // Optional label shown with the QR code.
URL string // Optional verification URL.
Size float64 // Requested QR size.
Align string // Horizontal alignment.
KeepTogether bool // Whether the QR block should stay on one page.
}
QRBlock describes a standalone QR code.
type QRVerificationBlock ¶
type QRVerificationBlock struct {
QR QRBlock // QR code configuration.
Text []TextSegment // Verification text.
Style TextStyle // Verification text style.
Box BoxStyle // Verification box style.
}
QRVerificationBlock combines a QR code with verification text.
func (QRVerificationBlock) DocumentBlockKind ¶
func (QRVerificationBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindQRVerification.
type RGBAType ¶
type RGBAType struct {
R int // Red component, 0-255.
G int // Green component, 0-255.
B int // Blue component, 0-255.
Alpha float64 // Alpha value, 0-1.
}
RGBAType holds red, green, and blue color components in the range 0..255 and an alpha transparency value in the range 0..1.
type RGBType ¶
type RGBType struct {
R int // Red component, 0-255.
G int // Green component, 0-255.
B int // Blue component, 0-255.
}
RGBType holds red, green, and blue color components in the range 0..255.
type SVG ¶
type SVG struct {
Wd float64 // SVG width.
Ht float64 // SVG height.
Segments [][]SVGSegment // Legacy path segment groups.
Paths []SVGPath // Parsed paths.
Texts []SVGText // Parsed text elements.
Images []SVGImage // Embedded raster images.
Elements []SVGElement // Drawable elements in document order.
}
SVG aggregates the information needed to describe a multi-segment vector image.
func SVGFileParse ¶
SVGFileParse parses an SVG file into a descriptor that SVGWrite can render.
type SVGElement ¶
type SVGElement struct {
Kind string // Element kind: path, text, or image.
Path SVGPath // Path data when Kind is path.
Text SVGText // Text data when Kind is text.
Image SVGImage // Image data when Kind is image.
}
SVGElement describes one drawable SVG element in document order.
type SVGGradient ¶
type SVGGradient struct {
Set bool // Whether a gradient is present.
Kind string // Gradient kind: linear or radial.
Units string // SVG gradientUnits value.
X1 float64 // Linear gradient start X coordinate.
Y1 float64 // Linear gradient start Y coordinate.
X2 float64 // Linear gradient end X coordinate.
Y2 float64 // Linear gradient end Y coordinate.
CX float64 // Radial gradient center X coordinate.
CY float64 // Radial gradient center Y coordinate.
FX float64 // Radial gradient focal X coordinate.
FY float64 // Radial gradient focal Y coordinate.
R float64 // Radial gradient radius.
Stops []SVGGradientStop // Gradient stops.
}
SVGGradient describes a linear or radial SVG gradient that SVGWrite can render as a PDF shading fill.
type SVGGradientStop ¶
type SVGGradientStop struct {
Offset float64 // Stop offset from 0 to 1.
Color CSSColorType // Stop color.
Opacity float64 // Stop opacity.
}
SVGGradientStop describes one color stop in a parsed SVG gradient.
type SVGImage ¶
type SVGImage struct {
X float64 // Image X coordinate.
Y float64 // Image Y coordinate.
Wd float64 // Image width.
Ht float64 // Image height.
ImageType string // Embedded image type, such as png or jpg.
Data []byte // Encoded image bytes.
Style SVGStyle // Image style.
}
SVGImage describes one embedded raster image from an SVG image element.
type SVGPath ¶
type SVGPath struct {
Segments []SVGSegment // Path segments.
Style SVGStyle // Path style.
}
SVGPath describes one styled SVG path.
type SVGPattern ¶
type SVGPattern struct {
Set bool // Whether a pattern is present.
Units string // SVG patternUnits value.
X float64 // Pattern origin X coordinate.
Y float64 // Pattern origin Y coordinate.
Wd float64 // Pattern width.
Ht float64 // Pattern height.
Elements []SVGElement // Pattern elements.
}
SVGPattern describes an internal SVG pattern fill that SVGWrite can tile inside a path.
type SVGSegment ¶
type SVGSegment struct {
Cmd byte // Normalized path command.
Arg [6]float64 // Command arguments.
}
SVGSegment describes one normalized SVG path command and its arguments.
type SVGStyle ¶
type SVGStyle struct {
Color CSSColorType // Current text or inherited color.
Stroke CSSColorType // Stroke paint.
Fill CSSColorType // Fill paint.
FillGradient SVGGradient // Fill gradient, when present.
FillPattern SVGPattern // Fill pattern, when present.
StrokeWidth float64 // Stroke width.
FillRule string // Fill rule, such as nonzero or evenodd.
ClipPath []SVGSegment // Inline clip path segments.
ClipRule string // Clip rule.
ClipRef string // Referenced clip path ID.
FillRef string // Referenced fill paint ID.
FontSize float64 // Text font size.
TextAnchor string // SVG text-anchor value.
StrokeLineCap string // Stroke line-cap style.
StrokeLineJoin string // Stroke line-join style.
StrokeDashArray []float64 // Stroke dash pattern.
StrokeDashOffset float64 // Stroke dash phase.
Opacity float64 // Overall opacity.
FillOpacity float64 // Fill opacity.
StrokeOpacity float64 // Stroke opacity.
OpacitySet bool // Whether Opacity was explicitly set.
FillOpacitySet bool // Whether FillOpacity was explicitly set.
StrokeOpacitySet bool // Whether StrokeOpacity was explicitly set.
StrokeDashSet bool // Whether a dash pattern was explicitly set.
Hidden bool // Whether the element should not render.
}
SVGStyle describes drawing attributes parsed from SVG presentation attributes or style declarations.
type SVGText ¶
type SVGText struct {
X float64 // Text X coordinate.
Y float64 // Text Y coordinate.
Text string // Text content.
Role string // Optional tagged PDF role for this text node.
Style SVGStyle // Text style.
}
SVGText describes one SVG text element.
type SectionBlock ¶
type SectionBlock struct {
Title string // Optional section title.
Blocks []Block // Section body blocks.
KeepTitleWithBody bool // Prefer to keep title and first body block together.
Box BoxStyle // Section box style.
}
SectionBlock groups related blocks under an optional title.
func (SectionBlock) DocumentBlockKind ¶
func (SectionBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindSection.
type SignatureBlock ¶
type SignatureBlock struct {
Rows []SignatureRowBlock // Signature rows.
KeepTogether bool // Whether rows should stay together.
PlaceholderReference string // Preferred PAdES signature field name.
}
SignatureBlock groups one or more signature rows.
func (SignatureBlock) PAdESFieldName ¶
func (s SignatureBlock) PAdESFieldName() string
PAdESFieldName returns the signature field name to use with PAdES signing.
type SignatureColumn ¶
type SignatureColumn struct {
Label string // Display label for the signature line.
Name string // Signer name.
Role string // Signer role or title.
Metadata []MetadataField // Additional signer metadata.
Width float64 // Requested column width.
}
SignatureColumn describes a single signature line and its metadata.
type SignatureRowBlock ¶
type SignatureRowBlock struct {
Columns []SignatureColumn // Signature columns.
KeepTogether bool // Whether the row should stay on one page.
Box BoxStyle // Row box style.
}
SignatureRowBlock represents one row of signature columns.
func (SignatureRowBlock) DocumentBlockKind ¶
func (SignatureRowBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindSignatureRow.
type Size ¶
Size fields Wd and Ht specify the horizontal and vertical extents of a document element such as a page.
func (*Size) Orientation ¶
Orientation returns "P" for portrait sizes, "L" for landscape sizes, and an empty string for nil or square sizes.
func (*Size) ScaleToHeight ¶
ScaleToHeight adjusts the width of a size to match height.
func (*Size) ScaleToWidth ¶
ScaleToWidth adjusts the height of a size to match width.
type Spacing ¶
type Spacing struct {
Top float64 // Top spacing.
Right float64 // Right spacing.
Bottom float64 // Bottom spacing.
Left float64 // Left spacing.
}
Spacing stores top, right, bottom, and left measurements in document units.
type StateType ¶
type StateType struct {
// contains filtered or unexported fields
}
StateType holds common drawing values for convenient retrieval with StateGet and restoration with Put.
type TableBlock ¶
type TableBlock struct {
Caption string // Optional table caption.
Columns []TableColumn // Column width constraints.
Header []TableRow // Header rows.
Body []TableRow // Body rows.
Style TableStyle // Table layout options.
Box BoxStyle // Table box style.
}
TableBlock represents a table split into header, body, and footer rows.
func (TableBlock) DocumentBlockKind ¶
func (TableBlock) DocumentBlockKind() BlockKind
DocumentBlockKind returns BlockKindTable.
type TableCell ¶
type TableCell struct {
Blocks []Block // Cell content blocks.
ColSpan int // Number of columns spanned by the cell.
RowSpan int // Number of rows spanned by the cell.
Align string // Horizontal cell alignment.
VerticalAlign string // Vertical cell alignment.
Style TextStyle // Cell text style.
Box BoxStyle // Cell box style.
}
TableCell stores table cell content and layout attributes.
type TableColumn ¶
type TableColumn struct {
Width float64 // Preferred column width.
MinWidth float64 // Minimum column width.
MaxWidth float64 // Maximum column width.
}
TableColumn describes a table column width constraint.
type TableRow ¶
type TableRow struct {
Cells []TableCell // Cells in this row.
KeepTogether bool // Whether the row should stay on one page.
}
TableRow stores table cells and row-level pagination hints.
type TableStyle ¶
type TableStyle struct {
BorderCollapse bool // Whether adjacent cell borders collapse.
RepeatHeader bool // Whether header rows repeat after page breaks.
KeepRows bool // Whether rows should stay together when possible.
}
TableStyle stores renderer-independent table layout options.
type Template ¶
type Template interface {
ID() string
Size() (Point, Size)
Bytes() []byte
Images() map[string]*ImageInfo
Templates() []Template
NumPages() int
FromPage(int) (Template, error)
FromPages() []Template
Serialize() ([]byte, error)
gob.GobDecoder
gob.GobEncoder
}
Template is an object that can be written to, then reused any number of times within a document.
func CreateTpl ¶
func CreateTpl(corner Point, size Size, orientationStr, unitStr, fontDirStr string, fn func(*Tpl)) Template
CreateTpl creates a template not attached to any document.
func DeserializeTemplate ¶
DeserializeTemplate creates a template from a previously serialized template.
type TextSegment ¶
type TextSegment struct {
Text string // Segment text.
Style TextStyle // Style applied to this segment.
Link string // Optional link target.
}
TextSegment is a styled text run.
type TextStyle ¶
type TextStyle struct {
FontFamily string // Font family name.
FontSize float64 // Font size in points.
Bold bool // Whether text is bold.
Italic bool // Whether text is italic.
Underline bool // Whether text is underlined.
StrikeThrough bool // Whether text has a strike-through line.
Color DocumentColor // Optional text color.
Align string // Horizontal alignment, such as L, C, R, or J.
LineHeight float64 // Line height in document units.
}
TextStyle describes common text styling independent of a renderer.
type ThumbnailOptions ¶
type ThumbnailOptions struct {
// MaxWidth is the maximum thumbnail width in pixels. If both MaxWidth and
// MaxHeight are zero, both default to 256.
MaxWidth int
// MaxHeight is the maximum thumbnail height in pixels. If both MaxWidth and
// MaxHeight are zero, both default to 256.
MaxHeight int
// Format may be "png", "jpg", "jpeg", or empty/"auto". Auto keeps JPEG
// sources as JPEG and encodes all other sources as PNG.
Format string
// JPEGQuality controls JPEG output quality. Zero uses the default quality 85.
JPEGQuality int
// Upscale permits thumbnails larger than the source image.
Upscale bool
}
ThumbnailOptions configures thumbnail generation.
type TickFormatFncType ¶
TickFormatFncType defines a callback for label drawing.
type Tpl ¶
type Tpl struct {
Document
}
Tpl is a Document used for writing a template. It has most of the facilities of a Document, but cannot add more pages. Tpl is used directly only during the limited time a template is writable.
type TransformMatrix ¶
type TransformMatrix struct {
A, B, C, D, E, F float64
}
TransformMatrix is used for generalized transformations of text, drawings and images.
Source Files
¶
- attachments.go
- color.go
- color_parse.go
- doc.go
- document.go
- document_builders.go
- document_compliance.go
- document_footer.go
- document_form.go
- document_lifecycle.go
- document_longform.go
- document_measure.go
- document_metadata.go
- document_render.go
- drawing.go
- drawing_clipping.go
- drawing_gradients.go
- drawing_paths.go
- drawing_spotcolor.go
- drawing_transform.go
- font.go
- font_cache.go
- font_core.go
- font_limits.go
- font_loader.go
- font_runtime.go
- font_utf8.go
- geometry.go
- grid.go
- html.go
- html_compiled.go
- html_css.go
- html_images.go
- html_layout.go
- html_tables.go
- html_template.go
- html_tokenizer.go
- html_validation.go
- image.go
- image_cache.go
- image_extended.go
- image_gif.go
- image_info.go
- image_jpeg.go
- image_limits.go
- image_output.go
- image_png.go
- image_webp.go
- labels.go
- layers.go
- layout_document.go
- links.go
- output.go
- output_catalog.go
- output_objects.go
- output_pages.go
- page.go
- page_boxes.go
- pdf_import.go
- pdf_import_parser.go
- pdf_output_format.go
- pdf_signing.go
- protection.go
- qrcode.go
- state.go
- svg.go
- svg_css.go
- svg_geometry.go
- svg_images.go
- svg_parse.go
- svg_write.go
- tagged_pdf.go
- templates.go
- templates_serialize.go
- text.go
- text_cell.go
- text_multicell.go
- text_split.go
- text_subwrite.go
- thumbnail.go
- types.go
- types_font.go
- types_image.go
- types_internal.go
- util_compress.go
- util_encoding.go
- util_io.go
- util_math.go
- watermark.go