Airplane Ticket

This guide will show how to create a sample airplane ticket using creator templates.

Before you begin

First things first, you should get your API key from your UniCloud account.

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

Clone the project repository

In your terminal, clone the 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 templates/airplane-ticket folder in the unipdf-examples directory.

cd unipdf-examples/templates/airplane-ticket

How it works

The import section in lines 10-26 imports UniPDF packages and other necessary libraries.

The init function defined in lines 28-37 adds a license key to authenticate library request.

The main function in lines 39-104 creates the file by using readTemplate, readTicket, and c.DrawTemplate functions. In lines 40-41 a creator object and sets the margins. The template file is read using readTemplate("templates/main.tpl") and is stored as io.Reader. The json data is read using readTicket("ticket.json") stored as Ticket object. This Ticket object is defined in lines 124-154.

In line 56 a qr code is created using createQRCode("https://github.com/unidoc/unipdf-examples/tree/master/templates/airplane-ticket", 500, 500) and is stored as model.Image. Here the url is the data to be converted into qr code and the last two parameters set width and height of the image respectively.

Template options and resource are defined using creator.TemplateOptions object in lines 62-89. These resources are map objects and utility functions which are to be used inside the template. For example the formatTime function is used in the template file in lines 69-70 as follows.

{{template "table-cell-paragraph" (extendDict $props "Text" (formatTime $route.Departure "02 Jan"))}}
{{template "table-cell-paragraph" (extendDict $props "Text" (formatTime $route.Arrival "02 Jan"))}}

The data used in the template is defined in lines 91-94. Then in line 96 the file is drawn using c.DrawTemplate(mainTpl, data, tplOpts). Here the data and templateOptions objects are passed as templates. Finally the file is written to file using c.WriteToFile("unipdf-airplain-ticket.pdf") in line 101.

The function readTemplate defined in lines 108-121 reads the template file and returns io.Reader. The function readTicket in lines 57-170 reads the json file containing the necessary ticket data and decodes it to Ticket object using json.NewDecoder(file).Decode(ticket). The decoded Ticket object is return from this function.

In lines 174-191 the createQRCode is defined to create a QR code image from the string data provided in the parameter.

Run the code

Use the following command to run the code.

go run pdf_airplane_ticket.go

Sample Output

Airplane Ticket

Got any Questions?

We're here to help you.