Converting HTML to PDF using JavaScript

My goal is to create an HTML page and then print and download it locally as a PDF. However, when I try to generate the PDF, it cuts off the last 3 to 4 lines of the page. I want to create multiple PDF pages in A4 size with the same styling as the HTML page.

(function () {
    var
     form = $('#formpdf, #logo'),
     cache_width = form.width(),
     a3 = [842, 1500]; // for A4 size paper width and height

    $('#create_pdf').on('click', function () {
        $('body').scrollTop(0);
        createPDF();
    });
    //create pdf
    function createPDF() {
        getCanvas().then(function (canvas) {
            var
             img = canvas.toDataURL("image/png"),
             doc = new jsPDF({
                 unit: 'px',
                 format: 'a3'
             });
            doc.addImage(img, 'JPEG', 10, 10);
            doc.save('Texas_Transportation.pdf');
            form.width(cache_width);

        });
    }

    // create canvas object
    function getCanvas() {
        form.width(a3[0]*1.3333-80).css('max-width', 'none');
        return html2canvas(form, {
            imageTimeout: 2000,
            removeContainer: false

        });
    }

}());

(function ($) {
    $.fn.html2canvas = function (options) {
        var date = new Date(),
        $message = null,
        timeoutTimer = false,
        timer = date.getTime();
        html2canvas.logging = options && options.logging;
        html2canvas.Preload(this[0], $.extend({
            complete: function (images) {
                var queue = html2canvas.Parse(this[0], images, options),
                $canvas = $(html2canvas.Renderer(queue, options)),
                finishTime = new Date();

                $canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);
                $canvas.siblings().toggle();

                $(window).click(function () {
                    if (!$canvas.is(':visible')) {
                        $canvas.toggle().siblings().toggle();
                        throwMessage("Canvas Render visible");
                    } else {
                        $canvas.siblings().toggle();
                        $canvas.toggle();
                        throwMessage("Canvas Render hidden");
                    }
                });
                throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);
            }
        }, options));

        function throwMessage(msg, duration) {
            window.clearTimeout(timeoutTimer);
            timeoutTimer = window.setTimeout(function () {
                $message.fadeOut(function () {
                    $message.remove();
                });
            }, duration || 2000);
            if ($message)
                $message.remove();
            $message = $('<div ></div>').html(msg).css({
                margin: 0,
                padding: 10,
                background: "#000",
                opacity: 0.7,
                position: "fixed",
                top: 10,
                right: 10,
                fontFamily: 'Tahoma',
                color: '#fff',
                fontSize: 10,
                borderRadius: 10,
                width: 'auto',
                height: 'auto',
                textAlign: 'center',
                textDecoration: 'none',


            }).hide().fadeIn().appendTo('body');
        }
    };
})(jQuery);

Answer №1

  • Convert your HTML content into a PDF by utilizing htmltocanvas for taking a screenshot.

Here's an example of how to use it:-

HTML

<div id="capture" style="padding: 10px; background: #f5da55">
    <h4 style="color: #000; ">Hello world!</h4>
</div>

Javascript

html2canvas(document.querySelector("#capture")).then(canvas => {
    document.body.appendChild(canvas)
});

Install the library by running npm install --save html2canvas.

  • Consider using third-party libraries like jsPDF or pdfmake, which are open source and offer an API for generating PDFs from HTML content.

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

What is preventing me from setting the maxwidth in Android WebView during onLayout?

I am attempting to customize the onLayout function of a WebView in order to limit the size of large images to fit within the screen size. Within my extended WebView, I have tried the following code: @Override protected void onLayout(boolean changed, i ...

Sorting tables in jQuery using a plugin

I discovered a jquery plugin that can be found at: Initially, I was successful in implementing it on a static table. However, my current challenge involves trying to make it work with a table populated from a database using ajax calls. I have included the ...

Can someone explain why my Laravel route is consistently showing a 404 error?

Currently, I am attempting to perform an AJAX request for a form post type. However, the PHP parse script I am trying to send the data to is returning a 404 error as observed through Chrome developer tools. Below is the code snippet: <script type="text ...

Listen for an event on a button to show a specific div

Looking to have a div appear when the user clicks on a button. //html-code <div class="col-md-4"> <h4 class="service-heading">Social Media</h4> <p class="text-muted">This is the first line of text.</p& ...

What is the process of encrypting a password using AngularJS on the client side, transferring it securely to the server through ExpressJS, and then decrypting it on the server

Looking for a simple method to encrypt a password on the client side using angular.js, send it to the server with express.js, and then decrypt it? While there are libraries like angular-bcrypt and similar ones in nodeJS, they may not be suitable as they ma ...

Prevent Dehydration issue while using context values in Next Js

Every time I log in with a user, update a context value, and re-render some components, I keep encountering a Hydration error in Next Js. The issue seems to be specifically with my NavBar component which is rendered using react-bootstrap. The code snippet ...

Creating the document.ready function in Angular2 with JQuery

I am seeking assistance to modify the JQuery function so that it can run without the requirement of a button click. Currently, the function only executes when a button is clicked. Code declare var jQuery: any; @Component({ selector: 'home-component ...

Creating a dynamic visual effect with image overlap in the Sencha Touch carousel

I've created a carousel that loads multiple images, but I'm experiencing an issue where each image is overlapping with another image from a different card. Here's a visual of the problem: As shown in the screenshot, parts of one image are a ...

the quickest method to apply font-weight:bold; to the text within the component

Is there a way to apply font-weight: bold; only to the inner content of a component in a scss file while avoiding affecting the component tag itself? :host { font-weight: bold; } Although this code works, it also affects the component tag itself. What ...

Retrieve the border color using Selenium WebDriver

Hey everyone, I'm currently trying to retrieve the border color of an extjs 4.2 form control text field using the getCssValue method. However, I'm having trouble getting the value as it's coming back blank. Below is a sample of my code that ...

Aligning content with CSS styling

I am facing a challenge with aligning buttons in three different td tags, as the text content within each varies. I want the buttons to line up evenly regardless of the amount of text present. Is there a solution that does not involve setting a fixed parag ...

I am having trouble with my append function even though I checked the console log and did not see any errors (beginner's inquiry)

As I practice working with functions and dynamically creating input fields, I have encountered an issue where I am unable to append my input field to the form. Despite using console.log() and not seeing any errors, I can't figure out what mistake I ma ...

Some pages are compatible with JS while others are not... Although, the file can be found in the page source

I have limited knowledge in javascript, so I often find myself copy-pasting code. Currently, I am working on a website that includes a navigation sidebar. I have implemented a script to toggle a class that sets the display property to none. $(document).rea ...

Customizing the page length menu select box in jQuery dataTables: A step-by-step guide

Can we swap out the default datatables select box (page length menu) for a bootstrap-style select? At present, datatables displays a standard select box with various length options that we set in the aLengthMenu option. I am looking to upgrade it to a mor ...

Transferring information between two separate components

Hey there, I'm struggling with the Payment Component. What I want to achieve is that when I click on a link, it transfers (ClassG, imageG, and PriceG) to the Payment Component where I can then style them accordingly. I've attempted something, but ...

Is AngularJS the right choice for creating components?

Currently, I am developing a PHP web application with approximately 200 unique views. Most of these views simply display tables or forms. However, there are about 10 pages where users could benefit from dynamic/async components to prevent constant page re ...

Is it possible to iterate over a non-reactive array in a Vue template without having to store it in a data property or computed property?

Presented below is a static array data: const colors = ["Red", "Blue", "Green"]; To display these values in my markup, I can use the following method in React: import React from "react"; // Static array of colors const colors = ["Red", "Blue", "Green"] ...

What are the steps to changing the navbar's color when scrolling down?

I am having trouble changing the color of my navigation bar from transparent to black after the user scrolls down. Despite trying various methods and watching tutorials, I can't seem to get it to work. HTML <nav role='navigation' class= ...

Does creating a form render the "action" attribute insignificant in an AJAX environment?

When submitting forms exclusively through AJAX, is there any advantage to setting the action attribute at all? I have yet to come across any AJAX-form guides suggesting that it can be left out, but I fail to see the purpose of including it, so I wanted t ...

Effective ways to sort material cards in Angular

Can someone guide me on how to implement a search bar in my Angular application to filter cards by name? Here is the link to my Stackblitz project for reference: https://stackblitz.com/edit/stackoverflowcom-a-60857864-6433166-dpaump Below is a snippet fro ...