pdfmake

Insert Image from URL in PDF using PDFMake

PDFMake is a popular javascript library for client-side and server-side pdf generation. In my previous article Angular Export to PDF using PDFMake we have seen PDFMake setup and pdf generation with online resume builder application. 

PDFMake provides features like insert an image, QR Code, Table Of Contents, Header and Footers, SVG, List and so on. 

PDFMake supports insert image in PDF, but one drawback of is It only supports adding an image from the local file system or in the form of a base64 data URL. It doesn’t support external URL directly.

So, In this article we will see How to insert image from URL in PDF using PDFMake ?

As we discussed, PDFMake directly does not support the insert image from URL. It supports base64 format or image path from the local file system. but in client-side pdf generation you have only one option, insert an image as base64 format.

So here we will implement it with the below approach :

  1. Get base64 formatted data URL from the external image URL.
  2. Add base64 formatted data URL in document definition.
  3. Generate PDF

We will write a function that will generateBase64 formatted Data URL from External Image URL.

  getBase64ImageFromURL(url) {
    return new Promise((resolve, reject) => {
      var img = new Image();
      img.setAttribute("crossOrigin", "anonymous");

      img.onload = () => {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;

        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var dataURL = canvas.toDataURL("image/png");

        resolve(dataURL);
      };

      img.onerror = error => {
        reject(error);
      };

      img.src = url;
    });
  }
Source code of the above function is from the StackOverflow answer, I have changed it to return promise.

Above function returns promise so that we can use it with async/await while generating document definition.

We will create one async function, which will configure the document definition and generate the PDF.

  async showPdf() {
    let docDefinition = {
      content: [
        {
          text: 'PDF Generated with Image from external URL',
          fontSize : 20
        },
        {
          image: await this.getBase64ImageFromURL(
            "https://images.pexels.com/photos/209640/pexels-photo-209640.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=300"
          )
        }        
      ]
    };

    pdfMake.createPdf(docDefinition).open();
  }

As you can see, we are passing external URL in getBase64ImageFromURL function which will generate base64 data URL, and add in document definition.

Here we are using async/await, We have to wait to generate pdf until document definition is built with base64 image.

The await expression causes async function execution to pause until a Promise is settled, that is fulfilled or rejected, and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise.

after that, we will call the showPdf()  function. it uses to open pdf pdfMake.createPdf(docDefinition).open();

This will generate pdf as below :

Using the above approach we can generate pdf with an image from URL.

This approach is good if you don’t have to add so many images, but if your pdf includes so many images from URL then above approach is might be not a good solution, because for each image you have to generate data URL and add it in document definition, which will affect the application performance.

In this article, we have seen insert an image from a URL in PDF using PDFMake.

I hope you like this article, please provide your valuable feedback and suggestions in below comment section🙂.

For more updates, Follow us 👍 on NgDevelop Facebook page.

Ankit

Disqus Comments Loading...
Share
Published by
Ankit

Recent Posts

Awesome Charts in Angular 13 with ng2-charts

Charts help us to visualize large amounts of data in an easy-to-understand and interactive way.  …

2 years ago

Client-Side PDF Generation In Angular 13 With PDFMake

Generating reports, invoices, blog content, documents, guidelines, forms, etc in PDF form is a common…

2 years ago

Dynamically Add Title and Meta Tags on Route Change in Angular

Web Page title, description, and other meta tags are very important for the Search Engine…

4 years ago

Integrate Google Analytics with Angular | Angular SEO

Google Analytics is a popular analytical tool for web and mobile applications from Google. It…

4 years ago

16 Best Chrome DevTools Tips and Tricks

Chrome DevTools provides amazing features to debug source code, capture element state, update and test…

4 years ago

Data Visualization with ECharts in Angular using ngx-echarts

Angular Charts Series Articles Best Angular Chart Libraries How to use ngx-charts in angular application…

4 years ago