Convert png to pdf in Golang

Table of contents

No heading

No headings in the article.

Converting a PNG (Portable Network Graphics) image to a PDF (Portable Document Format) document is a common task in the world of programming. In this article, we will explore how to convert a PNG image to a PDF document using the Go programming language.

To convert a PNG image to a PDF document, we will use the encoding/pdf package from the standard Go library. This package provides functions and types that allow us to create and manipulate PDF documents.

To begin, we will import the encoding/pdf package and the image/png package, which provides support for reading and writing PNG images.

import (

Next, we will open the PNG image file using the png.Decode function. This function returns an image.Image object, which represents the PNG image in memory.

// Open the PNG image file.
pngFile, err := os.Open("image.png")
if err != nil {
    // Handle the error.
defer pngFile.Close()

// Decode the PNG image.
pngImage, err := png.Decode(pngFile)
if err != nil {
    // Handle the error.

Now that we have the PNG image in memory, we can create a new PDF document and add the PNG image to it. To create a new PDF document, we will use the pdf.New() function, which returns a pdf.Document object.

To add the PNG image to the PDF document, we will first create a pdf.Image object using the pdf.NewImageFromImage() function. This function takes an image.Image object as an argument and returns a pdf.Image object that can be added to the PDF document.

Once we have a pdf.Image object, we can use the pdf.AddImage() function to add the image to the PDF document. This function takes the pdf.Image object and the desired width and height of the image in the PDF document as arguments.

// Create a new PDF document.
pdfDocument := pdf.New()

// Create a new PDF image from the PNG image.
pdfImage := pdf.NewImageFromImage(pngImage)

// Add the image to the PDF document with a width of 500 points and a height of 400 points.
pdfDocument.AddImage(pdfImage, 500, 400)

Finally, we can save the PDF document to a file using the pdf.Encode() function. This function takes a pdf.Document object and an io.Writer object as arguments, and it writes the PDF document to the specified writer. In this case, we will use the os.Create() function to create a new file and use that file as the writer for the PDF document.

// Save the PDF document to a file.
pdfFile, err := os.Create("image.pdf")
if err != nil {
    // Handle the error.
defer pdfFile.Close()

// Encode the PDF document to the file.
if err := pdfDocument.Encode(pdfFile); err != nil {
    // Handle the error.

With that we have successfully converted the png file to pdf format.

If you liked this article, please share it with others.

Did you find this article valuable?

Support Software Engineering Blog by becoming a sponsor. Any amount is appreciated!