Skip to main content

Using CloudAPI with WordPress

· 8 min read
James A Brannan

A client asked if The DynamicPDF API worked with WordPress. This question made us wonder how we could integrate The DynamicPDF API with WordPress so potential clients could use our product in their WordPress sites.

The following solution is what we came up with.

info

Before we begin, realize this is a way to use The DynamicPDF API within WordPress and is not necessarily the only way.

Before starting, our first concern was security. While creating the example, we wanted to avoid a webpage that somebody online could access repeatedly and run up our service usage. WordPress solves this problem by allowing a site to register its users and other security measures. However, we opted to only password-protect the page.

Our next concern was to preserve the site’s existing integrity. Although it is permissible to modify a WordPress site theme’s functions.php page, rather than risking corrupting a site in production, finding a plugin solution that allowed inserting PHP code into pages and posts seemed more prudent. We opted for the XYZ WP Insert Code Snippet plugin by XYZScripts.

info

If you are dead set against using plugins, realize you must modify your functions.php page to include the needed functionality. Your WordPress site will require modifications to allow the DLEX, JSON, and XML file extensions. See:

Adding PHP code snippets removes the dangers of adding custom code to your WordPress theme. A snippet is a small chunk of PHP code used to extend the functionality of any WordPress page or post - think of a snippet as a "mini-plugin." Using a snippet is a quick, easy, and safe way to extend your WordPress site’s functionality without requiring you to modify your existing theme.

info

Preliminary plans are in the works to create a DynamicPDF API WordPress Plugin, freeing you from the steps outlined here. If you want to see a WordPress Plugin for DynamicPDF API, let us know on our chat or via email at sales@dynamicpdf.com.

Before we could start coding, we needed to modify our WordPress Site by installing the plugins, creating some folders, and uploading the required files to our WordPress site's media library.

Installed Plugins

We installed two plugins, the File Upload Types, and the Insert PHP Code Snippet plugins. We used the File Upload Types plugin to allow uploading JSON, DLEX, and XML files to our WordPress Media Library. We used the Insert PHP Code Snippet plugin to insert PHP code into a page we created to call the pdf endpoint and then embed the returned PDF into that page.

danger

Carelessness with your WordPress site could bring it down. Moreover, embedding a link to generate a PDF dynamically could lead to a denial of service attack and incur significant DynamicPDF API usage costs.

  • We installed the File Upload Types plugin and the Insert PHP Code Snippet plugin.

Created File Types

  • We allowed the XML and JSON file types and created a new rule allowing the DLEX file type.

Created Folders and Files

Rather than stream the PDF from the pdf endpoint to the user's browser directly, it seemed easier to save the produced PDF to a temporary file, use an iframe to embed the saved PDF file and display it in the user's browser, and then periodically delete the temporary file. Therefore, we created a folder in our WordPress media folder to store the temporary PDFs. We also created a folder to contain the instructions.json file and the JSON data (report-with-cover-page.json).

  • We created two folders, pdf-data and pdf-output, in our wp-content folder

  • We placed Instructions.json and report-with-cover-page.json in the pdf-data folder.

info

Recall we had to install and configure our WordPress site to allow uploading JSON and XML files to our media folder.

PHP API Call

We next created the PHP code snippet to embed it in a page. To accomplish this, we created a snippet named pdf-dlex-example, added the PHP code, and tested it.

caution

Full disclosure. In reality, we wrote and edited the code in Visual Studio Code running standalone first. The end of this post lists the complete code listing. Attempting to create and debug the code directly via the code snippet would have been time-consuming.

  • We created a new PHP code snippet named pdf-dlex-example.

  • We then added the PHP code.

The PHP code performs the following tasks:

  • constructs the complete path to the instructions.json and the report-with-cover-page.json files,
  • constructs the complete path and file name to save the temporary PDF,
  • it ensures the save path exists, and if it doesn't create the path,
  • constructs the cURL POST request to the pdf endpoint,
  • calls the pdf endpoint,
  • saves the PDF as a temporary file,
  • echoes an iframe containing the path to the temporary PDF,
  • closes the cURL connection,
  • and then deletes any temporary file older than two minutes.
<?php

// get the path to instructions.json file and the
// json data.
$uploads = wp_upload_dir();
$instructions_path = $uploads['basedir'] . '/2023/12/pdf-data/instructions.json';
$json_path = $uploads['basedir'] . '/2023/12/pdf-data/report-with-cover-page.json';

//get the path to the output folder
$save_dir = '/pdf-output/';
$save_path = $uploads['basedir'] . '/2023/12/pdf-output/';

// create the file name that is unique
$output_file = strtotime("now") . '-pdf-output.pdf';
$output_path = $save_path . $output_file;
$output_url = $uploads['url'] . "/pdf-output/" . $output_file;

//if there is no save path, create it
if (!file_exists($save_path)) {
mkdir($save_path, 0777, true);
}

$ch = curl_init();

//initialize curl with dynamicpdf cloud api endpoint
//set it to post and that it returns content rather
//than success/failure

curl_setopt($ch, CURLOPT_URL, 'https://api.dynamicpdf.com/v1.0/pdf');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POST, 1);

//set dynamicpdf api key in header

curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer DP---api-key---',
]);

//specify the instructions json and the json
//layout data as files note the first param
//of CURLFile is the path to the file, and the
//last param is the form post file name

curl_setopt($ch, CURLOPT_POSTFIELDS, [
'Instructions' => new CURLFile($instructions_path, "application/json" ,"instructions.json"),
'Resource' => new CURLFile($json_path, "application/json", "report-with-cover-page.json"),
]);

//call the pdf endpoint

$response = curl_exec($ch);

//if there is an error print it out,
//otherwise save the response as a file

if ($response === false) {
echo curl_error($ch);
} else
{
file_put_contents($output_path, $response);

}

// be certain to close curl connection

curl_close($ch);

//echo the iframe to embed in a wordpress page/post
//specifying the just created pdf as the content

echo "<iframe src='" . $output_url . "' width='1000' height='1000'></iframe>";

//perform housekeeping by deleting any pdf older than
//two minutes old

$files = array();
foreach (scandir($save_path) as $file) {
if ($file !== '..' && $file !== '.') {
if( filemtime($save_path . $file) <= strtotime("-120 seconds")) {
unlink($save_path . $file);
}
}
}
?>

Testing the PHP Snippet

We then tested the PHP snippet directly via the preview link.

  • We tested the newly created snippet by clicking on the preview link.

After successfully debugging the code, the page displayed the PDF embedded in an iframe.

Creating a Page

We next created a page to embed the snippet and password-protected the page to ensure only authorized users could access the page.

danger

You would want better security in a production environment than a simple password-protected page (see WordPress Security).

  • We created a new page and password-protected the page.

  • We copied the short-code to embed in the newly created page.

  • We embedded the short-code in the page.

  • We saved the page, logged out of WordPress, and navigated to the newly created page.
  • We entered the password,

  • and the page with the dynamically created PDF appeared embedded in the page.

Conclusion

Embedding one of the DynamicPDF API endpoints is straightforward. The DynamicPDF API can easily be integrated into your WordPress site with a small amount of PHP coding.

GitHub Examples

To make it easier to use DynamicPDF API with WordPress, we provide the wordpress-dpdf-base.php file on GitHub, which contains the class, DynamicPdfWordPressBase. Install that PHP file to a folder accessible by WordPress when creating code snippets.

caution

Embedding class definitions and functions does not appear to be supported by XYZ Code Snippet plugin. Instead, upload the wordpress-dpdf_base.php file to a location accessible by PHP. Then use include_once('wordpress-dpdf-base.php'); when referring to the class. See the GitHub files for examples.

Then use the code snippets within your WordPress site. We also provide the files:

to help you get started creating snippets using the DynamicPdfWordPressBase class to create PHP code snippets.

PHP Test Code in Visual Studio

<?php

$instructions_path = "c:/temp/dlex/instructions.json";
$json_path = "c:/temp/dlex/report-with-cover-page.json";
$save_path = "c:/temp/dlex/php-dlex-output.pdf";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.dynamicpdf.com/v1.0/pdf');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer DP.---api-key---',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'Instructions' => new CURLFile($instructions_path, "application/json" ,"instructions.json"),
'Resource' => new CURLFile($json_path, "application/json", "report-with-cover-page.json"),
]);

$response = curl_exec($ch);

if ($response === false) {
echo curl_error($ch);
} else
{
file_put_contents($save_path, $response);
}
curl_close($ch);

?>