Generate and download the PDF using ITEXT

In this blog you can find the sample code to generate and download the PDF using ITEXT PDF. For my sample code I have been using the Angular as front end and Java spring boot as back end.

If you are beginner before you continue further, you should know how to create Angular application and how to create spring boot applications. If you do not know about it, please visit below links. https://samplecoder.com/how-to-create-a-spring-boot-application-in-sts/ https://samplecoder.com/basic-angular-cli-comments/

The report is a consolidated data in tabular format it may be a bank statement or credit card bill or telephone bill and etc.,. When the customer uses our application some time they want to see their data and submit that hard copy to someone. At that time they did not show interest to check it on the screen and prepare documents, it may be a big headache to them. In that case the best solution is we can prepare the pdf or excel file and make it download by users.

Add an ITEXT plugin in pom.xml

<dependency>
		    <groupId>com.itextpdf</groupId>
		    <artifactId>itextpdf</artifactId>
		    <version>5.5.13.2</version>
		</dependency>

Controller

@GetMapping("/downloadpdf")
	private ResponseEntity<Resource> downloadPdf() throws DocumentException{
		ByteArrayInputStream inputStream = null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		Document document = new Document(PageSize.A4, 20, 20, 30, 1);
		PdfPTable table = new PdfPTable(3);
        table.setWidthPercentage(100);
        Font headFont = FontFactory.getFont(FontFactory.TIMES_ROMAN);
        headFont.setSize(11);
        
        PdfPCell hcell;
        hcell = new PdfPCell(new Phrase("ID", headFont));
        hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        hcell.setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(hcell);
        
        hcell = new PdfPCell(new Phrase("Name", headFont));
        hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        hcell.setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(hcell);
        
        hcell = new PdfPCell(new Phrase("Std.", headFont));
        hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
        hcell.setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(hcell);
        
        Font cellFont = FontFactory.getFont(FontFactory.TIMES_ROMAN);
        cellFont.setSize(11);
        
        for(int i = 1; i <= 10; i++) {
        	PdfPCell cell;

    		cell = new PdfPCell(new Phrase("STU00"+i, cellFont));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);

            cell = new PdfPCell(new Phrase("St Name "+i, cellFont));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            
            cell = new PdfPCell(new Phrase(String.valueOf(i), cellFont));
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
        }
        
        PdfWriter.getInstance(document, out);
        document.open();
        document.add(table);
        document.close();
        inputStream = new ByteArrayInputStream(out.toByteArray());
	 	Resource resource = new InputStreamResource(inputStream);
	 	String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("ddMMyyyyhhmmss"))+".pdf";
	 	return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(resource);
	}

Angular – component.ts

downloadPdf(){
   
      this.studentService.downloadPdf().subscribe(data => {
        let blob = new Blob([data], {
          type: 'application/pdf' // must match the Accept type
        });
        let url = window.URL.createObjectURL(blob);
        window.open(url)
        window.URL.revokeObjectURL(url);
      })

  }

student.service.ts

downloadPdf(): Observable<any> {
    let headerOptions = new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/pdf'
    });
    let requestOptions = { headers: headerOptions, responseType: 'blob' as 'blob'};
    
    return this.http.get('/api/student/downloadpdf', requestOptions);
  }

Conclusion

Now you are there at the end of this post. In this blog, I have posted the steps to generate the PDF report and download it using the ITEXT and Java Spring boot along with Angular. After reading this blog, I hope you got some idea about how to implement ITEX PDF in your spring boot project, And how to generate and download PDF file