Is there a way to transform an HTML canvas into a tangible photograph?

I am currently working on converting HTML content into a real image on the client's side. After conducting research on canvas2base64, canvas2base64, and html2base64 on Stack Overflow, I have found that the generated images are always based on base64 code rather than a real picture.

While the quality of the generated image is satisfactory, I am facing an issue when trying to insert it into a PDF using jsPDF as it does not support base64 images.

My current setup includes using jquery.js, jspdf.js, html2canvas.js, and FileSaver.js.

I am looking for a solution to generate a genuine image in formats such as .png or .jpg from a canvas without relying on base64 code. Ideally, I would like to save this image in the user's localStorage for easy reference and use in my code.

The following code aims to generate an image and insert it into a PDF with the dimensions of a DIN A4 sheet:

function print() {
//const filename  = 'Loveletter_.pdf';

html2canvas(document.querySelector('.finishedLetter')).then(function(canvas) {
var pdf = new jsPDF('p', 'mm', 'a4');
$("#test_me").attr("src", canvas.toDataURL("image/png", 1.0));
var ImgForPDF = document.getElementById('test_me').getAttribute('src');
pdf.addImage(ImgForPDF, 'PNG', 0, 0, 211, 298);
});
pdf.save('Loveletter_.pdf');
}

Answer №1

Thank you for the confirmation. I recommend you try the following method to create a printable PDF file without affecting your css properties:

function print() {


// Utilizing HTML2Canvas to generate PDF
  html2canvas(document.body,{
    useCORS: true, 
    onrendered:function(canvas){
      var img=canvas.toDataURL("image/png");
      var imgData = canvas.toDataURL('image/png');
      var imgWidth = 210;
      var pageHeight = 295;
      var imgHeight = canvas.height * imgWidth / canvas.width;
      var heightLeft = imgHeight;

      var doc = new jsPDF('p', 'mm');
      var position = 0;

      doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }
      doc.save('myDoc.pdf');
    }
  });

}

Answer №2

It's great to hear that the solution is working well for you. Don't forget to up-vote the answer that helped resolve your issues. If you're looking to capture only specific div elements in your PDF, you can follow this technique:

 $(document).on('click', '#download_button', function(){

  // Adjusting settings before generating the PDF
  $('header').hide();
  $('footer').hide();

  // Using HTML2Canvas to create the PDF

  html2canvas(document.body,{
   //Insert your code here
  });

  // Restoring properties to their original state after PDF generation
  $('header').show();
  $('footer').show();

});

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

PHP Loop creating additional space in recurring section

I'm facing a perplexing issue that I can't seem to figure out. When I use the code provided below, it creates an extra blank row on my webpage. Interestingly, this code works perfectly fine on other pages without any issues. Although I have set t ...

Browser freezes unexpectedly every 10-15 minutes

I have an application that displays 10 charts using dygraphs to monitor data. The charts are updated by sending ajax requests to 4 different servlets every 5 seconds. However, after approximately 10-15 minutes, my browser crashes with the "aw! snap" messag ...

Mongoose - Mastering the Art of Executing Multiple Update Statements in a Single Operation

In the MongoDB documentation, I found out that you can execute multiple update statements in a single command. How can this be accomplished with Node.js and Mongoose? db.runCommand({ update: <collection>, updates: [ { q: <q ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

What is the quickest method for cycling through the most ancient elements in a collection? (Efficient way to execute a queue)

See edit too I'm currently working in JavaScript, but I believe any readable pseudocode may be able to help answer my question. Describing my issue might be a bit of a challenge, so feel free to ask for clarifications. I'll respond promptly and ...

Steps for retrieving the currently selected text inside a scrolled DIV

An imperfect DIV with text that requires a scroll bar For example: <div id="text" style='overflow:scroll;width:200px;height:200px'> <div style='font-size:64px;'>BIG TEXT</div> Lorem Ipsum is simply dummy text of th ...

Comparing UI Animations in Jquery and AngularJS

Currently working on a web application with AngularJS, I've noticed the absence of UI animations. The dilemma arises whether to utilize jQuery or stick to AngularJS for crafting these animations. While AngularJS provides the ngAnimate directive and t ...

How come when you add ({}+{}) it equals to "[object Object][object Object]"?

I ran the following code: {}+{} = NaN; ({}+{}) = "[object Object][object Object]"; What is the reason behind the difference in result when adding ()? ...

Prevent scrollbar from appearing while splash page loads

Looking for help with a script to create a splash/intro page loader. $(function(){ setTimeout(function() { $('#splash').fadeOut(500); }, 6000); }); The current script hides the intro page after 6 seconds, ...

Tips for updating existing data with Angular JS?

I'm looking to edit a posted JSON data form record by clicking a button, but I'm having trouble populating the form with the old data for editing. <button style="margin:3px;" ng-click="put1(student)" onclick="opendiv();">Edit</button> ...

Encountering the error message "Cannot GET /" in a NodeJS Express

I've been experimenting with various approaches to resolve this issue, ranging from app.use(express.static(__dirname + "public")) to res.render. It seems to function correctly in my terminal environment but fails when I try to access it locally. Can a ...

Sinon - using callbacks in stubbed functions leading to test method exceeding time limit

One of my express route methods is structured as follows: exports.register_post = function(req, res) { var account = new Account(); account.firstName = req.param('firstName'); //etc... account.save(function(err, result) { ...

I am having trouble setting breakpoints in Google Chrome

For a while, I've been using Google Chrome to debug my JavaScript code without any issues. However, out of nowhere, I am no longer able to place breakpoints. When I click on the line number where I used to add breakpoints, nothing happens. Sometimes, ...

Ways to conceal a div in React when the input or child is not in focus

My custom search and select component includes an input field and a results list enclosed in a wrapper container: <div className='wrapper'> <input /> <div className='results'> <div>Result Item</div> ...

Create an HTML div element that spans the full width of the

I'm facing an issue on my HTML page where a div containing users from a chat system database is not displaying correctly. The ul li tag within the parent div is not taking up the full width as expected. Here's how it should look: http://prntscr.c ...

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...

Fluctuating price depending on the selected choice

Hello, I am in the process of updating the price based on the selection made from the options. I am unsure whether to use JavaScript or Ajax for this task and how to go about it. Can someone please guide me? <tr> <td width="160">Price:</td ...

How to horizontally align Material-UI elements in ReactJS

My goal is to create a user-friendly form where respondents can input answers to questions and select one as the preferred option by using a radio button. However, I'm facing an issue where Material-UI displays each element on its own line. This is t ...

Logic for iterating through blocks in JavaScript

I have a code that consists of an array containing multiple objects, in this case URLs. I am currently using a loop to iterate through this array and send a request for each URL. However, I am looking for a way to optimize this process by breaking it dow ...

The appearance of the drop-down menu in IE is not the same as in other

I have implemented css bootstrap 3.2.0 on my website. However, I have noticed some discrepancies when viewing the site in Internet Explorer. The menu options have a thick black border and the dropdown menu button appears different compared to other browse ...