PNG to PDF Conversion in Golang

Posted on Fri 03 Feb 2023

Subscribe to Web Distro Newsletter
and never miss any latest articles.

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 (
    "image/png"
    "encoding/pdf"
)

 

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.
    return
}
defer pngFile.Close()

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

 

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.
    return
}
defer pdfFile.Close()

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

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

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

Check articles with similar categories