Welcome folks today in this blog post we will be encoding local pdf file or from url to base64 string
in javascript and node.js. All the source code of the application is given below.
Get Started
In order to get started we need to install pdf-to-base64
library by using the npm
command
npm i pdf-to-base64
After installing this library make a index.js
file and copy paste the following code
index.js
from local pdf file
1 2 3 4 5 6 7 8 9 10 11 12 |
const pdf2base64 = require('pdf-to-base64'); pdf2base64("test/sample.pdf") .then( (response) => { console.log(response); //cGF0aC90by9maWxlLmpwZw== } ) .catch( (error) => { console.log(error); //Exepection error.... } ) |
Here we are taking the example of local pdf
file where we provide the path of the pdf file which is present inside the computer and then it converts to base64 string using this library.
If you run the node.js project by running the index.js
file by running the following command
node index.js
Converting URL PDF to Base64
Now we will be converting a url
pdf document where user will provide the link of the pdf document
and then we will be converting to base64 code
1 2 3 4 5 6 7 8 9 10 11 12 |
const pdf2base64 = require('pdf-to-base64'); pdf2base64("http://www.africau.edu/images/default/sample.pdf") .then( (response) => { console.log(response); //cGF0aC90by9maWxlLmpwZw== } ) .catch( (error) => { console.log(error); //Exepection error.... } ) |