Converting jQuery elements into PDF format

I have encountered an issue with a custom Js script that I developed. The purpose of this script is to style a specific div in HTML using CSS.

Currently, the script is functional and performing its intended task. However, it is not behaving exactly as desired. At present, it only displays content visible on the user's screen and excludes any content above or below that is not currently within view. This can be problematic when dealing with HTML documents containing a significant amount of content.

Additionally, the script is rendering white backgrounds as black for reasons unknown.

Sample Code

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

    var w = document.getElementById("content").offsetWidth;
    var h = document.getElementById("content").offsetHeight;
    html2canvas(document.getElementById("content"), {
      dpi: 300,
      scale: 3,
      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.save('sample-file.pdf');
      }
    });
  });
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;
  }

Edit

I have found a temporary solution to the issues I was facing but am still exploring ways to improve the quality and eliminate unnecessary white space from the document.

Here is the current state of the Js snippet:

    function getPDF() {

            var HTML_Width = $(".canvas_div_pdf").width();
            var HTML_Height = $(".canvas_div_pdf").height();
            var top_left_margin = 15;
            var PDF_Width = HTML_Width + (top_left_margin * 2);
            var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
            var canvas_image_width = HTML_Width;
            var canvas_image_height = HTML_Height;

            var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

            //more code for creating PDF

        };

If you wish to use the functionality above, simply add onclick='getpdf()' to your button.

To address the issue of black rendering, ensure you assign an ID or class to the targeted div and set a CSS Background color of #ffffff.

Any assistance would be greatly appreciated.

Kind Regards, Faz.

Answer №1

One issue that arose was due to the unit setting being in pixels (px) while jsPDF was converting units to points. The main document should always be in points (pt), and when providing image dimensions using pixels, jsPDF automatically converts them to points. Changing the unit to points captures the entire image.

I have some recommendations regarding your code:

  1. You are using an outdated version of html2canvas (version 0.4.1 while the latest is 1.0.0-rc.5). I found success with version 1.0.0-rc.1.
  2. Instead of passing an image URI to jsPDF, you can directly pass the canvas element.

If your end goal is a resume, it's usually letter-sized. It's advisable to design the content using units like pt, em, rem, and in. Remember to convert inches to 72dpi rather than the default 96dpi.

Check out this sandbox demonstrating the use of to instead of px: https://codesandbox.io/s/zen-blackburn-y093n

Here's an example I created showcasing how to create a simple resume and download it as a PDF: https://codesandbox.io/s/laughing-austin-rzlc9

I hope this information proves useful.

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

Navbar brand in Bootstrap 4 not centered when navbar is collapsed

I am currently working on aligning the brand-item and nav-items on mobile view. The alignment is incorrect in the mobile view. It is not centered. The "Brand" should be vertically aligned with "link1-3". In the desktop view, the alignment should be like ...

Utilizing Angular's ngShow and ngHide directives to hide spinner when no data is retrieved

I'm having an issue with the HTML code below. It currently displays a spinner until a list of tags is loaded for an application. However, the spinner continues even if no events exist. I want to make the spinner disappear and show either a blank inpu ...

How can a Vue.js toggle button dynamically change based on the combined state of two checkboxes?

My current project involves implementing a toggle feature that allows users to enable a day and then select between AM or PM using checkboxes. One issue I'm facing is how to de-toggle the button if a user unchecks both AM and PM options. Check out t ...

Is it possible for the editor to detect and recognize the hyperlink?

I am working on a project that involves using an html editor such as freetextbox or ckeditor. My question is, is it possible for the editor to recognize a link after it has been pasted into the editor? For example, if I copy and paste the following link: ...

How can we ensure successful validation using Jquery?

I'm currently working on a basic form that includes text fields. Whenever these text fields are modified, an Ajax function is called to save the changes. However, I am facing a challenge in validating these fields using jQuery before the change even ...

Background image not visible on Firefox and Chrome when using a DIV element

I'm encountering an odd issue where my DIV background isn't showing up in Firefox and Chrome, but it looks fine in IE. I've searched on several places like Stackoverflow for solutions to this problem, but none of them have worked for me so f ...

Stop the initial expansion of the first accordion with JavaScript on page load

I have a simple accordion created using only pure javascript without jQuery and Pure CSS. Everything is functioning correctly, but the problem I am facing is that the first accordion is automatically expanded when the page loads. I have tried various metho ...

Tips on detecting a collision between a cube mesh and the boundaries of a browser using ThreeJS

I'm a beginner in 3D games and ThreeJS. In the image above, my Mesh is located at the left boundary of the browser with a position of -1035 instead of 0. This leads me to question what exactly is the relationship between mesh.position.x in ThreeJS and ...

How can I format the URL in an AJAX request to send a POST method and receive a RESPONSE ENTITY?

After researching tutorials on Spring for the POST method and inserting data with ResponseEntity, I encountered an error in AJAX. I need clarification on the correct URL format from AJAX to Java. Here is my assumption: localhost:8080/name-project/insert?i ...

Refresh the Kendo Auto Complete feature within a grid whenever the grid page is changed

Incorporating a kendo auto complete into the filter feature of a grid column has presented a challenge for me. I am looking to have the auto complete update based on the current page number and size whenever the page changes. Despite exploring different s ...

Unusual data entries within Datalist Input 'Gas' and 'gas'

When setting the name or id of an Input with a list like 'cia', two strange selectable values appear at the bottom: Gas and gas. Any thoughts on why this might be happening? <input list="browsers" id="cia"> <datalist id="browsers"> & ...

The compatibility of JQuery MVC with Internet Explorer

Sheesh, folks, I've got a real head-scratcher of an issue on my hands. Running my webapp in Firefox has been smooth sailing, but now my client wants to use Internet Explorer. Simply telling them to switch browsers is not a viable solution for me, so I ...

The data passed by Ajax Json is correct, however the method is receiving an object with empty properties

I encountered an issue with an Ajax call where a list of objects is sent to a method within the controller. The JSON data appears to be correct when sent, but upon reaching the controller, the list contains objects with all properties set to null, despite ...

Issue with displaying Vue.js page within iframe in Firefox

We are facing an issue where a Vue.js page with an Echarts pie chart is not displaying in Firefox, even though it shows up perfectly in Chrome and IE. Replacing the Echarts page with basic numbers did not solve the problem in Firefox. Here is how i ...

Using jQuery to focus on the selected element after a change event

What is the best way to focus after jQuery plugin chosen has been activated? I attempted to use this code, but it did not have the desired effect: HTML: <select id="producer_id"> <option value="a">A</option> <option value="b ...

Design an HTML table with each row represented by a form element

I'm attempting to design a table where each row serves as a form. I would like each input to be in a separate table division, but I also need all the first inputs to belong to the same table header, and so forth. My goal is to create an editable grid ...

Utilize CSS to create a column layout

I have some HTML output that I would like to style using CSS, but unfortunately I have no control over how the HTML is generated and cannot make any changes to it. Right now, I have a two-column layout set up here: http://jsfiddle.net/uvg6f3tr/ I'm ...

Employing Bootstraps data-spy and data-toggle features with a button

Is it possible for a button to not only toggle a hidden accordion but also scroll the page to that section? Currently, my code is working great with navigation, but I'm struggling to make the button display text and scroll to the top of the section. ...

Issue with passing values through radio buttons in a form

Can anyone explain why a small form with a radio button group is not passing any value to a php processing page? I have shared the code on Pastebin at the following link: http://pastebin.com/GT5HDpuc. Any help in identifying the issue would be greatly appr ...

What is the process for removing selected columns while simultaneously transmitting the selected radio button value?

Currently, I have a PHP code snippet that needs to handle deleting rows from a database based on whether a "delete checkbox" has been checked. Additionally, I need to update a "verify" column in the database with a value of 1 or 0. However, I am struggling ...