In this article, I am going to demonstrate a simple way that we could support pdf download from server. We will generate a pdf document in the server using itextpdf api. And then we will write the pdf document in the output stream.
First add the dependency in the pom.xml
Next step, define a method where you write the functionality to write a pdf document.
Reference:
http://stackoverflow.com/questions/16652760/return-generated-pdf-using-spring-mvc
http://itextpdf.com/examples/iia.php?id=173
First add the dependency in the pom.xml
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.0.6</version> </dependency>
Next step, define a method where you write the functionality to write a pdf document.
@RequestMapping(value="/getpdf", method=RequestMethod.GET)
public ResponseEntity<byte[]> getPdf(@RequestBody String json){
String text = json;
if (text == null || text.trim().length() == 0) {
text = "You didn't enter any text.";
}
// step 1
Document document = new Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
PdfWriter.getInstance(document, baos);
// step 3
document.open();
// step 4
document.add(new Paragraph(String.format(
"You have submitted the following text using the %s method:",
"getpdf")));
document.add(new Paragraph(text));
// step 5
document.close();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// retrieve contents of "C:/tmp/report.pdf"
byte[] contents = baos.toByteArray();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return response;
}
Reference:
http://stackoverflow.com/questions/16652760/return-generated-pdf-using-spring-mvc
http://itextpdf.com/examples/iia.php?id=173
No comments:
Post a Comment
If you like to say anything (good/bad), Please do not hesitate...