Wednesday, April 30, 2025

Generate pdf using flying saucer and freemarker

In this article we will go through flying saucer framework and how to use the same to generate pdfs. 

Maven dependencies

We will add flying saucer and free marker dependencies as below:

<dependency>

<groupId>org.xhtmlrenderer</groupId>

<artifactId>flying-saucer-pdf</artifactId>

<version>9.4.1</version>

</dependency>


Ftlh file

Now we will create a sample demo.ftlh file under resources/templates folder which will be used to generate html and then pdf.

<html>

<body>


<h1>Pdf demo generated at ${timestamp}</h1>

<h2>Second header</h2>


</body>

</html>


Implementation

The implementation to infuse data into this ftlh is as below:

@Service

public class DemoService {


@Autowired

Configuration configuration;


public File generatePdf() {

File pdf = new File("Demo.pdf");

Map<String, Object> model = new HashMap<>();

model.put("timestamp", new SimpleDateFormat("dd MMM yyyy").format(new Date()));

OutputStream os;

try {

os = new FileOutputStream(pdf);

ITextRenderer itr = new ITextRenderer();

itr.setDocumentFromString(getHtml(model));

itr.layout();

itr.createPDF(os);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

return pdf;

}


private String getHtml(Map<String, Object> model) {

StringWriter stringWriter = new StringWriter();

configuration.setClassForTemplateLoading(this.getClass(), "/templates/");

try {

configuration.getTemplate("demo.ftlh").process(model, stringWriter);

} catch (TemplateException | IOException e) {

e.printStackTrace();

}

return stringWriter.getBuffer().toString();

}

}


Test

We shall implement a rest api to test the above implementation. Please note that you will need to add spring boot starter and spring web dependencies for below implementation.

@RestController

public class DemoController {


@Autowired

DemoService demoService;


@GetMapping("/generatePdf")

public ResponseEntity<Resource> generatePdf() throws FileNotFoundException {

File file = demoService.generatePdf();

InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

return ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM)

.body(resource);

}


}


Output

Once we invoke the api it will generate a pdf as below:






No comments:

Post a Comment