Maven dependencies
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.4.1</version>
</dependency>
Ftlh file
<html>
<body>
<h1>Pdf demo generated at ${timestamp}</h1>
<h2>Second header</h2>
</body>
</html>
Implementation
@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
@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);
}
}
No comments:
Post a Comment