pdf

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2021 License: MIT Imports: 16 Imported by: 4

README

one-file-pdf - A minimalist PDF generator in <2K lines and 1 file

Go Report Card Build Status Test Coverage Gitter chat godoc

The main idea behind this project was:
"How small can I make a PDF generator for it to still be useful for 80% of common PDF generation needs?"

The result is a single .go file with less than 1999 lines of code, about 400 of which are color and glyph-size constants, and ~350 are comments.

  • It's easier to learn about the internals of the PDF format with a small, concise library.
  • The current version of the file is indicated in the header (the timestamp).

Features:

  • The essentials for generating PDF documents, sufficient for common business reports.
  • Use all built-in PDF fonts: Courier, Helvetica, Symbol, Times, ZapfDingbats, and their variants
  • Specify colo(u)rs by name (144 web colors), HTML codes (#RRGGBB) or RGB value
  • Set columns for text (like tab stops on the page)
  • Built-in grid option to help measurement and positioning
  • Metadata properties: author, creator, keywords, subject and title
  • Set the measurement units you want: mm, cm, inches, twips or points
  • Draw lines with different thickness
  • Filled or outline rectangles, circles and ellipses
  • JPEG, GIF and transparent PNG images (filled with specified background color)
  • Stream compression can be turned on or off (PDF files normally compress streams to reduce file size, but turning it off helps in debugging or learning about PDF commands)

Not Yet Supported:

  • Unicode (requires font embedding)
  • Font embedding
  • PDF encryption
  • Paths, curves and complex graphics

Installation:

    go get github.com/balacode/one-file-pdf

Naming Convention:

All types in are prefixed with PDF for public, and 'pdf' for private types. The only type you need to use is PDF, while PDFColorNames are left public for reference.

Hello World:

package main 

import (
	"fmt"
	"github.com/balacode/one-file-pdf"
)

func main() {
    fmt.Println(`Generating a "Hello World" PDF...`)

    // create a new PDF using 'A4' page size
    var pdf = pdf.NewPDF("A4")

    // set the measurement units to centimeters
    pdf.SetUnits("cm")

    // draw a grid to help us align stuff (just a guide, not necessary)
    pdf.DrawUnitGrid()

    // draw the word 'HELLO' in orange, using 100pt bold Helvetica font
    // - text is placed on top of, not below the Y-coordinate
    // - you can use method chaining
    pdf.SetFont("Helvetica-Bold", 100).
        SetXY(5, 5).
        SetColor("Orange").
        DrawText("HELLO")

    // draw the word 'WORLD' in blue-violet, using 100pt Helvetica font
    // note that here we use the colo(u)r hex code instead
    // of its name, using the CSS/HTML format: #RRGGBB
    pdf.SetXY(5, 9).
        SetColor("#8A2BE2").
        SetFont("Helvetica", 100).
        DrawText("WORLD!")

    // draw a flower icon using 300pt Zapf-Dingbats font
    pdf.SetX(7).SetY(17).
        SetColorRGB(255, 0, 0).
        SetFont("ZapfDingbats", 300).
        DrawText("a")

    // save the file:
    // if the file exists, it will be overwritten
    // if the file is in use, prints an error message
    pdf.SaveFile("hello.pdf")
} //                                                                        main

Samples:

Click on a sample to see the PDF in more detail.

Changelog:

These are the most recent changes in the functionality of the package, not including internal changes which are best seen in the commits history.

2018-04-14

  • Changed CurrentPage from read-only to read/write property: added SetCurrentPage()
  • Created PageCount() read-only property
  • Created dingbats() demo to generate zapf_dingbats_table.pdf. You can use this table to look up the hex code for each icon.
  • Changed text encoding from /WinAnsiEncoding to /StandardEncoding

See changelog.md for changes made earlier.

Roadmap:

  • Achieve 100% test coverage
  • Create a unit test for every method
  • Unicode support
  • Partial font embedding

Documentation

Overview

Package pdf provides a PDF writer type to generate PDF files. Create a new PDF writer by assigning pdf.NewPDF(paperSize) to a variable. Then call property setters and methods to render the document. Finally, call WriteFile(filename) to save the file, or use Bytes() to get the PDF document as an array of bytes.

Index

Constants

This section is empty.

Variables

View Source
var PDFColorNames = map[string]color.RGBA{} //                                                               PDFColorNames

/* 145 elements not displayed */

PDFColorNames maps web (X11) color names to values. From https://en.wikipedia.org/wiki/X11_color_names

Functions

This section is empty.

Types

type PDF

type PDF struct {
	// contains filtered or unexported fields

} //                                                                         PDF

PDF is the main structure representing a PDF document.

func NewPDF

func NewPDF(paperSize string) PDF

NewPDF creates and initializes a new PDF object. Specify paperSize as: A, B, C series (e.g. "A4") or "LETTER", "LEGAL", "LEDGER", or "TABLOID" To specify a landscape orientation, add "-L" suffix e.g. "A4-L". You can also specify custom paper sizes using "width unit x height unit", for example "20 cm x 20 cm" or even "15cm x 10inch", etc.

func (*PDF) AddPage

func (p *PDF) AddPage() *PDF

AddPage appends a new blank page to the PDF and makes it the current page.

func (*PDF) Bytes

func (p *PDF) Bytes() []byte

Bytes generates the PDF document from various page and auxiliary objects and returns it in an array of bytes, identical to the content of a PDF file. This method is where you'll find the core structure of a PDF document.

func (*PDF) Clean

func (p *PDF) Clean() *PDF

Clean clears all accumulated errors.

func (*PDF) Color

func (p *PDF) Color() color.RGBA

Color returns the current color, which is used for text, lines and fills.

func (*PDF) Compression

func (p *PDF) Compression() bool

Compression returns the current compression mode. If it is true, all PDF content will be compressed when the PDF is generated. If false, most PDF content (excluding images) will be in plain text, which is useful for debugging or to study PDF commands.

func (*PDF) CurrentPage

func (p *PDF) CurrentPage() int

CurrentPage returns the current page's number, starting from 1.

func (*PDF) DocAuthor

func (p *PDF) DocAuthor() string

DocAuthor returns the optional 'document author' metadata property.

func (*PDF) DocCreator

func (p *PDF) DocCreator() string

DocCreator returns the optional 'document creator' metadata property.

func (*PDF) DocKeywords

func (p *PDF) DocKeywords() string

DocKeywords returns the optional 'document keywords' metadata property.

func (*PDF) DocSubject

func (p *PDF) DocSubject() string

DocSubject returns the optional 'document subject' metadata property.

func (*PDF) DocTitle

func (p *PDF) DocTitle() string

DocTitle returns the optional 'document subject' metadata property.

func (*PDF) DrawBox

func (p *PDF) DrawBox(x, y, width, height float64, optFill ...bool) *PDF

DrawBox draws a rectangle of the specified width and height, with the top-left corner starting at point (x, y). To fill the rectangle, pass true in the optional optFill.

func (*PDF) DrawCircle

func (p *PDF) DrawCircle(x, y, radius float64, optFill ...bool) *PDF

DrawCircle draws a circle of radius r centered on (x, y), by drawing 4 Bézier curves (PDF has no circle primitive) To fill the circle, pass true in the optional optFill.

func (*PDF) DrawEllipse

func (p *PDF) DrawEllipse(x, y, xRadius, yRadius float64,
	optFill ...bool) *PDF

DrawEllipse draws an ellipse centered on (x, y), with horizontal radius xRadius and vertical radius yRadius by drawing 4 Bézier curves (PDF has no ellipse primitive). To fill the ellipse, pass true in the optional optFill.

func (*PDF) DrawImage

func (p *PDF) DrawImage(x, y, height float64, fileNameOrBytes interface{},
	backColor ...string) *PDF

DrawImage draws a PNG image. x, y, height specify the position and height of the image. Width is scaled to match the image's aspect ratio. fileNameOrBytes is either a string specifying a file name, or a byte slice with PNG image data.

func (*PDF) DrawLine

func (p *PDF) DrawLine(x1, y1, x2, y2 float64) *PDF

DrawLine draws a straight line from point (x1, y1) to point (x2, y2).

func (*PDF) DrawText

func (p *PDF) DrawText(s string) *PDF

DrawText draws a text string at the current position (X, Y).

func (*PDF) DrawTextAlignedToBox

func (p *PDF) DrawTextAlignedToBox(
	x, y, width, height float64, align, text string) *PDF

DrawTextAlignedToBox draws 'text' within a rectangle specified by 'x', 'y', 'width' and 'height'. If 'align' is blank, the text is center-aligned both vertically and horizontally. Specify 'L' or 'R' to align the text left or right, and 'T' or 'B' to align the text to the top or bottom of the box.

func (*PDF) DrawTextAt

func (p *PDF) DrawTextAt(x, y float64, text string) *PDF

DrawTextAt draws text at the specified point (x, y).

func (*PDF) DrawTextInBox

func (p *PDF) DrawTextInBox(
	x, y, width, height float64, align, text string) *PDF

DrawTextInBox draws word-wrapped text within a rectangle specified by 'x', 'y', 'width' and 'height'. If 'align' is blank, the text is center-aligned both vertically and horizontally. Specify 'L' or 'R' to align the text left or right, and 'T' or 'B' to align the text to the top or bottom of the box.

func (*PDF) DrawUnitGrid

func (p *PDF) DrawUnitGrid() *PDF

DrawUnitGrid draws a light-gray grid demarcated in the current measurement unit. The grid fills the entire page. It helps with item positioning.

func (*PDF) ErrorInfo

func (*PDF) ErrorInfo(err error) (ret struct {
	ID            int
	Msg, Src, Val string
})

ErrorInfo extracts and returns additional error details from PDF errors

func (*PDF) Errors

func (p *PDF) Errors() []error

Errors returns a slice of all accumulated errors.

func (*PDF) FillBox

func (p *PDF) FillBox(x, y, width, height float64) *PDF

FillBox fills a rectangle with the current color.

func (*PDF) FillCircle

func (p *PDF) FillCircle(x, y, radius float64) *PDF

FillCircle fills a circle of radius r centered on (x, y), by drawing 4 Bézier curves (PDF has no circle primitive)

func (*PDF) FillEllipse

func (p *PDF) FillEllipse(x, y, xRadius, yRadius float64) *PDF

FillEllipse fills a Ellipse of radius r centered on (x, y), by drawing 4 Bézier curves (PDF has no ellipse primitive)

func (*PDF) FontName

func (p *PDF) FontName() string

FontName returns the name of the currently-active typeface.

func (*PDF) FontSize

func (p *PDF) FontSize() float64

FontSize returns the current font size in points.

func (*PDF) HorizontalScaling

func (p *PDF) HorizontalScaling() uint16

HorizontalScaling returns the current horizontal scaling in percent.

func (*PDF) LineWidth

func (p *PDF) LineWidth() float64

LineWidth returns the current line width in points.

func (*PDF) NextLine

func (p *PDF) NextLine() *PDF

NextLine advances the text writing position to the next line. I.e. the Y increases by the height of the font and the X-coordinate is reset to zero.

func (*PDF) PageCount

func (p *PDF) PageCount() int

PageCount returns the total number of pages in the document.

func (*PDF) PageHeight

func (p *PDF) PageHeight() float64

PageHeight returns the height of the current page in selected units.

func (*PDF) PageWidth

func (p *PDF) PageWidth() float64

PageWidth returns the width of the current page in selected units.

func (*PDF) PullError

func (p *PDF) PullError() error

PullError removes and returns the first error from the errors collection.

func (*PDF) Reset

func (p *PDF) Reset() *PDF

Reset releases all resources and resets all variables, except paper size.

func (*PDF) SaveFile

func (p *PDF) SaveFile(filename string) error

SaveFile generates and saves the PDF document to a file.

func (*PDF) SetColor

func (p *PDF) SetColor(nameOrHTMLColor string) *PDF

SetColor sets the current color using a web/X11 color name (e.g. "HONEY DEW") or HTML color value such as "#191970" for midnight blue (#RRGGBB). The current color is used for subsequent text and line drawing and fills. If the name is unknown or invalid, sets color to black.

func (*PDF) SetColorRGB

func (p *PDF) SetColorRGB(r, g, b byte) *PDF

SetColorRGB sets the current color using red, green and blue values. The current color is used for subsequent text/line drawing and fills.

func (*PDF) SetColumnWidths

func (p *PDF) SetColumnWidths(widths ...float64) *PDF

SetColumnWidths creates column positions (tab stops) along the X-axis. To remove all column positions, call this method without any argument.

func (*PDF) SetCompression

func (p *PDF) SetCompression(val bool) *PDF

SetCompression sets the compression mode used to generate the PDF. If set to true, all PDF steams will be compressed when the PDF is generated. If false, most content (excluding images) will be in plain text, which is useful for debugging or to study PDF commands.

func (*PDF) SetCurrentPage

func (p *PDF) SetCurrentPage(pageNo int) *PDF

SetCurrentPage opens the specified page. Page numbers start from 1.

func (*PDF) SetDocAuthor

func (p *PDF) SetDocAuthor(s string) *PDF

SetDocAuthor sets the optional 'document author' metadata property.

func (*PDF) SetDocCreator

func (p *PDF) SetDocCreator(s string) *PDF

SetDocCreator sets the optional 'document creator' metadata property.

func (*PDF) SetDocKeywords

func (p *PDF) SetDocKeywords(s string) *PDF

SetDocKeywords sets the optional 'document keywords' metadata property.

func (*PDF) SetDocSubject

func (p *PDF) SetDocSubject(s string) *PDF

SetDocSubject sets the optional 'document subject' metadata property.

func (*PDF) SetDocTitle

func (p *PDF) SetDocTitle(s string) *PDF

SetDocTitle sets the optional 'document title' metadata property.

func (*PDF) SetFont

func (p *PDF) SetFont(name string, points float64) *PDF

SetFont changes the current font name and size in points. For the font name, use one of the standard font names, e.g. 'Helvetica'. This font will be used for subsequent text drawing.

func (*PDF) SetFontName

func (p *PDF) SetFontName(name string) *PDF

SetFontName changes the current font, while using the same font size as the previous font. Use one of the standard font names, such as 'Helvetica'.

func (*PDF) SetFontSize

func (p *PDF) SetFontSize(points float64) *PDF

SetFontSize changes the current font size in points, without changing the currently-selected font typeface.

func (*PDF) SetHorizontalScaling

func (p *PDF) SetHorizontalScaling(percent uint16) *PDF

SetHorizontalScaling changes the horizontal scaling in percent. For example, 200 will stretch text to double its normal width.

func (*PDF) SetLineWidth

func (p *PDF) SetLineWidth(points float64) *PDF

SetLineWidth changes the line width in points.

func (*PDF) SetUnits

func (p *PDF) SetUnits(units string) *PDF

SetUnits changes the current measurement units: mm cm " in inch inches tw twip twips pt point points (can be in any case)

func (*PDF) SetX

func (p *PDF) SetX(x float64) *PDF

SetX changes the X-coordinate of the current drawing position.

func (*PDF) SetXY

func (p *PDF) SetXY(x, y float64) *PDF

SetXY changes both X- and Y-coordinates of the current drawing position.

func (*PDF) SetY

func (p *PDF) SetY(y float64) *PDF

SetY changes the Y-coordinate of the current drawing position.

func (*PDF) TextWidth

func (p *PDF) TextWidth(s string) float64

TextWidth returns the width of the text in current units.

func (*PDF) ToColor

func (p *PDF) ToColor(nameOrHTMLColor string) (color.RGBA, error)

ToColor returns an RGBA color value from a web/X11 color name (e.g. "HONEY DEW") or HTML color value such as "#191970" If the name or code is unknown or invalid, returns zero value (black).

func (*PDF) ToPoints

func (p *PDF) ToPoints(numberAndUnit string) (float64, error)

ToPoints converts a string composed of a number and unit to points. For example '1 cm' or '1cm' becomes 28.346 points. Recognised units: mm cm " in inch inches tw twip twips pt point points

func (*PDF) ToUnits

func (p *PDF) ToUnits(points float64) float64

ToUnits converts points to the currently selected unit of measurement.

func (*PDF) Units

func (p *PDF) Units() string

Units returns the currently selected measurement units. E.g.: mm cm " in inch inches tw twip twips pt point points

func (*PDF) WrapTextLines

func (p *PDF) WrapTextLines(width float64, text string) (ret []string)

WrapTextLines splits a string into multiple lines so that the text fits in the specified width. The text is wrapped on word boundaries. Newline characters ("\r" and "\n") also cause text to be split. You can find out the number of lines needed to wrap some text by checking the length of the returned array.

func (*PDF) X

func (p *PDF) X() float64

X returns the X-coordinate of the current drawing position.

func (*PDF) Y

func (p *PDF) Y() float64

Y returns the Y-coordinate of the current drawing position.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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