Blog Detail

  • Home
  • Convert HTML to PDF in Spring Boot using Itext PDF

Convert HTML to PDF in Spring Boot using Itext PDF

Convert the html into pdf is easiest way to generate the colorfull pdf and download it by using angular. the steps are below

pom.xml

<!-- iText Core -->
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext7-core</artifactId>
			<version>7.1.9</version>
			<type>pom</type>
		</dependency>

		<!-- iText pdfHTML add-on -->
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>html2pdf</artifactId>
			<version>2.1.7</version>
		</dependency>

Controller.java

@GetMapping("/htmlToPdf")
	private ResponseEntity<Resource> htmlToPdf() throws IOException{
		ByteArrayInputStream inputStream = null;
		StringBuffer buffer = new StringBuffer();
		buffer.append("<h1 style='color:red;'>Students List</h1>");
		buffer.append("<table>")
			.append("<thead>").append("<th>ID</th>").append("<th>Name</th>").append("<th>Std</th>").append("</thead>")
			.append("<tbody>");
		for(int i = 1; i<=10; i++) {
			buffer.append("<tr>")
			.append("<td>").append("STU00").append(i).append("</td>")
			.append("<td>").append("Name").append(i).append("</td>")
			.append("<td>").append(i).append("</td>")
			.append("</tr>");
		}
		buffer.append("</tbody>").append("</table>");
		String html = buffer.toString();
		ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
		HtmlConverter.convertToPdf(html, pdfStream);
		inputStream = new ByteArrayInputStream(pdfStream.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 – student.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);
      })

  }

angular – 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/htmlToPdf', requestOptions);
  }

Write a comment