Displaying all the contents of a div in a scrollable format on a PDF using html2canvas

I have a basic div with multiple paragraphs inside, each set to a specific height with vertical scrolling enabled. When I attempt to download the PDF file, only the visible portion of the div is being captured. However, I would like to include all the contents in the PDF. Below is the code snippet.

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js">
</script>
<div id="content">
      <p>This is the element you only want to capture</p>   
       <p>This is the element you only want to capture</p>  
        <p>This is the element you only want to capture</p> 
         <p>This is the element you only want to capture</p>    
          <p>This is the element you only want to capture</p>   
    </div>
    <button id="print">Download Pdf</button>
    <footer>This is the footer</footer>

Javascript

(document).ready(function() {
 $('#print').click(function() {

  var w = document.getElementById("content").offsetWidth;
  var h = document.getElementById("content").offsetHeight;
  html2canvas(document.getElementById("content"), {

    dpi: 300, // Set to 300 DPI
    scale: 3, // Adjusts your resolution
    onrendered: function(canvas) {
      var img = canvas.toDataURL("image/jpeg", 1);
      var doc = new jsPDF('L', 'px', [w, h]);
      doc.addImage(img, 'JPEG', 0, 0, w, h);
      doc.addPage();
      doc.save('sample-file.pdf');
    }
  });
});

});

CSS

body {
  background: beige;
}

header {
  background: red;
}

footer {
  background: blue;
}

#content {
  background: yellow;
  width: 70%;
  height: 100px;
  margin: 50px auto;
  border: 1px solid orange;
  padding: 20px;
  overflow-y:auto;
}
.html2canvas-container { width: 3000px !important; height: 3000px !important; }

Answer №1

Ensure the height is initially set to auto, then adjust it to your desired height once the image is generated. This way, you can capture the entire content seamlessly.

After obtaining the offsetWidth and offsetHeight, include this line:

document.getElementById("content").style.height="auto";
.

Following the completion of html2canvas, add this line:

document.getElementById("content").style.height="100px";
.

$(document).ready(function() {
     $('#print').click(function() {
     var currentPosition = document.getElementById("content").scrollTop;
      var w = document.getElementById("content").offsetWidth;
      var h = document.getElementById("content").offsetHeight;
     document.getElementById("content").style.height="auto";

      html2canvas(document.getElementById("content"), {

        dpi: 300, // Set to 300 DPI
        scale: 3, // Adjusts your resolution
        onrendered: function(canvas) {
          var img = canvas.toDataURL("image/jpeg", 1);
          var doc = new jsPDF('L', 'px', [w, h]); 
          doc.addImage(img, 'JPEG', 0, 0, w, h); 
          doc.addPage();
          doc.save('sample-file.pdf');
        }
      });
     document.getElementById("content").style.height="100px";
     document.getElementById("content").scrollTop = currentPosition;
    });

});

If the download doesn't work in the above snippet, you can test it out here

Update 1

Include a p tag on each page jsfiddle

Answer №2

Using the

context.scale(horizontalRescale,verticalRescale)
command allows you to reduce the size of all subsequent drawings by the percentage specified for horizontalRescale and verticalRescale.

If you want both the horizontalRescale and verticalRescale values to be the same, you can set them as follows:

var downscaleFactor= 0.70;

context.scale( downscaleFactor, downscaleFactor );

With this code snippet, the node will be reduced to 70% of its original size.

I trust that this information addresses your query satisfactorily.

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

The CSS styles are not being rendered on the page

My simple static html/css project seems to be having trouble applying styles to the html elements in stackblitz. You can view the project here. I'm wondering if there might be an issue with linking the css file using the link tag, or perhaps it's ...

One method to add a hashtag before a variable in the HTML attribute value data-bs-target

Basically, I have set up a vue web application with a container containing multiple bootstrap cards. Each card has a button that is supposed to collapse a form for guests to apply. However, the issue arises when I click on the button of one card, as it col ...

Using Python Selenium to create a login page with Javascript

Attempting to access a page using Python selenium package for certain activities is proving challenging. Despite the following code being written, an error message of "the Class is not found" keeps appearing. To proceed with using send_keys(), it's ne ...

Encountering Timeout Issues with Reading Streams on Amazon S3 using Express.js

I am currently facing an issue with streaming videos from an Amazon S3 Bucket. It seems that everything works perfectly when calling my REST endpoint once, but the problem arises when trying to stream the video simultaneously from multiple browsers. The er ...

What sets apart the process of installing AngularJS and AngularJS Core using NuGet?

I am curious about the difference between these two packages in my packages.config file. Would it be advisable to uninstall one of them? <?xml version="1.0" encoding="utf-8"?> <packages> <package id="angularjs" version="1.3.15" targetFr ...

There seems to be a problem with how the navbar is being displayed in ResponsiveSlides.js

I am currently using WordPress, but I have come here seeking help with a jQuery/CSS issue. I am utilizing responsiveSlides.js to create a simple slideshow, however, when viewing it here at gallery link, it appears that something is not quite right. STEPS: ...

JavaScript class name modifications are not functioning as expected

Testing a sprite sheet on a small web page I created. The code for each sprite in sprites.css is structured like this... .a320_0 { top: 0px; left: 0px; width: 60px; height: 64px; background: url("images/sprites.png") no-repeat -787 ...

Using GSAP to create a staggered animation with a negative delay

Seeking a Solution: I am curious if there is a method to incorporate a negative delay into the staggerFrom / staggerTo functions within greensock? Issue at Hand: The current animation I have in place is extending longer than desired. It would be benefic ...

Utilizing ng-class in AngularJS based on the specific html elements

I am displaying each item from my array as an HTML paragraph using the ng-repeat directive. <p ng-repeat="item in queries track by $index">{{ item }}</p> The output looks like this: ------------ title 1 -------------- content 1 ------------ ...

A guide on utilizing handlebars to display a JSON Array

I'm currently using Handlebars.js to display a repeating UI component... <div class="container-fluid article-container"> {{#each this}} <h1>{{header}}</h1> <h1>{{url}}</h1> <h1>{{body}}& ...

Using JavaScript to iterate over two arrays and merge them into a single object

I have an object that contains three arrays, and I want to map over all of them at once. Here's how I'm currently doing it: const containerNames = this.state.fileContent.xContainers.map(xContainer => <Container containerName={xContainer} ...

Incorporate hyperlinks to the right side of the footer section

I want to expand the footer by adding 3 more links to the right side of the logo. These new links should float to the right and always be positioned about 100px from the right edge of the web browser. Check out my JSFiddle for reference: In my attempt at ...

Chrome and Safari disregarding navbar height dimensions

Recently, I encountered an unexpected issue in a local project that I've been working on. Two weeks ago, everything appeared correctly, but now Chrome and Safari are ignoring the height of the navbar. Surprisingly, Firefox is displaying it correctly, ...

Tips for verifying the accuracy of a user's input in a quiz

How can I validate a user's input in a quiz scenario? Imagine a quiz where users have to guess the origin of a food item based on an image displayed. If the first picture is from Turkey, followed by Greece, India, and Mongolia, how can I verify if th ...

Best Practices for HTML and CSS Coding

We have decided to hire an outside consultant to create XHTML (Transitional) and CSS for the key pages of our new project. In order to ensure a certain level of quality, I am putting together a set of guidelines for them to follow. The HTML they provide wi ...

The min() function within the withStyles method

How can min() be used in withStyles? Currently declared as: maxWidth: "min(700, 90vw)" Tried this as well: maxWidth: "min('700', '90vw')" Neither of these solutions are working. Has anyone successfully utilized this feature with ma ...

Utilizing arrow keys as a means of setting focus (HTML & JavaScript)

Is it possible to program the left arrow key to function like the tab button (moving focus to the next focusable item) and the right arrow key to function as a shift+tab (moving focus to the previous focusable item)? I've made some progress with the ...

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

Tips for continuing a count from where it left off

I have encountered an issue with the input fields in my form. I used the counter method to add input fields and saved the form. However, when I try to add more fields, the counter starts from 0 again. For example, I initially added 5 input fields with mod ...

Utilizing Ajax to selectively choose a radio button by its ID within an ASP.Net MVC framework

How can I check a radio button by id instead of value? Currently, I am dynamically populating a table using ajax and need to automatically select the radio button with a 'Y' default flag. This is the current code I have that checks the radiobutt ...