Top Related Projects
Quick Overview
gofpdf is a Go library for generating PDF documents. It's a pure Go implementation, requiring no external dependencies, and provides a wide range of features for creating complex PDF layouts, including text, images, and various drawing operations.
Pros
- Pure Go implementation with no external dependencies
- Comprehensive feature set for PDF generation
- Well-documented with numerous examples
- Active development and community support
Cons
- Learning curve can be steep for complex layouts
- Performance may be slower compared to C-based libraries
- Limited support for advanced PDF features like forms and digital signatures
- Large codebase may be overwhelming for simple use cases
Code Examples
- Creating a simple PDF with text:
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello, World!")
pdf.OutputFileAndClose("hello.pdf")
- Adding an image to a PDF:
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.Image("image.jpg", 10, 10, 100, 0, false, "", 0, "")
pdf.OutputFileAndClose("with_image.pdf")
- Creating a table in PDF:
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Simple Table")
pdf.Ln(12)
pdf.SetFont("Arial", "", 12)
for i := 0; i < 3; i++ {
pdf.CellFormat(40, 10, fmt.Sprintf("Row %d, Col 1", i+1), "1", 0, "", false, 0, "")
pdf.CellFormat(40, 10, fmt.Sprintf("Row %d, Col 2", i+1), "1", 0, "", false, 0, "")
pdf.Ln(-1)
}
pdf.OutputFileAndClose("table.pdf")
Getting Started
To use gofpdf in your Go project, follow these steps:
-
Install the library:
go get github.com/jung-kurt/gofpdf
-
Import the package in your Go code:
import "github.com/jung-kurt/gofpdf"
-
Create a new PDF document and start adding content:
pdf := gofpdf.New("P", "mm", "A4", "") pdf.AddPage() pdf.SetFont("Arial", "B", 16) pdf.Cell(40, 10, "Hello, gofpdf!") pdf.OutputFileAndClose("output.pdf")
This will create a simple PDF file named "output.pdf" with the text "Hello, gofpdf!" in the top-left corner.
Competitor Comparisons
A simple library for generating PDF written in Go lang
Pros of gopdf
- More actively maintained with recent updates
- Better support for Unicode and non-Latin characters
- Simpler API for basic PDF creation tasks
Cons of gopdf
- Less comprehensive documentation compared to gofpdf
- Fewer advanced features and customization options
- Smaller community and ecosystem
Code Comparison
gopdf:
pdf := gopdf.GoPdf{}
pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
pdf.AddPage()
pdf.SetFont("Arial", "", 14)
pdf.Cell(nil, "Hello, World!")
gofpdf:
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 14)
pdf.Cell(40, 10, "Hello, World!")
pdf.OutputFileAndClose("hello.pdf")
Both libraries offer straightforward ways to create simple PDFs, but gopdf's API is slightly more concise. gofpdf provides more explicit control over cell dimensions and file output, while gopdf abstracts some of these details.
When choosing between the two, consider your specific requirements. If you need extensive Unicode support and simpler API for basic tasks, gopdf might be preferable. However, if you require advanced features, extensive documentation, and a larger community, gofpdf could be the better choice.
A maroto way to create PDFs. Maroto is inspired in Bootstrap and uses gofpdf. Fast and simple.
Pros of Maroto
- Higher-level abstraction for creating PDFs, simplifying common tasks
- Built-in support for tables, charts, and other complex elements
- More modern and actively maintained codebase
Cons of Maroto
- Less flexibility for fine-grained control over PDF elements
- Smaller community and fewer resources compared to Gofpdf
- Potentially steeper learning curve for users familiar with low-level PDF creation
Code Comparison
Maroto:
m := maroto.New()
m.Row(40, func() {
m.Col(12, func() {
m.Text("Hello, Maroto!")
})
})
m.OutputFileAndClose("output.pdf")
Gofpdf:
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello, Gofpdf!")
pdf.OutputFileAndClose("output.pdf")
Maroto provides a more structured approach with rows and columns, while Gofpdf offers lower-level control over PDF elements. Maroto's API is designed for ease of use, whereas Gofpdf requires more manual setup but offers greater flexibility.
Golang PDF library for creating and processing PDF files (pure go)
Pros of unipdf
- More comprehensive PDF manipulation capabilities, including reading, editing, and form filling
- Active development with regular updates and improvements
- Better performance for large PDF files
Cons of unipdf
- Commercial license required for most use cases
- Steeper learning curve due to more complex API
- Larger codebase and dependencies
Code comparison
unipdf:
pdf := creator.New()
page := pdf.NewPage()
font, _ := pdf.NewStandardFont(fonts.Helvetica)
text := page.NewTextBox("Hello, World!", 100, 100, 400, 50)
text.SetFont(font)
gofpdf:
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello, World!")
Both libraries allow for creating PDFs and adding text, but unipdf offers more granular control over text positioning and styling. gofpdf has a simpler API for basic operations, making it easier to get started with for simple use cases.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
GoFPDF document generator
Package gofpdf implements a PDF document generator with high level support for text, drawing and images.
Features
- UTF-8 support
- Choice of measurement unit, page format and margins
- Page header and footer management
- Automatic page breaks, line breaks, and text justification
- Inclusion of JPEG, PNG, GIF, TIFF and basic path-only SVG images
- Colors, gradients and alpha channel transparency
- Outline bookmarks
- Internal and external links
- TrueType, Type1 and encoding support
- Page compression
- Lines, Bézier curves, arcs, and ellipses
- Rotation, scaling, skewing, translation, and mirroring
- Clipping
- Document protection
- Layers
- Templates
- Barcodes
- Charting facility
- Import PDFs as templates
gofpdf has no dependencies other than the Go standard library. All tests pass on Linux, Mac and Windows platforms.
gofpdf supports UTF-8 TrueType fonts and âright-to-leftâ languages. Note that Chinese, Japanese, and Korean characters may not be included in many general purpose fonts. For these languages, a specialized font (for example, NotoSansSC for simplified Chinese) can be used.
Also, support is provided to automatically translate UTF-8 runes to code page encodings for languages that have fewer than 256 glyphs.
We Are Closed
This repository will not be maintained, at least for some unknown duration. But it is hoped that gofpdf has a bright future in the open source world. Due to Goâs promise of compatibility, gofpdf should continue to function without modification for a longer time than would be the case with many other languages.
Forks should be based on the last viable commit. Tools such as active-forks can be used to select a fork that looks promising for your needs. If a particular fork looks like it has taken the lead in attracting followers, this README will be updated to point people in that direction.
The efforts of all contributors to this project have been deeply appreciated. Best wishes to all of you.
Installation
To install the package on your system, run
go get github.com/jung-kurt/gofpdf
Later, to receive updates, run
go get -u -v github.com/jung-kurt/gofpdf/...
Quick Start
The following Go code generates a simple PDF file.
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello, world")
err := pdf.OutputFileAndClose("hello.pdf")
See the functions in the fpdf_test.go file (shown as examples in this documentation) for more advanced PDF examples.
Errors
If an error occurs in an Fpdf method, an internal error field is set.
After this occurs, Fpdf method calls typically return without performing
any operations and the error state is retained. This error management
scheme facilitates PDF generation since individual method calls do not
need to be examined for failure; it is generally sufficient to wait
until after Output()
is called. For the same reason, if an error
occurs in the calling application during PDF generation, it may be
desirable for the application to transfer the error to the Fpdf instance
by calling the SetError()
method or the SetErrorf()
method. At any
time during the life cycle of the Fpdf instance, the error state can be
determined with a call to Ok()
or Err()
. The error itself can be
retrieved with a call to Error()
.
Conversion Notes
This package is a relatively straightforward translation from the
original FPDF library written in PHP (despite
the caveat in the introduction to Effective
Go). The API names have been
retained even though the Go idiom would suggest otherwise (for example,
pdf.GetX()
is used rather than simply pdf.X()
). The similarity of
the two libraries makes the original FPDF website a good source of
information. It includes a forum and FAQ.
However, some internal changes have been made. Page content is built up using buffers (of type bytes.Buffer) rather than repeated string concatenation. Errors are handled as explained above rather than panicking. Output is generated through an interface of type io.Writer or io.WriteCloser. A number of the original PHP methods behave differently based on the type of the arguments that are passed to them; in these cases additional methods have been exported to provide similar functionality. Font definition files are produced in JSON rather than PHP.
Example PDFs
A side effect of running go test ./...
is the production of a number
of example PDFs. These can be found in the gofpdf/pdf directory after
the tests complete.
Please note that these examples run in the context of a test. In order
run an example as a standalone application, youâll need to examine
fpdf_test.go
for some helper routines, for example exampleFilename()
and
summary()
.
Example PDFs can be compared with reference copies in order to verify
that they have been generated as expected. This comparison will be
performed if a PDF with the same name as the example PDF is placed in
the gofpdf/pdf/reference directory and if the third argument to
ComparePDFFiles()
in internal/example/example.go is true. (By default
it is false.) The routine that summarizes an example will look for this
file and, if found, will call ComparePDFFiles()
to check the example
PDF for equality with its reference PDF. If differences exist between
the two files they will be printed to standard output and the test will
fail. If the reference file is missing, the comparison is considered to
succeed. In order to successfully compare two PDFs, the placement of
internal resources must be consistent and the internal creation
timestamps must be the same. To do this, the methods SetCatalogSort()
and SetCreationDate()
need to be called for both files. This is done
automatically for all examples.
Nonstandard Fonts
Nothing special is required to use the standard PDF fonts (courier,
helvetica, times, zapfdingbats) in your documents other than calling
SetFont()
.
You should use AddUTF8Font()
or AddUTF8FontFromBytes()
to add a
TrueType UTF-8 encoded font. Use RTL()
and LTR()
methods switch
between âright-to-leftâ and âleft-to-rightâ mode.
In order to use a different non-UTF-8 TrueType or Type1 font, you will need to generate a font definition file and, if the font will be embedded into PDFs, a compressed version of the font file. This is done by calling the MakeFont function or using the included makefont command line utility. To create the utility, cd into the makefont subdirectory and run âgo buildâ. This will produce a standalone executable named makefont. Select the appropriate encoding file from the font subdirectory and run the command as in the following example.
./makefont --embed --enc=../font/cp1252.map --dst=../font ../font/calligra.ttf
In your PDF generation code, call AddFont()
to load the font and, as
with the standard fonts, SetFont() to begin using it. Most examples,
including the package example, demonstrate this method. Good sources of
free, open-source fonts include Google
Fonts and DejaVu
Fonts.
Related Packages
The draw2d package is a two dimensional vector graphics library that can generate output in different forms. It uses gofpdf for its document production mode.
Contributing Changes
gofpdf is a global community effort and you are invited to make it even
better. If you have implemented a new feature or corrected a problem,
please consider contributing your change to the project. A contribution
that does not directly pertain to the core functionality of gofpdf
should be placed in its own directory directly beneath the contrib
directory.
Here are guidelines for making submissions. Your change should
- be compatible with the MIT License
- be properly documented
- be formatted with
go fmt
- include an example in fpdf_test.go if appropriate
- conform to the standards of golint
and go vet, that is,
golint .
andgo vet .
should not generate any warnings - not diminish test coverage
Pull requests are the preferred means of accepting your changes.
License
gofpdf is released under the MIT License. It is copyrighted by Kurt Jung and the contributors acknowledged below.
Acknowledgments
This packageâs code and documentation are closely derived from the FPDF library created by Olivier Plathey, and a number of font and image resources are copied directly from it. Bruno Michel has provided valuable assistance with the code. Drawing support is adapted from the FPDF geometric figures script by David Hernández Sanz. Transparency support is adapted from the FPDF transparency script by Martin Hall-May. Support for gradients and clipping is adapted from FPDF scripts by Andreas Würmser. Support for outline bookmarks is adapted from Olivier Plathey by Manuel Cornes. Layer support is adapted from Olivier Plathey. Support for transformations is adapted from the FPDF transformation script by Moritz Wagner and Andreas Würmser. PDF protection is adapted from the work of Klemen Vodopivec for the FPDF product. Lawrence Kesteloot provided code to allow an imageâs extent to be determined prior to placement. Support for vertical alignment within a cell was provided by Stefan Schroeder. Ivan Daniluk generalized the font and image loading code to use the Reader interface while maintaining backward compatibility. Anthony Starks provided code for the Polygon function. Robert Lillack provided the Beziergon function and corrected some naming issues with the internal curve function. Claudio Felber provided implementations for dashed line drawing and generalized font loading. Stani Michiels provided support for multi-segment path drawing with smooth line joins, line join styles, enhanced fill modes, and has helped greatly with package presentation and tests. Templating is adapted by Marcus Downing from the FPDF_Tpl library created by Jan Slabon and Setasign. Jelmer Snoeck contributed packages that generate a variety of barcodes and help with registering images on the web. Jelmer Snoek and Guillermo Pascual augmented the basic HTML functionality with aligned text. Kent Quirk implemented backwards-compatible support for reading DPI from images that support it, and for setting DPI manually and then having it properly taken into account when calculating image size. Paulo Coutinho provided support for static embedded fonts. Dan Meyers added support for embedded JavaScript. David Fish added a generic alias-replacement function to enable, among other things, table of contents functionality. Andy Bakun identified and corrected a problem in which the internal catalogs were not sorted stably. Paul Montag added encoding and decoding functionality for templates, including images that are embedded in templates; this allows templates to be stored independently of gofpdf. Paul also added support for page boxes used in printing PDF documents. Wojciech Matusiak added supported for word spacing. Artem Korotkiy added support of UTF-8 fonts. Dave Barnes added support for imported objects and templates. Brigham Thompson added support for rounded rectangles. Joe Westcott added underline functionality and optimized image storage. Benoit KUGLER contributed support for rectangles with corners of unequal radius, modification times, and for file attachments and annotations.
Roadmap
- Remove all legacy code page font support; use UTF-8 exclusively
- Improve test coverage as reported by the coverage tool.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot