Site icon Voina Blog (a tech warrior's blog)

Libraries #golang : A PDF document generator with high level support for text, drawing and images

Advertisements

The best golang library for generating pdfs. It has so many features and you can control so well the layout of the pdf that I can compare it to LateX level.

Package gofpdf implements a PDF document generator with high level support for text, drawing and images.

You can find the library at https://github.com/jung-kurt/gofpdf

And the extensive godoc at https://godoc.org/github.com/jung-kurt/gofpdf

It is extremely easy to use:

...
// initiate pdf
pdf := gofpdf.New("P", "pt", "A5", "")

// add the proper ISO-8859-16 Romanian font
pdf.AddFont("romanianCustom", "", "romanianCustom.json")
// pdf.AddFont("romanianCustomBold", "", "romanianCustomBold.json")

// Make the appropriate code page translator
tr := pdf.UnicodeTranslatorFromDescriptor("iso-8859-16")
// Populate pdf
...
// define pdf header with an image
pdf.SetHeaderFunc(func() {
		pdf.SetY(15)
		pdf.Image("logo.png", 25, 20, 70, 0, false, "", 0, "")
		pdf.SetFont("Arial", "B", 18)
		pdf.CellFormat(0, 18, label, "", 0, "R", false, 0, "")

		pdf.SetY(40)
		pdf.SetFont("romanianCustom", "", 14)
		pdf.CellFormat(0, 14, "Header Text", "", 0, "R", false, 0, "")

	})

// define pdf footer
pdf.SetFooterFunc(func() {
		pdf.SetY(-35)
		pdf.SetFont("romanianCustom", "", 12)
		pdf.CellFormat(0, 12, "Footer 1", "", 1, "L", false, 0, "")
		pdf.CellFormat(0, 12, "Footer 2", "", 1, "L", false, 0, "")
	})

// define pdf Body
pdf.AddPage()
pdf.SetY(100)
pdf.SetFont("romanianCustom", "", 12)

pdf.CellFormat(0, 12, "This is a left body text", "", 0, "L", false, 0, "")
pdf.CellFormat(0, 12, "This is a right body text", "", 1, "R", false, 0, "")

// embed an image in pdf Body
pdf.Image("embeded_logo.png", 30, 380, 50, 0, false, "", 0, "")
fileName := "pdf/test.pdf"

// save pdf to disk
err := pdf.OutputFileAndClose(fileName)
...

What I like about golang is the fact that one can find lots of golang free libraries on github .

This is a series of small blog posts where I share my discoveries.

Exit mobile version