How to Write PDFs in Golang: A Beginner’s Guide

If you’re a developer who uses the Go programming language (Golang), you’ve probably been drawn to its simplicity, speed, and efficiency. However, you might be wondering, “how can I use Golang to write PDFs?” Well, you’re in luck because that’s exactly what we’re going to cover in this article.

In this comprehensive guide, we will explore the process of generating PDFs using Golang. While we’ll primarily focus on the gofpdf library as a starting point for beginners, we’ll also introduce you to the UniPDF library by UniDoc for more advanced reporting needs. With this step-by-step guide, you’ll gain the skills to create PDFs confidently using the right tool for your needs. Whether you’re a beginner or looking to expand your Golang PDF capabilities, this guide is designed to help you navigate the landscape of PDF generation with Golang on the UniDoc platform.

Table of Contents

  1. Introduction to PDF Generation
  2. Why Golang for PDF Generation?
  3. Installing the Gofpdf Library
  4. Creating Your First PDF in Golang
  5. Adding Images and Fonts to Your PDF
  6. Advanced Techniques for PDF Creation
  7. Introduction to UniPDF for Advanced PDF Generation
  8. Conclusion

1. Introduction to PDF Generation

Portable Document Format (PDF) is a file format that has captured the digital world due to its ability to preserve the fonts, images, graphics, and layout of any source document, regardless of the computer or software used to create it. If you’re interested in delving deeper into the world of PDFs, Adobe has an excellent guide that covers everything you need to know.

When we talk about creating PDFs programmatically, we mean generating PDF files directly from code. This can be particularly useful for creating reports, invoices, or any other types of documents where data needs to be presented in a structured and visually appealing format.

2. Why Golang for PDF Generation?

You might be wondering, “Why should I use Golang for PDF generation?” While there are many programming languages you could use, Golang stands out for several reasons: 

  1. Speed: Golang is compiled to machine code, which means it runs incredibly fast. This is beneficial when generating large PDFs that contain lots of data. 
  2. Concurrency: Golang’s approach to concurrency allows multiple PDFs to be generated simultaneously without blocking the system. 
  3. Simplicity: Golang is easy to learn and use, thanks to its simple syntax. This makes it a good choice for beginners. 
  4. Rich Library Support: Golang has a rich standard library and a number of third-party libraries, like gofpdf, which make PDF generation simple and efficient. 

3. Installing the Gofpdf Library

Before we can start writing PDFs, we first need to install the gofpdf library. This library provides a simple interface for creating PDF documents in Golang.  To install gofpdf, you can use the go get command

go get github.com/jung-kurt/gofpdf

4. Creating Your First PDF in Golang

Now that we’ve installed gofpdf, let’s dive into creating our first PDF. Here’s a simple example that creates a PDF with a single line of text using the gofpdf library

package main

import (
    "github.com/jung-kurt/gofpdf"
)

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 {
        panic(err)
    }
}

Let’s break this down: 

  1. We start by importing the gofpdf package. 
  2. We then initialize a new PDF document with gofpdf.New(“P”, “mm”, “A4”, “"). The arguments here specify the page orientation (“P” for portrait), the unit of measurement (“mm” for millimeters), the size (“A4”), and the font directory (”" for none). 
  3. We add a new page to the document with pdf.AddPage(). 
  4. We set the font to Arial, bold, with a size of 16 points using pdf.SetFont(“Arial”, “B”, 16). 
  5. We add a cell (a rectangular area) to the page with pdf.Cell(40, 10, “Hello, World!").This cell contains the text “Hello, World!". 
  6. Finally, we save the PDF to a file with pdf.OutputFileAndClose(“hello.pdf”). If there’s an error, we panic. 

If you run this code, you’ll get a PDF named hello.pdf with the text “Hello, World!”.

5. Adding Images and Fonts to Your PDF 

So far, our PDF is quite plain. Let’s enrich it by adding an image and using a custom font. First, let’s see how to add an image: 

pdf.ImageOptions("image.jpg", 10, 10, 30, 0, false, gofpdf.ImageOptions{ImageType: "JPG", ReadDpi: true}, 0, ""

This line of code adds an image located at image.jpg to the PDF. The arguments specify the file path, the x and y coordinates (10, 10), the width (30), and the height (0, which means it’s automatically computed to maintain the aspect ratio). We also specify some image options, including the image type (JPG) and the DPI setting (ReadDpi: true). 

Now, let’s use a custom font: 

pdf.AddFont("Roboto", "", "Roboto-Regular.json") pdf.SetFont("Roboto", "", 14

Here, we first add the Roboto font using a JSON file that contains the necessary font metrics (you can generate this file using utilities provided by the gofpdf package). We then set the font for subsequent text. 

6. Advanced Techniques for PDF Creation with Gofpdf 

With the basics covered, let’s move on to some advanced techniques for creating more complex PDFs. 

Creating Tables 

Tables are often used in PDFs to present data in a structured manner. Here’s how you can create a simple table with gofpdf: 

// Table headers
headers := []string{"Country", "Capital", "Population"} 

// Table data 
data := [][]string{ 	
    []string{"China", "Beijing", "1,403M"}, 	
    []string{"India", "New Delhi", "1,366M"}, 	
    []string{"United States", "Washington, D.C.", "331M"}, 
} 

pdf.SetFont("Arial", "B", 12) 

// Print table headers for 
_, i := range headers { 	
    pdf.CellFormat(40, 7, headers[i], "1", 0, "", false, 0, "") 
} 

pdf.Ln(-1) 

// Print table data 
pdf.SetFont("Arial", "", 12) 
for _, line := range data { 	
    for _, cell := range line { 		
        pdf.CellFormat(40, 7, cell, "1", 0, "", false, 0, "") 	
    } 	
    pdf.Ln(-1) 
}

In this code, we first set the font to Arial bold with a size of 12 points. We then print the table headers by creating a cell for each header. We use the pdf.Ln(-1) function to move to the next line. 

We do the same for the table data, but we use the normal Arial font. Each line of data is printed on a new line. 

Multi-Page PDFs 

Creating multi-page PDFs is as simple as calling pdf.AddPage() multiple times. Here`s an example:

pdf.AddPage() pdf.SetFont("Arial", "B", 16) pdf.Cell(40, 10, "Page 1") 
pdf.AddPage() pdf.Cell(40, 10, "Page 2")

In this example, we’ve added two pages to the PDF and add a cell with the text “Page 1” to the first page and “Page 2” to the second page. 

7. Introduction to UniPDF for Advanced PDF Generation 

While we’ve dedicated the majority of this guide to introducing gofpdf for beginners, it’s important to mention that when you’re ready to take on more advanced tasks with your PDFs, the UniPDF library by UniDoc could be your next move. This powerful library provides a variety of additional features and capabilities, including but not limited to, PDF splitting, merging, text extraction, and even PDF to image conversion. This makes it an excellent tool for tasks requiring more complex operations beyond basic PDF generation. You can find out more about UniPDF’s capabilities in their Ultimate Guide to PDF reports

8. Conclusion 

Congratulations! You’ve made it to the end of this guide. You now know how to create PDFs in Golang using the gofpdf package, including how to add text, images, and tables, and how to create multipage PDFs. 

You have also been introduced to the UniPDF library for when your needs surpass basic PDF generation. While we’ve covered a lot, there’s still much more you can do with both gofpdf and UniPDF. We encourage you to explore both the gofpdf and UniPDF documentation to learn more about their capabilities. Remember, practice is key when learning a new skill, so try creating different types of PDFs to get a feel for it.