How to hide an image conditionally

Introduction

When using dynamic picture, Carbone will print a white placeholder with crosses in case of errors:
The image value is empty (empty string or attribute missing from the JSON dataset)
The image URL or Data-URL format is not correct
The image can't be downloaded from the provided URL

If image value is empty, 2 solutions are available to avoid the image with crosses:
Hide the image
Insert an alternative image

Solution 1: Hide the image if is empty

Conditional blocks are a good solution to hide elements inside a document, in our case we want to hide the image if the value is empty or does not exist. The following Statement checks if the image is empty, if true, the dynamic picture will be removed from the document:

{d.image:ifEM:hideBegin}
// IMAGE JUST HERE
{d.image:hideEnd}


As an example, an ODT template is created, and a temporary picture is inserted (1200x600 grey picture) with the alternative text {d.picture:imageFit(contain)} .
The temporary picture will be used by Carbone to insert the image coming from your JSON data-set. Conditional blocks are wrapping the image to hide it if the image value is empty. The {d.image:ifEM:hideBegin} should be place before the image, and the {d.image:hideEnd} after the image. Make sure the image as anchor set to As character or In line with text. Finally the imageFit(contain) expression will scale the image to fit within the temporary image container.

ODT Template including a dynamic picture and wrapped by a condition

The following JSON data-set is used to generate the document:
{
"image": ""
}

As the image is an empty string, the image is removed and the generated document prints nothing.

Generated PDF document

Solution 2: insert an alternative image if it is empty

As an example, an ODT template is created, and a temporary picture is inserted (1200x600 grey picture) with the alternative text {d.image:ifEmpty(.imageError, true):imageFit(contain)}. The temporary picture will be used by Carbone to insert the image coming from your JSON data-set. If the image is empty, the imageError will be injected inside the document (imageError is a transparent image of 1 pixel). Finally the imageFit(contain) will scale the imageError to fit within the temporary image container.

ODT Template including a dynamic picture

The following JSON data-set is used to generate the document:
{
"image": "",
"imageError": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="
}

As the image value is an empty string, the imageError is injected inside the generated PDF:

Generated PDF document

The second solution is only working with the ifEmpty(.imageAttributeName, true) conditionnal formatter and with the last argument set to true, it is not working with ifEM, nor ifEQ, ifGT, etc...
Was this article helpful?
Cancel
Thank you!