PDF to Image Custom Encoding

In this guide rendering pdf document to image using custom encoding will be shown.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.

Project setup

Clone the project repository

In your terminal, clone examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unipdf-examples.git

Navigate to the render folder in the unipdf-examples directory.

cd unipdf-examples/render

Configure environment variables

Replace the UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.





How it works

The import section imports unipdf packages and other necessary libraries.

The init function in lines 26-33 loads your metred API key and authenticates your request with UNIDOC_LICENSE_API_KEY.

The main function in lines 35-92 reads the pdf files in the given directory and renders each page of each pdf file to image using the custom JPX encoder given in lib_jpeg2k_encoder.go.

lines 36-39 validates the minimum number of environment variables. Line 40 gets the output directory using os.Args[1]. lines 42-44 checks if the output directory exists and it creates a new directory if it doesn’t exist. The loop in lines 46-91 iterates through all the files given in the environment variable and runs render operation on each file.

The custom encoder is registered in lines 64-65 using

customJpxEncoder := jpeg2k.NewCustomJPXEncoder()
core.RegisterCustomStreamEncoder(core.StreamEncodingFilterNameJPX, customJpxEncoder)

In line 56 an image device is instantiated using render.NewImageDevice(). The inner loop in lines 57-77 iterates through each page and converts it to an image.

Run the code

Run the code using the following code, where OUTPUT_DIR directory is the directory to save the output to and INPUT.pdf... represents a list of pdf files to be rendered to an image using the custom encoding.

go run pdf_image_render_custom_encoder_cgo.go OUTPUT_DIR INPUT.pdf...

After running the code all images generated by the code will be available in the OUTPUT_DIR provided.

Got any Questions?

We're here to help you.