Dynamic barcodes

pdfChip includes a barcode library that allows creating high-quality barcodes by inserting special HTML objects into the DOM. Those can be static, but they can also be dynamically created. Often, the easiest solution is to have a 'template' barcode object in the HTML, and then modifying its parameters using JavaScript.

The HTML would look like this:

<object id="barcodeObject" class="qrcode" type="application/barcode" 
        style="width:15mm; height:15mm;">                    

	<param name="type" value="QR-Code">                    
	<param id="barcodeValue" name="data" value="Sample Data">                    
</object>
Click to copy

This HTML instructs pdfChip to create a QR code, with the data that is encoded set to "Sample Data". The following JavaScript then modifies the data for the QR code.

document.getElementById('barcodeValue').value = "Penguins are great!";
Click to copy

The function 'getElementById' finds the correct object in the HTML DOM. Then, its value is modified to the value we really want to have in the generated PDF. There is, however, a problem with that.

Modifying parameters of objects

The problem is that WebKit doesn't realize something changed to the DOM, when you use the above JavaScript code. So in your final PDF, you'll end up with the default value ('Sample data'), rather than what you set in JavaScript.

To fix that, you need to jolt WebKit a bit so it understands something changed and uses the new parameters. You can do this quite simply with the following line of JavaScript:

document.getElementById('barcodeObject').innerHTML = document.getElementById('barcodeObject').innerHTML;
Click to copy

This code looks weird, because it sets the HTML content of the 'barcodeObject' object, to the same thing! But that's intentional; this is sufficient to make WebKit realize something changed to the DOM and for it to pick up the new values you set up using JavaScript.

Multiple barcode parameter changes

If you want to modify a barcode multiple times (for example in a loop) and then call 'printPages' to output more pages to the output PDF, you have to use this trick each time. The sequence should be:

  • Modify barcode parameters.
  • Assign innerHTML trick to jolt WebKit into action.
  • Use 'printPages' to output additional page(s).