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);
}
}
Thanks for sharing this useful information about system design and modern development practices. Having a strong foundation in Java along with system architecture knowledge is very important today. Learners can explore Top System Design with Java Online Training in Hyderabad to gain practical insights into real-world system design.
ReplyDeleteA very helpful post for Java learners! Strong fundamentals always make a difference in programming. You can explore Best Core JAVA Online Training in Hyderabad to enhance your skills.
ReplyDeleteVery helpful for freshers planning Java Full Stack Online Training for Freshers in Hyderabad.
ReplyDelete