Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Javascript PDFKit Example to Add Images From URL in PDF Document Using BLOB Stream Library

Posted on February 12, 2023

 

 

Welcome folks today in this blog post we will be adding images from url in pdf document using pdfkit library in browser using javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to include the library cdn of these libraries inside the index.html file as shown below

 

 

index.html

 

 

1
2
3
<body></body>
<script src="https://github.com/devongovett/pdfkit/releases/download/v0.8.0/pdfkit.js"></script>
<script src="https://github.com/devongovett/blob-stream/releases/download/v0.1.3/blob-stream.js"></script>

 

 

Now we need to add the javascript code which is shown below

 

 

script.js

 

 

JavaScript
1
2
3
4
5
6
7
  var filesLoaded = 0;
 
    var files = {
        img1: {
            url: 'https://pdfkit.org/docs/images/test.jpeg',
        }
    };

 

 

As you can see first of all we are declaring an array where we are providing the url of the images that needs to be inserted inside the pdf document.

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
var doc = new PDFDocument({
        layout: 'landscape',
        size: [311.83, 595.28],
        margins: {
            top: 0,
            bottom: 0,
            left: 0,
            right: 0
        }
    });

 

 

And now you can see that we are declaring a new pdf document using the pdfkit constructor and then we are attaching the different properties of the pdf document such as the layout which can either be portrait or landscape and then we are providing the size of the pdf document and then we are providing the margins of the pdf document from all directions.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
var stream = doc.pipe(blobStream());
 
for (var file in files) {
        files[file].xhr = new XMLHttpRequest();
        files[file].xhr.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                loadedFile(this);
            }
        };
        files[file].xhr.responseType = 'arraybuffer';
        files[file].xhr.open('GET', files[file].url);
        files[file].xhr.send(null);
    }

 

 

And now we are initializing the blob stream constructor and passing it to the pdkit library. And then we are looping through all the images defined inside the array. One by one we are using ajax to make the http request to the image and getting it’s base64 code by using the arraybuffer and then sending that get request to the url.

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
function loadedFile(xhr) {
        for (var file in files) {
            if (files[file].url === xhr.responseURL) {
                files[file].data = xhr.response;
            }
        }
        filesLoaded += 1;
        if (filesLoaded == Object.keys(files).length) {
            showPDF();
        }
    }

 

 

As you can see here we are looping through all the images and then we are simply attaching the response which is coming from the ajax request to the files data.

 

 

JavaScript
1
2
3
4
5
6
function showPDF() {
 
        //obrazki
        doc.image(files.img1.data, 0, 0, { fit: [doc.page.width, doc.page.height] });
        doc.end();
    }

 

 

And lastly in this function we are adding the image inside the pdf document using the image() method and here we are providing the base64 data of the image and then we are providing the x and y coordinates and then we are providing the width and height of the image in pdf document.

 

 

JavaScript
1
2
3
4
stream.on('finish', function () {
        var blob = stream.toBlob('application/pdf');
        saveData(blob, 'aa.pdf');
    });

 

 

And now basically guys we are listening for the stream end event here when it reaches basically here we will be converting the base64 data or arraybuffer to the blob object and then we will be calling the saveData() function to download the pdf document as an attachment inside the browser using this blob object. And in the second argument we are providing the filename of the pdf document.

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
var saveData = (function () {
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        return function (blob, fileName) {
            var url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);
        };
    }());

 

 

As you can see here in this function we are creating the dynamic anchor element just attaching the required attributes to it such as the filename and the URL of the pdf document and automatically clicking it without showing it to the user. Now if you open the index.html file inside the browser you will see the below result

 

 

 

Recent Posts

  • Android Java Project to Store,Read & Delete Data Using SharedPreferences Example
  • Android Java Project to Download Multiple Images From URL With Progressbar & Save it inside Gallery
  • Android Java Project to Capture Image From Camera & Save it inside Gallery
  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme