Images Tutorial
In this tutorial you'll learn how to add images (both from files
or generated ones) to your reports.
There are two ways to add images to a report: by
its path using
addLinkedImage (note that in case the file
is inside jars you must check if the ReportGenerator you use support
adding them with
supportImagesOfJarFilesOrURLs function), or
by direct sending the image data to the generator, using the function
addImage.
Let's add big centered image from its link. Note
that the image is only loaded a single time per report, even if it's
used multiple times at it (it's an easy optimization afterwards).
String imgLink = Thread.currentThread().getContextClassLoader().getResource(
"nerval.png").getPath();
reportGenerator.setTextAlignment(ReportTextAlignment.CENTER);
reportGenerator.addLinkedImage(imgLink, 661);
The advantage of
addImage is that if you
use it often on lots of reports, you can load it just a single time
per application instance. The other big advantage is that you can
dynamically generate your report images and directly add them to the
report without the need to save them to a file. For example, if you
use generated charts at your reports (by a third party library), you
can add them easily that way.
Let's, for example, generate a QRCode (using the
library
QRGen) and add it to our report:
byte[] qrImage = QRCode.from("Nerval Reports")
.withSize(200, 200)
.to(ImageType.PNG).stream().toByteArray();
reportGenerator.addImage(qrImage, "NervalQR", 200);
reportGenerator.beginGroup(ReportGroupType.PARAGRAPH);
reportGenerator.addText("Nerval Reports generated QRCode");
reportGenerator.endGroup();
You can normally use images in your headers and
footers. The only thing to note here is to avoid using groups (as the
alignment is predefined by header/footer position). Also, if you
plan to use TeXReportGenerator, do not use direct added images in
headers or footers, as they aren't supported there. Let's see our
page header and footer generation function:
String nervalSmallLink = Thread.currentThread().getContextClassLoader()
.getResource("nerval_small.png").getPath();
reportGenerator.beginPageHeaderLeft();
reportGenerator.addLinkedImage(nervalSmallLink, 50);
reportGenerator.addSeparatorLine();
reportGenerator.endPageHeaderLeft();
reportGenerator.beginPageHeaderCenter();
reportGenerator.addText("Tutorial 6 - Images");
reportGenerator.endPageHeaderCenter();
reportGenerator.beginPageFooterCenter();
reportGenerator.addCurrentPageNumber();
reportGenerator.endPageFooterCenter();
reportGenerator.beginPageFooterRight();
reportGenerator.addSeparatorLine();
reportGenerator.addLinkedImage(nervalSmallLink, 50);
reportGenerator.endPageFooterRight();
That's it.
Here's the pdf generated by NervalReports' PDFReportGenerator:
And
here you can download the full code of this tutorial.