Generating PDFs with Golang: A Comprehensive Guide
Introduction to gofpdf
The gofpdf
package is a document generator that provides high-level support for text, drawing, and images. Created by Jung Kurt, this package offers a wide range of features, including page compression, clipping, barcodes, and more. With no dependencies other than the Golang standard library, gofpdf
is an excellent choice for generating PDFs.
Installing Dependencies
To get started, we’ll install two packages: fmt
for printing text to the console and github.com/jung-kurt/gofpdf
for generating PDFs.
package main
import (
"fmt"
"github.com/jung-kurt/gofpdf"
)
Next, navigate to the directory containing your main.go
file and run the command go mod init go-pdf
to initialize Go modules. Then, run go mod tidy
to download the required packages.
Creating Your First PDF
To create a PDF, update your main.go
file with the following code:
func main() {
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello World")
err := pdf.OutputFileAndClose("hello.pdf")
if err!= nil {
fmt.Println(err)
}
}
This code creates a new PDF object, sets the font and cell properties, and writes the text “Hello World” to the PDF. Finally, it saves the PDF to a file called hello.pdf
.
Converting a Text File to PDF
To convert a text file to a PDF, you can use the following code:
func main() {
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "", 14)
file, err := os.Open("lorem.txt")
if err!= nil {
fmt.Println(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
pdf.Cell(0, 10, scanner.Text())
}
err = pdf.OutputFileAndClose("hello.pdf")
if err!= nil {
fmt.Println(err)
}
}
This code reads a text file line by line, writes each line to the PDF, and saves the PDF to a file called hello.pdf
.
Whether you need to generate reports, invoices, or other documents, gofpdf
is an excellent choice for your Golang projects.