Print PDF in Angular

Welcome back to another Angular-related article. In this one, we will see how to download PDF in Angular. We will be making a POST request that returns a PDF using Angular’s HttpClient. To make angular get pdf from API, we would also need to create a backend service that would be sending the PDF as a response. But I have already created a Node JS service for it in this article: How to Convert HTML to PDF with JavaScript Using Puppeteer 

Prerequisites!

Table of Content

  1. Node JS Service to Convert HTML to PDF 
  2. Angular HTTP Request to Print PDF 

STEP 1: Node JS Service to Convert HTML to PDF

First, we need to start our backend service which will convert raw HTML to PDF. Furthermore, it will be accepting POST requests and then send the converted PDF in response. For simplicity, I will not go into depth about the backend service, for that check out this article for a step-by-step guide.  

I am simply going to paste the JavaScript code that I made in the Node JS service that takes care to convert HTML to PDF and sends it back in response with the content type as a BLOB. 

				
					const puppeteer = require("puppeteer"); 
const fs = require("fs"); 
  
  
exports.generate_pdf = async (req, res) => { 
  const browser = await puppeteer.launch({ headless: true }); 
  const page = await browser.newPage(); 
  const html = await `${fs.readFileSync(`./dummyHmlTemplate.html`, "utf8")}`; 
  await page.setContent(html, { waitUntil: "domcontentloaded" }); 
  
  const pdf = await page.pdf({ 
    format: "A4", 
    printBackground: false, 
    preferCSSPageSize: true, 
    displayHeaderFooter: true, 
  
    headerTemplate: `<div class="header" style="font-size:20px; padding-left:15px;"><h1>Main Heading</h1></div> `, 
    footerTemplate: '<footer><h5>Page <span class="pageNumber"></span> of <span class="totalPages"></span></h5></footer>', 
    margin: { top: "200px", bottom: "150px", right: "20px", left: "20px"}, 
  }); 
  
  //  SENDING BACK PDF AS BLOB IN RESPONCE TO API CALL 
  res.send(pdf); 
}; 
				
			

This code is reading raw HTML from a file kept in the root directory named “dummyHmlTemplate.html”. So just keep that there before using this code.  

Note that the above code is sending the PDF in response in BLOB format. If you want to directly send the file in pdf format, then just before “res.send(pdf);” line of code, add the following line:  

				
					res.contentType("application/pdf"); 
				
			

You can test it out in the POSTMAN tool, as shown in this article here. The above Node JS service uses an NPM package called Puppeteer to convert HTML to PDF.  

STEP 2: HTTP Request, Angular Get PDF From API

To make Angular download pdf, we will now create our POST request to call our backend service to generate pdf. The following code does exactly that.  

				
					let pdfReqBody = { 
    // any usefull data you would want to send to service 
} 
  
this.http.post(`http://localhost:3000/pdf`, pdfReqBody, { responseType: 'blob'}).subscribe(res =>{ 
      let blob = new Blob([res], { type: 'application/pdf' }); 
      let pdfUrl = window.URL.createObjectURL(blob); 
  
      var PDF_link = document.createElement('a'); 
      PDF_link.href = pdfUrl; 
    //   TO OPEN PDF ON BROWSER IN NEW TAB 
      window.open(pdfUrl, '_blank'); 
    //   TO DOWNLOAD PDF TO YOUR COMPUTER 
      PDF_link.download = "TestFile.pdf"; 
      PDF_link.click(); 
    }); 
				
			

Explanation: 

The above code does a few things to make angular download pdf, so let’s break it down. Firstly, I have created an (empty) JSON object named “pdfReqBody” and sent it with the POST request to my backend service. It’s empty because for this example I don’t need anything to send to the service. 

My API endpoint in the backend service is running on ‘http://localhost:3000/pdf’. However, you would change it according to your endpoint URL. As a result of this HTTP POST call, I would be receiving the PDF in binary object form. Which would be the HTTP response sent by the Node JS backend service. This binary object response needs to be parsed into a BLOB object in Angular. At the same time, I’ve also set its type to ‘application/pdf’. Afterward, we are creating a URL link using that BLOB object. This URL is the source of that PDF now.  

Finally, we need to have that PDF either opened in a new tab or have Angular download PDF file. Therefore, we have created a temporary HTML anchor element ‘a’. And gave it all the properties using JS. Then lastly, programmatically clicked the anchor element to perform supposed actions.  

And that’s a wrap! 

I’m optimistic that you guys must’ve found the content useful. I hope now you have a good idea of How to download PDF in Angular. Feel free to share your thoughts and opinions in the comments section down below. 

Have a great one!