Feature

CraftMyPDF API

Marketplace Product

PDF remains a ubiquitous format for offline data. Both mobile and web applications often have the need to create PDF documents for various user workflows. The CraftMyPDF plugin available in Backendless Marketplace provides integration with the CraftMyPDF.com service.

This integration enables generation of PDF documents based on the data of your application. Using the API provided by the plugin, your application can generate a PDF from the frontend app or in the backend logic. The frontend app can be created with UI Builder, native code. or with any other no-code UI solution.

CraftMyPDF Automated PDF Generation Plugin

Installation Instructions

1. Login to Backendless Console and select your app. Open the Marketplace screen, select the API Services section and install the “CraftMyPDF” plugin from the Backendless Marketplace.

2. When you install the plugin, you will be asked to configure the service. The configuration requires entering a PDF storage folder – it is a folder in the Backendless Cloud where all generated PDF documents will be stored, and the CraftMyPDF API Key which is used to generate PDFs:

CraftMyPDF API service key configuration

Configuration of the PDF service takes a few minutes and it is a straightforward process:

  • In a separate browser window (or tab), register on the CraftMyPDF website.
  • Click the API Integration button located in the main toolbar.
    CraftMyPDF API Integration
  • In the API Integration section copy the API Key to clipboard.
    CraftMyPDF API Key
  • Return to the Service Configuration pop-up window and paste CraftMyPDF API Key.
    • In the PDF Storage Folder field, enter the name of a directory from the application’s file storage where the generated PDF documents will be stored.

3. To verify the installation, click the Cloud Code icon in Backendless Console and check if the “CraftMyPDF” plugin appeared in the list of services.

CraftMyPDF Plugin added installed in Backendless

4. If you plan to use the PDF generation service from a native application, select a programming language of your choice to download the client SDK generated specifically for the CraftMyPDF service.

Download CraftMyPDF API Service SDK in Backendless

5. In case a language you would like to use does not show up in the list, you can still use the plugin using its REST API.

PDF Templates

This plugin relies on the preconfigured templates to generate PDF documents. A template is a combination of text fields, images, logos, QR codes, charts and other elements put in a specific order or location – these elements are called components.

Almost every component expects some data which is sent via an API call. When you make an API call, you send data to these components to generate a PDF document. Find a more detailed description of how to send data to components in the Data Fields section.

Template Editor

All templates must be edited in the CraftMyPDF editor. To open the Editor, click the Manage Templates button in the toolbar.

CraftMyPDF Manage Templates

Every template has a unique identifier, and these identifiers are stored within the Template ID column. When you work with the service, you will have to use them, because the API must know which template you want to use to generate a PDF. 

Open a template by clicking the Edit button.

Select CraftMyPDF Template to edit

Once in the Editor, add the desired components to create your template.

The CraftMyPDF service provides a variety of components that can be used to build advanced PDF templates. To learn more, it is recommended to read the components documentation.

Data Fields

To receive data, components have special data fields, which act as substitution variables. These data fields are used for data injection when an API is invoked. 

In the screenshot below, you can see the notation for various data fields in curly braces:

  • {{data.client_address}}
  • {{row.description}}
  • {{data.due_date}}

CraftMyPDF Template data fields

Data fields are divided into two categories:

  1. Basic data fields. Used to display single, non-repeating data elements. The field format for these data fields is {{data.client_address}}.
  2. Table data fields. Used to display tabular data. Data fields can be grouped in rows. The resulting PDF repeats the row structure to create a table. The format for this field type is {{row.description}}. 

The difference between these two types is in their prefixes. Basic data fields use the data. prefix, but table data fields use the row. prefix.

Fields containing such expressions as {{format(sum(“total”,data.items), “number”, “0,0.00”)}} represent formulas that calculate data passed to the template. For instance, you can link multiple data fields to calculate the sum, or perform other mathematical operations. To learn more about CraftMyPDF expressions, navigate to the Editor and click the Docs: Expressions button.

Open CraftMyPDF Expressions to edit data fields

To generate a PDF document, a JSON object must be sent to the API service. The JSON object contains data that is used to populate the data/table fields. The service generates a PDF document based on the specified template.

In the sections below you will learn how to send data to table/data fields and the corresponding JSON objects.

Sending Data to Basic Data Fields

Consider the template below:

CraftMyPDF template data fields example

When a template field is identified in the JSON object, the data prefix must not be included. For example, instead of using the data.address field name, you must use description.

Below is a sample JSON object used to populate the data fields shown above:

{   
   "templateId": "a0877b2b1c67703a",
   "data": {
      "first_name": "John",
      "last_name": "Smith",
      "address": "13th Street. 47 W 13th St, New York, NY 10011"
    },
   "outputFile": "craft_my_pdf_invoice_table.pdf"
}

Once the server receives the JSON object, all fields within the template get rendered and the PDF document is generated:

CraftMyPDF template data displayed

The PDF document is saved as craft_my_pdf_invoice_table.pdf, since this name was passed to the outputFile parameter in the JSON object.

Table Fields

One of the most frequently used components is a data table. The CraftMyPDF service relies on the Sections component to build custom tables based on the structured JSON data passed to the template. Below is a Section component containing three table fields:

CraftMyPDF Sections component for custom tables

This table automatically populates rows depending on the number of data items sent via the API call. 

To create a table, you must first add the Normal Section component to your template. The template is divided into three default areas:

  • Header
  • Body
  • Footer

1. You cannot remove either the Header or the Footer. The Normal section must be added to the Body of the template. To do so, in the Editor, select the Header section, then click the Insert button to add a Normal section below.

Insert Normal section in CraftMyPDF editor

2. This section is used as the Table header, and it must have a few column names. You need to add a few text components to the newly added Normal section and edit them to create the Table header as demonstrated below:

Create table header in CraftMyPDF template

3. Add another Normal section below where table fields will be created. To do that, repeat the process as described in the Step 1, then add the desired number of text components to the new section:

Create table fields in CraftMyPDF

4. The CraftMyPDF service requires sending data to all table fields within one JSON object.  The JSON object must be composed at this point since it will be used in the next step to map PDF template fields to the properties in the JSON. All template fields that belong to a single table must be grouped in a single JSON property. The JSON property must be of the JSON Array type. 

In the example below, the JSON array is called “items”. The name of the property can be whatever you want, it is not critical.

Notice the “items” property contains an array of a single object that contains “description”, “quantity” and “price”. These properties will be used for two purposes:

  1. Create a mapping in the CraftMyPDF editor between JSON and template fields.
  2. Contain values for the actual data when the same JSON is used in the API.

The names of the properties must not contain the “row.” prefix.

{
   "templateId": "a0877b2b1c67703a",
   "data": {
      "items": [
         {
            "description": "Magic T-Shirt, L",
            "quantity": 1,
            "price": 50
         }
      ]
   },
   "outputFile": "craft_my_pdf_invoice_table.pdf"
}

In the next step, you will be creating a mapping between the template’s table fields and the properties from the JSON. To do this, you will need to use the contents of the “data” property:

{   
   "items": [
      {
         "description": "Magic T-Shirt, L",
         "quantity": 1,
         "price": 50
      }
   ]
}

5. It is necessary to bind the table fields to the expected data that will be received from the API invocation. Click the Data button in the Editor, and copy and paste the JSON object shown above into the editor:

Add JSON data to bind table fields to expected data in CraftMyPDF

6. Select the Normal section containing table fields, and assign a name to it:

Assign name to table fields section

7. In the General menu, scroll down to the Data Binding section, check the Enabled box and click the Insert Data Expression button to bind this section to a JSON object structure: 

Enable data binding with Insert Data Expression in CraftMyPDF

8. Select the “items” element in the Expression Builder menu to bind the Normal section to the JSON object, and click the Use This button to confirm your selection.

Bind Normal section to JSON object

9. Now you need to bind every table field to the corresponding field name in the JSON object. Select a table field, and in the General menu, find the Text section, then click the Insert Data Expression button:

Bind every table field to JSON field name

10. Match the name of a table field to a property in the JSON object. Select the property in the list and confirm your selection by clicking the Use This button.

Match names of table fields to JSON

11. Repeat the same process for all other table fields as described in Step 10 to have all table fields bound:

Bind all table fields

Sending Data to Table Fields

Now the sample template is ready to receive data from the API to build a data table. To build a table with multiple rows, you have to add a few more objects to the “items” array:

{   
   "templateId": "a0877b2b1c67703a",
   "data": {
      "items": [
         {
            "description": "Magic T-Shirt, L",
            "quantity": 1,
            "price": 50
         },
         {
            "description": "Military Boots - Brown - US 11",
            "quantity": 1,
            "price": 100
         }
      ]
   },
   "outputFile": "craft_my_pdf_invoice_table.pdf"
}

To generate a PDF document, send a JSON object to the API service. The JSON object must contain the template ID in the "templateId" property and the template fields data in the "data" property. The result of the API service invocation is a generated PDF document containing a table with 2 rows:

Result of text PDF document from CraftMyPDF

The PDF document is saved as the craft_my_pdf_invoice_table.pdf, since this name was passed to the outputFile parameter in the JSON object.

Sourcing Data From Backendless Database

Instead of sending actual data values in the JSON document, the Backendless plugin supports an alternative way of obtaining data. You can configure a query in the JSON object which will fetch data from your Backendless Database and send the data to the CraftMyPDF service.

For demonstration purposes, consider the following data table schema:

Demonstration data table schema in Backendless Database

Suppose the name of the data table is “invoices”. To source data from the data table, the following JSON object can be used:

{
   "templateId": "a0877b2b1c67703a",
   "data": {
      "items": {
         "tableName": "invoices",
         "where": "objectId in ('30D662C7-A945-477E-9142-746C2747E3E7', '8EE19152-AC6F-4405-BE28-7EA65F854B9A')",
         "properties" : ["objectId", "ownerId"],
         "excludeProps" : ["created"]
      }
   },
   "outputFile": "craft_my_pdf_invoice_table.pdf"
}

The tableName is a mandatory parameter used to reference the data table in Backendless Database.

The where parameter sets a query to select objects/records from the table that match the specified condition. When using this approach, the names of the columns in the referenced table must match the names of the template fields configured in the CraftMyPDF editor.

The excludeProps parameter shown above instructs the server not to return the specified properties.

The properties parameter tells the server that only the specified properties should be returned.

In addition to the where property,  you can also use other properties to configure your database query. Below is a list of all supported query properties:

   * @property {String} tableName
   * @property {boolean} findFirst // if true, returns {first object from db}; false, returns an array of selected db records
   * @property {String} [where]
   * @property {string[]} [properties]
   * @property {string[]} [excludeProps]
   * @property {string[]} [sortBy]
   * @property {boolean} [distinct]
   * @property {number} [pageSize]
   * @property {number} [offset]
   * @property {string} [having]
   * @property {string[]} [groupBy]
   * @property {string[]} [relations]
   * @property {number} [relationsDepth]

CraftMyPDF API

generateDocument

Generates a PDF document from a template. 

options – is a mandatory parameter consisting of 5 parts:

  • templateId – A string value. Unique identifier of the requested template stored within the CraftMyPDF service. This parameter is always required to invoke the method.
  • data – A string value in the JSON format. Is the mandatory parameter that accepts data to generate a document.
  • outputFile – A string value. Is the optional parameter used to name an output document.
  • isCmyk– A boolean value. This parameter identifies the CMYK color profile which is used in color printing. This profile improves the quality of colors on the printed paper. Defaults to false.
  • imageResampleRes – An integer value. Is an optional parameter that allows reducing resolution of all images within the requested PDF. This optimization helps to reduce the file size. Suggested values are 1200, 600, 300, 150 or 72.

REST Example:

In this example, a document named invoice_client_2 is generated using the template 70977b2b1cbdb942

Returns a URL to the document.

curl -X "POST" "https://xxxxx.backendless.app/api/services/CraftMyPdf/generate" \
   -H 'Content-Type: application/json' \
   -H 'Accept: application/json' \
   -d $'{
      "templateId": "a0877b2b1c67703a",
      "data": {
         "first_name": "John",
         "last_name": "Smith",
         "address": "13th Street. 47 W 13th St, New York, NY 10011",
         "items": [
            {
               "description": "Magic T-Shirt, L",
               "quantity": 1,
               "price": 50
            },
            {
               "description": "Military Boots - Brown - US 11",
               "quantity": 1,
               "price": 100
             }
         ]
      },
      "outputFile": "invoice_client_2",
      "isCmyk": false,
      "imageResampleRes": 0
   }'

Codeless Example:

CraftMyPDF Codeless Logic Example