How to Create PDF Documents

Pure data is for computers and nerds like you and me. Anyone else likes nicely formatted reports. Go and a good PDF package can help.

The Table Header: Formatted Cells

Having created the initial document, we can now create the table header. This time, we generate a formatted cell with a light grey as the background color.

func header(pdf *gofpdf.Fpdf, hdr []string) *gofpdf.Fpdf {
	pdf.SetFont("Times", "B", 16)
	pdf.SetFillColor(240, 240, 240)
	for _, str := range hdr {

The CellFormat() method takes a couple of parameters to format the cell. We make use of this to create a visible border around the cell, and to enable the background fill.

		pdf.CellFormat(40, 7, str, "1", 0, "", true, 0, "")
	}

Passing -1 to Ln() uses the height of the last printed cell as the line height.

	pdf.Ln(-1)
	return pdf
}

The Table Body

In the same fashion, we can create the table body.

func table(pdf *gofpdf.Fpdf, tbl [][]string) *gofpdf.Fpdf {

Reset font and fill color.

	pdf.SetFont("Times", "", 16)
	pdf.SetFillColor(255, 255, 255)

Every column gets aligned according to its contents.

	align := []string{"L", "C", "L", "R", "R", "R"}
	for _, line := range tbl {
		for i, str := range line {

Again, we need the CellFormat() method to create a visible border around the cell. We also use the alignStr parameter here to print the cell content either left-aligned or right-aligned.

			pdf.CellFormat(40, 7, str, "1", 0, align[i], false, 0, "")
		}
		pdf.Ln(-1)
	}
	return pdf
}

The Image

Next, let’s not forget to impress our boss by adding a fancy image.

func image(pdf *gofpdf.Fpdf) *gofpdf.Fpdf {

The ImageOptions method takes a file path, x, y, width, and height parameters, and an ImageOptions struct to specify a couple of options.

	pdf.ImageOptions("stats.png", 225, 10, 25, 25, false, gofpdf.ImageOptions{ImageType: "PNG", ReadDpi: true}, 0, "")
	return pdf
}

Saving The Document

Finally, the convenience method OutputFileAndClose() lets us save the finished document.

func savePDF(pdf *gofpdf.Fpdf) error {
	return pdf.OutputFileAndClose("report.pdf")
}

How to get and run the code

Step 1: go get the code. Note the -d flag that prevents auto-installing the binary into $GOPATH/bin.

go get -d github.com/appliedgo/pdf

Step 2: cd to the source code directory.

cd $GOPATH/src/github.com/appliedgo/pdf

Step 3. Run the binary.

go run pdf.go

Then you should find a file named “report.pdf” in the same directory. The document should look like this:

The finished report

Try pimping up the report a bit! How about:

  • adjusting the column widths
  • ensuring the table always spans the printable width (and then change the orientation to portrait)
  • aligning the decimal points (hint: cheat a bit by using a fixed-width font)

If you want to look into a real-world scenario, read this blog post from the Gopher Academy Advent series 2017.

And don’t go overboard with the formatting. Less is more.

Happy coding!

comments powered by Disqus