Making sure the DOM is ready
This page is valid only for pdfChip 2.6 and up, or pdfToolbox 16 and up.
As explained before, the main problem with dynamically altering the HTML DOM, is that not all resources may be available when you're telling pdfChip to create PDF content. This is mostly visible for content that the WebKit engine builds dynamically. For pdfChip, this includes loading images from either online, or on-site sources (from a URL, or from a file), and creating barcodes using the built-in barcode engine.
It's important to realize that this problem is a timing issue. As such, it may not always occur in a template. You could have a template with 2 barcodes, where one loads correctly while the other one doesn't load at all.
It's also important to realize that an image not appearing in the final PDF, for example, might not be caused by this issue at all. You may have an error in the image's 'scr' parameter, the placement of the image may be wrong... Dynamic resource loading is just one of the issues that may cause this.
If the WebKit engine not being ready is the issue, how do we fix that? Luckily this is quite easy. The code snippets below show the cchipPrintLoop
function before and after fixing the issue.
Fixing the print loop
Before
A typical print loop function may look like this:
function cchipPrintLoop() {
// Modify the src of an image dynamically
document.getElementById('myImage').src = './images/penguin.jpg';
// Asking pdfChip to print
cchip.printPages();
}
The code defines the 'cchipPrintLoop
' function that is called automatically by pdfChip. This function proceeds to:
- Get the image element by using its unique ID as set in the HTML,
- Change the '
src
' attribute to the path of the image we want to use, - Tell pdfChip we are ready and want to convert the DOM to PDF.
After
To fix the dynamic resource loading problem, modify the code to this:
async function cchipPrintLoop() {
// Modify the src of an image dynamically
document.getElementById('myImage').src = './images/penguin.jpg';
// Asking pdfChip to print
await cchip.printReadyPromise();
cchip.printPages();
}
Two changes have been done in this code, and they are both necessary:
- The '
printReadyPromise
' function is called, after the DOM was modified and before pdfChip is instructed to create PDF. - Because this function is called using the '
await
' keyword in front of it, there needs to be an 'async
' keyword before the function definition for the print loop function.
The async / await paradigm in JavaScript is one possible way to deal with asynchronous JavaScript code and essentially convert it to synchronous code. If you don't understand what this means or how it is used here, just copy the syntax as stated above.
When dealing with more complex HTML templates, it is a good idea to ensure you understand the principles of asynchronous JavaScript code, and the importance of the async / await paradigm.