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

Imran Habib

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 two powerful options for generating PDFs using Golang. UniPDF library by UniDoc for more advanced reporting needs and gofpdf library as a starting point for beginners. 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. UniPDF Library introduction
  4. Create your first PDF Report
  5. Gofpdf library installing
  6. Creating PDF in Golang with Gofpdf
  7. Adding Images and Fonts to Your PDF
  8. Advanced Techniques for PDF Creation
  9. 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. UniPDF library introduction

UniPDF is a Golang PDF library to create, edit and annotate PDF documents in your application. This powerful library provides a variety of features and capabilities, including but not limited to, PDF splitting, merging, text extraction, and even PDF to image conversion you can read more about features here. This makes it an excellent tool for tasks requiring PDF generation and more complex operations beyond it.

Allow me to guide you through the process of getting started with this excellent library. I will demonstrate how to create your first PDF document using a template with UniPDF in just a few minutes.

To get started with UniPDF, you’ll need to sign up for a UniCloud account to grab your API key. Just head over to UniCloud, create your account, and don’t forget to check your inbox for the activation email from UniDoc. Once your account is activated, you’ll get 100 free credits to test things out.

4. Create your first PDF Report

Initialize a Go module/project.

go mod init unipdf-getting-started 

UniPDF SDK is hosted on this Github repository. To install the Go SDK and its dependencies, run this command.

go get github.com/unidoc/unipdf/v3 

Next step will be loading the API key which we generated in UniCloud

Linux/Mac

export UNIDOC_LICENSE_KEY=PUT_YOUR_API_KEY_HERE 

Windows

set UNIDOC_LICENSE_KEY=PUT_YOUR_API_KEY_HERE 

After setting the environment variables, UniPDF will automatically load the license key for subsequent API requests.

Import the SDK

Go ahead and create a file named pdf_report.go.

Import the necessary packages from the SDK into your project.

package main import ( "github.com/unidoc/unipdf/v3/common/license" "github.com/unidoc/unipdf/v3/creator" ) 

The license package is included in every call to the SDK to authenticate your request with a valid license key.

Import other dependencies

Our program will depend on their packages like os to read the environment variables, log to output a message to the terminal, usually error messages and time to include the time and date the document is created.

The updated import block will look like this:

package main import ( "log" "os" "time" "github.com/unidoc/unipdf/v3/common/license" "github.com/unidoc/unipdf/v3/creator" "github.com/unidoc/unipdf/v3/model" ) 

Run the sample code

Add the following lines of code to the unipdf-getting-started file after the import block.

func init() < // Make sure to load your metered License API key prior to using the library. // If you need a key, you can sign up and create a free one at  err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`)) if err != nil < panic(err) > > func main() < c := creator.New() c.SetPageMargins(50, 50, 100, 70) helvetica, _ := model.NewStandard14Font("Helvetica") helveticaBold, _ := model.NewStandard14Font("Helvetica-Bold") p := c.NewParagraph("UniPDF") p.SetFont(helvetica) p.SetFontSize(48) p.SetMargins(15, 0, 150, 0) p.SetColor(creator.ColorRGBFrom8bit(56, 68, 77)) c.Draw(p) p = c.NewParagraph("Example Page") p.SetFont(helveticaBold) p.SetFontSize(30) p.SetMargins(15, 0, 0, 0) p.SetColor(creator.ColorRGBFrom8bit(45, 148, 215)) c.Draw(p) t := time.Now().UTC() dateStr := t.Format("1 Jan, 2006 15:04") p = c.NewParagraph(dateStr) p.SetFont(helveticaBold) p.SetFontSize(12) p.SetMargins(15, 0, 5, 60) p.SetColor(creator.ColorRGBFrom8bit(56, 68, 77)) c.Draw(p) loremTxt := "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" + "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut " + "aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore" + "eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt " + "mollit anim id est laborum." p = c.NewParagraph(loremTxt) p.SetFontSize(16) p.SetColor(creator.ColorBlack) p.SetLineHeight(1.5) p.SetMargins(0, 0, 5, 0) p.SetTextAlignment(creator.TextAlignmentJustify) c.Draw(p) err := c.WriteToFile("hello_world.pdf") if err != nil < log.Println("Write file error:", err) > > 

In this code, function init loads your license API Key from the environment variable you set earlier. The main function creates a page with three paragraphs styled as indicated in the code and saves it to a file named getting_started.pdf.

Note:

You are likely to see red lines underneath the code because some packages are yet to be installed.

To fix this, run go mod tidy to install the missing dependencies.

Save and run the file.

go run pdf_report.go 

The created PDF will be added to your project directory.

5. Gofpdf library installing

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 

6. Creating PDF in Golang with Gofpdf

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!”.

7. 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.ImageOptionsImageType: "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.

8. 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.

9. Conclusion

Congratulations! You’ve reached the end of this guide, and now you know how to create PDFs in Golang using both UniPDF and gofpdf. You’ve learned how to add text, images, and tables, and even how to create multipage PDFs.

While free libraries might cover the basics, UniPDF offers a wide range of features—from advanced PDF generation and editing to secure document handling with encryption and redaction. We encourage you to explore the UniPDF documentation to discover all it can do.

Remember, practice makes perfect. So keep experimenting with different types of PDFs to really master these skills!