How to send PDF file over WhatsApp in NodeJS

Nitesh Jain
Nov 2 · 3 min read

©https://www.datarecovery.institute/export-whatsapp-chat-to-pdf/

Effective communication is the key to building and nurturing a solid relationship with the customers in any business. It can help you gain their loyalty leading to purchases, positive word-of-mouth and referrals. On the flip side though, failure to communicate well can create dis-satisfaction, frustration and a decrease in sales. And in the age of social media a negative word-of-mouth can spread like wildfire. The medium you choose to communicate is equally important to what you want to communicate to your customers. Personalised communications related to services, marketing campaigns and customer’s bookings play an important role in determining the overall customer experience . A good customer experience will increase the companies customer retention numbers. Although there are several mediums through which communication can be enabled like sms, emails, notifications , calls, ivr and many more , whatsapp has gained a lot of popularity in the last couple of years.

This blog explains how to send information documents to the customers as pdf over whatsapp.
One can follow these steps to send any other form of documents over whatsapp.

Create a data object containing all the essential information to be sent as part of the pdf. Lets call it content.
Create an html template defining the structure and layout of the pdf as intended to be displayed to the end user. Handlebars templating engine can be used to create the html and obtain compiled template.

let template = await Promise.resolve(Handlebars.compile(html));

Using the library html-pdf, create a pdf in the following way by passing the filePath and options parameters as desired.


const pdfCreator = require('html-pdf');
// file path where created pdf will get stored
const filePath = resolve('whatsapp/pdf/');let content = {user_name : 'Garry',greeting_info: 'Have a great day!!'};async function createPdf(content, filePath, template) {const options = {format: "A3",orientation: "portrait",border: "32px",type: "pdf"};return new Promise(function (resolve, reject) {pdfCreator.create(template(content), options).toFile(filePath, (err, res) => {if (err) {reject(err);}resolve();});})}

Once the pdf is created it needs to be uploaded on whatsapp server using whatsapp business api /v1/media.

const fs = require('fs');
// contentType - 'application/pdf'async function uploadOnWhatsapp(filePath, contentType) {const stats = fs.statSync(filePath);const fileSizeInBytes = stats.size;let requestOptions = {method: 'POST',url: whatsapp_server_url+ '/v1/media',json: true,headers: {authorization: your_bearer_token,'content-type' : contentType,'content-length': fileSizeInBytes,},};return await fs.createReadStream(filePath).pipe(requestPromise(requestOptions));}

If the document is successfully uploaded , document id will be received in the response .

{"media": [{"id": "f043afd0-f0ae-4b9c-ab3d-696fb4c8cd68"}]}

If error responses are received , refer to https://developers.facebook.com/docs/whatsapp/api/errors to know more about these errors and their resolution.

After uploading the document , it can be sent out to any whatsapp user as http post request using the same media.id received in upload request’s response using whatsapp business api /v1/messages.

async function sendWhatsappMsg() {const requestOptions = {method: 'POST',url: whatsapp_server_url+ '/v1/messages',headers: {authorization: your_bearer_token},body: {to: whatsappId, // whatsapp numbertype: "document",id: media.id,// optional fieldsdocument: {provider: {name : your_business_account_id},caption: "Greetings",}},json: true,timeout: 10000};return await requestPromise(requestOptions);}

The successful response will contain message.id which can be used to retrieve the status of message sent and its content.

Congratulations!! You have just successfully sent out a pdf over Whatsapp.

References:
https://developers.facebook.com/docs/whatsapp/api/media/
https://developers.facebook.com/docs/whatsapp/api/messages

https://handlebarsjs.com/

Nitesh Jain

Written by

Software Developer and Travel Enthusiast

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade