Skip to content Skip to sidebar Skip to footer

Image Not Displaying In Pdf Template Using Spring Boot, Flying Saucer And Thymeleaf

I create a file pdf from html template using Spring Boot, flying saucer, thymeleaf. But image is not displaying in my file. Project structure: code html:
classpath: prefix. This loads your file directly from the classpath, no matter if you are running from a .jar or within your IDE. Here is an example:

<imgalt="mastercard"th:src="@{classpath:static/images/mastercard.png}" />

More information about classpath: can be found in the official documentation.

Solution 2:

In order to embed an image in a PDF generated by Flying Saucer,

1) Convert the image to a base64 encoded string.

Pathpath= Paths.get("src/main/resources/static/images/mastercard.png");
Stringbase64Image= convertToBase64(path);

Function to convert image stored in a path like shown above, to a base64 encoded string

private String convertToBase64(Path path) {
    byte[] imageAsBytes = newbyte[0];
    try {
      Resource resource = new UrlResource(path.toUri());
      InputStream inputStream = resource.getInputStream();
      imageAsBytes = IOUtils.toByteArray(inputStream);

    } catch (IOException e) {
      System.out.println("\n File read Exception");
    }

    return Base64.getEncoder().encodeToString(imageAsBytes);
  }

2) Set the base64 encoded image in the thymeleaf context

Contextcontext=newContext();
    Stringimage="data:image/png;base64, " + base64Image;
    context.setVariable("image",  image);

    Stringhtml= templateEngine.process("template", context);

3) In HTML, set the value of image as shown below:

<imgth:src="${image}" style="width: 200px; height=100px"/>

4) Finally, render the HTML template to PDF

ITextRendererrenderer=newITextRenderer();
  renderer.setDocumentFromString(html); // html -> String created in Step 2
  renderer.layout();
  finalByteArrayOutputStreambaos=newByteArrayOutputStream();
  renderer.createPDF(baos)

Now you have the byteArrayOutputStream of the generated PDF, with which you can choose to store them to a file server or serve it to a client in a format of your choice.

Solution 3:

Use standard html src atribute and relative path from root of the project.

You can put your image in the root of the project and use it like this:

<imgsrc="mastercard.png" />

If you want to resource folders you can set it like this:

<imgsrc="src/main/resources/static/images/mastercard.png" />

Solution 4:

I faced the same issue but reading image file from disk is little costly, I would suggest you go with uri-data

http://www.tothenew.com/blog/using-data-urls-for-embedding-images-in-flying-saucer-generated-pdfs/

Because you anyway going to read image to generate PDF, better keep it in template.

Post a Comment for "Image Not Displaying In Pdf Template Using Spring Boot, Flying Saucer And Thymeleaf"