Generating PDFs with Golang: A Comprehensive Guide

Golang, one of the fastest-growing programming languages, has a vast array of packages that make development easier. In this article, we’ll explore the gofpdf package, a powerful tool for generating PDFs.

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. Create a new file called main.go and add the following code:
“`go
package main

import (
“fmt”
“github.com/jung-kurt/gofpdf”
)

Next, navigate to the directory containing your
main.gofile and run the commandgo mod init go-pdfto initialize Go modules. Then, rungo mod tidy` to download the required packages.

Creating Your First PDF

To create a PDF, update your main.go file with the following code:
go
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:
go
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.

Conclusion

In this article, we explored the gofpdf package and its features for generating PDFs. We also demonstrated how to convert a text file to a PDF using this package. Whether you need to generate reports, invoices, or other documents, gofpdf is an excellent choice for your Golang projects.

Leave a Reply

Your email address will not be published. Required fields are marked *