Convert HTML to PDF

Why do we need to convert the HTML into PDF?

Let you can consider you have been working in one e-commerce project. That definitely has the option or page to customer can check the their orders. There you have to display the order history along with the product image, quantity price per item discount etc. As a developer, you know how difficult to bring that page as per your client requires. You have to add many HTML tags and CSS. If your client gives requirement that the customer can download and see the their orders in PDF format and that pdf should be same as your HTML design. In this case you have to spend more time to designing the PDF and more hard to bring same design. So here most easiest way is converting the HTML code into PDF.

In this blog, I have given you the sample code for converting the HTML into PDF. For my example, I have been using the ITEXT PDF plugin. My back end code is completely in Java Spring Boot. and my front end is in Angular

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/

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);
  }

Conclusion

In this blog, I have posted the sample code for converting the your HTML code into the PDF, by using the Java Spring Boot as back end and Angular as a front end. Hope you have got some idea about how to convert the HTML to PDF. After you read this blog, I believe you got the expected solution for your problem. And now you can implement same in your project and get smiles from your client.