The image fails to appear while creating a PDF in AngularJS using pdfmake

I recently started using a fantastic pdf printing library called pdfmake in my angularjs SPA to generate PDF files. Everything was going smoothly until I tried to include images in the PDF. Strangely, when I added images, nothing happened - no errors, no empty PDF, just total silence. There weren't even any 404 errors indicating missing files.

Below is the code snippet that's causing me trouble:

var dd = {
        content: [
            {
                image: 'picture13438908025659.jpg'
            },
            {
                text: 'Patient\'s Detail', fontSize: 18, bold: true
            },
            {
                columns: [
                    {
                        text: 'Patient\'s ID: ' + $scope.prescription.Patient[0].id, bold: false
                    },
                    {
                        text: 'Name: ' + $scope.prescription.Patient[0].name, bold: false
                    },
                    {
                        text: 'Age: ' + $scope.prescription.Patient[0].age, bold: false
                    },
                    {
                        text: 'Contact: ' + $scope.prescription.Patient[0].contact, bold: false
                    }
                ]
            },
            {
                text: 'Address: ' + $scope.prescription.Patient[0].address, bold: false
            }
        ]
    }

Answer №1

This method is quite simple:

1) Start by converting your image into base64 format using this website

2) Once you have the base64 code, replace it in the following line of code:

image : 'base64', // use your base64 instead of image.jpg

3) That's it! This approach comes in handy when the image fails to load via a link, so you can opt for using base64 instead.

Answer №2

Converting an image into base64 format is a common practice recommended by documentation. Below is a foolproof code that will get the job done:

function transformImageToBase64URL(imageUrl, callback, outputFormat){
    var canvas = document.createElement('CANVAS'),
    ctx = canvas.getContext('2d'),
    img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var dataURL;
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
img.src = imageUrl;
}

Simply include this in your PDF generation code:

var docDefinition = {
  content: [
    {
      // DataURI images are commonly used on the browser side
      // Provide dimensions for resizing options
      image: 'data:image/jpeg;base64,...encodedContent...'
    }]

Answer №3

To begin, you'll want to change your image into base64 format before using it in the image property. Here's an example:

{
  image: 'data:image/jpeg;base64,...encodedContent...',
  width: 75,
  height: 75,
  alignment : 'left'
}

If you need more information, you can check out this resource -

Answer №4

Have you tried including width:your_required_width in the image object to see if that resolves the issue? I encountered a similar problem, and it turned out that the image resolution was too high for PDFMake to display properly on standard size paper. I recommend using the PDFMake playground for creating your document definitions in the future, as it's a very useful tool.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch out the URL in npm's build process

While developing, I am using a mock REST service but for the public release, I intend to switch to a real backend. Is there a method to update the endpoint URL during the npm build process? ...

Challenge with the npm packages and dependencies in AngularJS is causing difficulties

Encountering this particular error... angular.js:38 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.4/$injector/modulerr?p0=myApp&p1=Error%3A%2…arJS%2Fangular-my-app%2Fnode_modules%2Fangular%2Fangular.min.js%3A22%3A179) ...

"Clicking on a jQuery div will cause it to slide down, and clicking again

I am currently working on this code snippet: $("#right").click(function() { $("#signin").stop().slideDown(300); }); At the moment, it drops down when clicked, but I would like it to slideUp() when clicked again. Your help is appreciated. On a relate ...

Assigning the href attribute dynamically

How can you dynamically set the href attribute of the <a> tag using jQuery? In addition, what is the method for retrieving the value of the href attribute from the <a> tag with jQuery? ...

What is the best way to automatically post to Slack at regular intervals?

In order to provide users with the option to choose when they receive information from my API, such as daily at 5PM or every Friday at 5PM, I have a configuration page. Once users set their preferred time, I want to send them a Slack message at that specif ...

Using http-proxy to forward request to a different port

In my code, I am creating a proxy that routes all application calls from port 3000 to port 3002 seamlessly. var http = require('http'), httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer(); http.create ...

Assign an attendee the role of organizer in the Google Calendar API

I am currently utilizing the googleapis npm package to facilitate calendar event creation. Below is my request payload for calendar.events.insert in order to generate an event: { "summary":"Biology class", "location":"Google Meet: Please follow the go ...

Interacting with wpdb using AngularJS

I just started learning AngularJS and I'm eager to implement it on my WordPress website. My goal is to display a table with data from a database in my WordPress site, but I am encountering difficulties accessing the WordPress functions and variables. ...

How do I resolve the issue of PHP sendmail form sending empty emails and fix the JavaScript?

I spent the whole day dealing with sendmail.php. Initially, I had an issue with not receiving emails, which I managed to fix. However, after that, I started receiving blank emails. It wasn't a problem with my PHP or HTML code, but rather with the Java ...

Execute the following onclick event when the button is enabled

I am trying to display a popup when the "add to cart" button is clicked (but only when the button is active!). I thought about using a div that wraps the button and changes the class from "disabled" to "enabled". I have tried using jQuery, but it could als ...

Can we utilize object properties in this manner?

Hey there! I've been experimenting with the react-bootstrap library recently, trying to get better at using it. While going through the tutorial, I came across some ES6 code that caught my attention. function FieldGroup({ id, label, help, ...props } ...

Replacing text with new content when text is stored in a separate file

After organizing all the strings from my code, I compiled them into a file named constants.ts. export class Constants { public static API_URL = '/api/'; public static CREATE_CHILD_API_URL = Constants.API_URL + '%s' + '/create- ...

Obtaining the NativeElement of a component in Angular 7 Jasmine unit tests

Within the HTML of my main component, there is a my-grid component present. Main.component.html: <my-grid id="myDataGrid" [config]="gridOptions" </my-grid> In main.component.specs.ts, how can I access the NativeElement of my-grid? Cu ...

Testing Jest with NodeJS involves simulating input from standard input (stdin)

I'm currently working on a command-line application that takes user input from standard input using the following code: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, }); rl.on('li ...

Saving the index.html file to disk when the button is clicked

Is there a way to export the current HTML page to a file? I have attempted to achieve this using the following code, but it only works when the page is loaded and not with a button click. <?php // Start buffering // ob_start(); ?> <?php file_pu ...

Implement Javascript Event Listener

I'm a newcomer to the world of javascript and I’m struggling to understand why the code below isn't functioning correctly: var displayMessage = document.getElementById("notification"); displayMessage.addEventListener("click", function() { ...

Unable to utilize jQuery's .append(data) function due to the need to use .val(append(data)) instead

I have been attempting to utilize JQuery .append(data) on success in order to change the value of an input to the appended data like this: .val(append(data)), but it doesn't seem to be working. Surprisingly, I can successfully change the value to a st ...

Creating a constant in router resolve using AngularJS

Is there a way to define a constant in the router resolve and then use it within a controller by dependency injection? Whenever I try to run the project, an error shows up stating that the provider obj is unknown. var app = angular.module("pikadOnlineAp ...

Issue with improper lighting on Three.Geometry objects when using LambertMaterial in Three.js

After enhancing my initial version of this inquiry (previously asked question) with a JSFiddle showcasing the latest build of Three.JS and illustrating the lighting issue on Three.Geometry, I encountered difficulties with dependencies in Stack Snippets. Ho ...

Hey there, I'm looking to use different CSS fonts on Windows and Mac for the same page on a web application. Can someone please guide me on how to accomplish this?

In order to tailor the font based on the operating system, the following criteria should be followed: For Windows: "Segoe UI" For Mac: "SF Pro" Attempts have been made using the code provided below, but it seems to load before the DOM and lacks persisten ...