How To Create PDF through HTML Template In Spring Boot

Posted By : S. Ajit | 09-Apr-2017

This blog assumes that your are using spring boot maven project and you have sound knowledge of thymeleaf template engine. To create PDF from HTML we are going to use Thymeleaf which is a template rendering engine and flying-saucer-pdf which is a XHTML rendrer

Follow the below written procedure to create a simple PDF file:

 

1. Add Thymeleaf and flying-saucer-pdf dependency in your pom.xml

     <!-- Thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>       

     <!-- flying saucer pdf -->  
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf</artifactId>
            <version>9.1.4</version>
        </dependency>

 

2. Create a ClassLoaderTemplateResolver bean will will help us to resolve html template

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

@Configuration
public class ThymeleafConfiguration {
  @Bean
  public ClassLoaderTemplateResolver emailTemplateResolver(){
    ClassLoaderTemplateResolver emailTemplateResolver=new ClassLoaderTemplateResolver();
    emailTemplateResolver.setPrefix("templates/");
    emailTemplateResolver.setTemplateMode("HTML5");
    emailTemplateResolver.setSuffix(".html");
    emailTemplateResolver.setTemplateMode("XHTML");
    emailTemplateResolver.setCharacterEncoding("UTF-8");
    emailTemplateResolver.setOrder(1);
    return emailTemplateResolver;
  }
}

 

3.  Add your HTML template to templates folder which will be inside the resources folder of your spring boot application. Your HTML template may look like this

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>

 

4. Now create a PdfGeneratorUtil class which will be our utility class to generate pdf. You will find a createPdf method in below code, what this method does is that on providing template name and a Map (which will have our dynamic content for pdf) will generate PDF and save it to temporary location in your system. createPdf method uses thymeleaf to render HTML template and flying-saucer-pdf uses this HTML to generate PDF.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;


@Component
public class PdfGenaratorUtil {
	@Autowired
	private TemplateEngine templateEngine;
	public void createPdf(String templateName, Map map) throws Exception {
		Assert.notNull(templateName, "The templateName can not be null");
		Context ctx = new Context();
		if (map != null) {
		     Iterator itMap = map.entrySet().iterator();
		       while (itMap.hasNext()) {
			  Map.Entry pair = (Map.Entry) itMap.next();
		          ctx.setVariable(pair.getKey().toString(), pair.getValue());
			}
		}
		
		String processedHtml = templateEngine.process(templateName, ctx);
		  FileOutputStream os = null;
		  String fileName = UUID.randomUUID().toString();
	        try {
	            final File outputFile = File.createTempFile(fileName, ".pdf");
	            os = new FileOutputStream(outputFile);

	            ITextRenderer renderer = new ITextRenderer();
	            renderer.setDocumentFromString(processedHtml);
	            renderer.layout();
	            renderer.createPDF(os, false);
	            renderer.finishPDF();
	            System.out.println("PDF created successfully");
	        }
	        finally {
	            if (os != null) {
	                try {
	                    os.close();
	                } catch (IOException e) { /*ignore*/ }
	            }
	        }
	}
}

 

5. In your service or controller, autowire PdfGeneratorUtil class

@Autowired
PdfGenaratorUtil pdfGenaratorUtil;

Now create a Map, which will be use to bind our dynamic data to HTML template .Let suppose we want to show name in PDF for this we will write following code.

 Map<String,String> data = new HashMap<String,String>();
    data.put("name","James");
    pdfGenaratorUtil.createPdf("greeting",data); 

 Here greeting denote greeting.html file inside templates folder

This will generate PDF, Assuming that you are using a linux system PDF will be generated inside tmp folder in root directory.   

Thanks

 

 

 

 

About Author

Author Image
S. Ajit

Ajit is a software developer who loves solving problems and programming in C, C++, Java. He also has a passion to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..