The conundrum of jsPDF's image compatibility

I am attempting to generate a PDF document on the client-side using the jsPDF library. The code I have written is as follows:

<script type="text/javascript" src="libs/base64.js"></script>
<script type="text/javascript" src="libs/sprintf.js"></script>
<script type="text/javascript" src="jspdf.js"></script>

<script>
var doc = new jsPDF();
var imgData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAAByCAMAAAAh126/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmGOCRNa8krajABAElEQVR4nO3aay+mmmHaSidPau/urZyi43j9nj/XHU0qAcATtSYChHIDTfqLWwRR2grgf5EkpQEAAAAASUVORK5CYII=';
doc.setFontSize(40);
doc.text(30, 20, 'Hello world!');
doc.output('datauri');
doc.addImage(imgData, 'JPEG', 15, 40, 200, 114);
</script>

However, it seems that only the text is being printed and not the image.
What could be causing this issue?

Answer №1

To incorporate a png image, you will need to acquire the most up-to-date version of jspdf.js and integrate the necessary png libraries.

<script type="text/javascript" src="libs/png_support/zlib.js"></script>
<script type="text/javascript" src="libs/png_support/png.js"></script>
<script type="text/javascript" src="jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="jspdf.plugin.png_support.js"></script>
<script type="text/javascript" src="jspdf.js"></script>

Next, adjust the format to 'PNG' within the script.

<script>
    var doc = new jsPDF();
    var imgData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABy...
    doc.setFontSize(40);
    doc.text(30, 20, 'Hello world!');
    doc.addImage(imgData, 'PNG', 15, 40, 200, 114);
    doc.output('datauri');
</script>

Answer №2

To add these functionalities to your HTML, include the following files:

<script src="CustomScripts/support/zlib.js"></script>
<script src="CustomScripts/support/png.js"></script>
<script src="CustomScripts/FileSaver.js"></script>
<script src="CustomScripts/jspdf.js"></script>
<script src="CustomScripts/jspdf.plugin.addimage.js"></script>
<script src="CustomScripts/jspdf.plugin.png_support.js"></script>

All of these files are available for download at https://example.com/jsPDF-libraries

The FileSaver.js file can be found in the libs/FileSaver.js folder, while zlib.js and png.js files are located in the libs/png_support.js directory.

If you do not require the ability to save PDF files, you may exclude the FileSaver.js file from the list.

In case you receive alerts about missing functions, refer to the dist/jspdf.debug.js file. Search for the specific function name and find the corresponding module that contains it. Include that module in the above list (following the jspdf.js file).

Answer №3

Make sure to include the doc.output method call once you have created the document:

doc.addImage(imgData, 'JPEG', 15, 40, 200, 114);
doc.output('datauri');

Answer №4

If you are utilizing a framework such as Vue.js, you have the option to store the image in a reactive state and display it within the view. Upon exporting this code snippet, the image will be visible.

const [image, setImage] = Vue.useState(null);

  Vue.useEffect(() => {
    const loadImage = async () => {
      let imageUrl =
        "your-image-url";
      let imageUrlFetched = await fetch(imageUrl);
      let blob = await imageUrlFetched.blob();
      let fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
      let file = new File([blob], fileName, { type: blob.type });
      setImage(URL.createObjectURL(file));
    };

    loadImage();
  }, []);

In conclusion, you can assign the reactive state, 'image', to the src attribute of an HTML img tag:

<img src={image} alt="" />

Answer №5

Currently, the jsPDF library exclusively supports images in JPEG format.

Unfortunately, the image with the data string

var imgData = 'data:image/png;base64,iVBORw...
is in PNG format.

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

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

Manipulating a DOM element in Angular 2 to alter its class attribute

I am a beginner in angular2. Here is my code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main', template: ` <div class="current"> </div> ` }) export class MainComponent impl ...

Ruby on Rails: clearing the asset pipeline cache by hand

While Rails usually clears the asset pipeline cache automatically when files are modified, I am facing a unique situation. I am providing my application as an HTML response to an Ajax request, cross-domain using rack-cors to bypass CORS. The issue arises ...

Heroku - JavaScript and CSS Updates Causing Loading Issues

Ruby version: 2.1.5 | Rails version: 4.1.1 For some reason, the changes I make to my JavaScript and CSS files are not reflecting on Heroku; it seems like the cached assets are still being used. I've tried removing the assets and precompiling them bef ...

Error: Unable to parse JSON field value due to an unexpected OBJECT_START

Currently in my coding project, I am utilizing node and mongoose to update a Watson rank and access the database. My goal is to insert multiple documents into the collection. While I can successfully add a single document, I encounter issues when creating ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

One issue encountered in the AngularJS library is that the default value does not function properly in the select element when the value and

In this AngularJS example, I have created a sample for the select functionality. It is working fine when I set the default value of the select to "$scope.selectedValue = "SureshRaina";". However, when I set it to "$scope.selectedValue = "Arun";", it does n ...

The variable remains undefined, despite the fact that the code executes correctly in a different location

I'm currently working on a multiplayer game in three js and integrating socket.io for real-time communication. I have all the player characters stored in an array called players on the server side. When each client connects, I send them the list of p ...

Tips for showcasing checkbox options on an HTML page (utilizing ejs) following the retrieval of information from MongoDB and making it editable for the User

Currently, I store data in mongo for a multiple-choice question and indicate the correct answers. In mongo, I save them like this: question.options.option1.check = "on" for the correct answers. When I navigate to the "edit" page, I retrieve the specific ...

Ways to verify whether a string has already been hashed in Node.js utilizing crypto

I am currently working on an application that allows users to change their passwords. For this project, I am utilizing Node.js along with the mongoose and crypto libraries. To generate hashes for the passwords, I have implemented a hook into the model&ap ...

What is the best way to transfer information to a different component using Vue router?

At the moment, I have a component that is displayed on the page. When I check the this.$router variable inside this component, I notice that the full path property is '/hello/reports?report=3849534583957' and the path property is '/hello/rep ...

What might be causing my Vue unit test to overlook a function?

I am in the process of creating unit tests for my component dateFormat.js using Jest. The focus is on testing the function formatDateGlobal. Here is an excerpt from the test: import DateFormat from '../dateFormat'; describe('dateFormat.js& ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

Building a simple messaging platform with the power of Socket.io and Node.js

After following the guide at http://socket.io/get-started/chat/, I attempted to create a basic chat application. However, upon running npm install --save socket.io I encountered the error message below. How can I resolve this issue? npm WARN package.jso ...

Error message in Node.js with Multer: The function '.array' is not recognized

I've spent the last two days searching for a solution to this issue, but the only reference I could find was an unresolved problem reported on version 1.1.0: https://github.com/expressjs/multer/issues/338 I am using the Node.js SDK and Express framew ...

What is the process for importing a .gltf/.glb model into a Three.js application?

After browsing through several related topics on SO, I'm still unable to find a solution to my current issue. The problem I'm facing is that the .glb model simply refuses to load. My Vue application utilizes webpack (specifically the Quasar frame ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

How can you simultaneously send FormData and String Data using JQuery AJAX?

Is there a way to upload both file and input string data using FormData()? For example, I have several hidden input values that also need to be included in the server request. html, <form action="image.php" method="post" enctype="multipart/form-data"& ...

Invoke a function in a different component following the completion of an asynchronous task in a React.js application

I am working with 2 components in my project. The first component contains a function that needs to be called after an async function in the second component completes. I am looking for a way to achieve something similar to Vue's this.$emit() function ...

Add information to the Database seamlessly without the need to refresh the page using PHP in combination with JQuery

Check out my code below: <form action='insert.php' method='post' id='myform'> <input type='hidden' name='tmdb_id'/> <button id='insert'>Insert</button> <p i ...