Converting all HTML classes into a PDF document for export

I am attempting to export an HTML element with the class .content into merged PDF pages. I am utilizing the pdfMake library, which can be found at this link: pdfMake

Within the body of the document, there are two elements with the class .content, styled as a4 dimensions..

.content {
    padding: 50px 0;
    width: 1000px;
    height: 842px;
}

I am attempting to export these elements to a PDF file.

UPDATED

function makePdf(){
    pages = document.querySelectorAll(".content")
    html2canvas(pages, {
        onrendered: function (canvas) {
            var data = canvas.toDataURL();
            var docDefinition = {
                content: [{
                    image: data,
                    width: 500
                }]
            };


            pdfMake.createPdf(docDefinition).download("document.pdf");
        }
    });
}

However, I have encountered an issue. I am unable to export the .content elements as merged PDF pages. Using html2canvas(pages, { exports 2 merged but empty pages.

When I attempted to troubleshoot by using html2canvas(pages[0], {, it successfully exported one PDF file without any issues. However, the second .content is omitted, as expected.

To address this, I tried implementing a forEach loop as shown below:

function makePdf(){
    pages = document.querySelectorAll(".content")
    pages.forEach(page => {
        html2canvas(page, {
            onrendered: function (canvas) {
                var data = canvas.toDataURL();
                var docDefinition = {
                    content: [{
                        image: data,
                        width: 500
                    }]
                };


                pdfMake.createPdf(docDefinition).download("table.pdf");
            }
        });
    })

}

Unfortunately, this approach exports individual PDFs for each .content element instead of merging them together.

I am slightly confused. How can I combine the .content elements into merged PDF pages?

Answer №1

const generatePdf = async () => {
    const pdfGenerator = new jsPDF("a4");
    let contentElements = document.querySelectorAll(".content")
    
    html2canvas(contentElements).then(canvas => {
        var imageWidth = pdfGenerator.internal.pageSize.getWidth();
        var imageHeight = pdfGenerator.internal.pageSize.getHeight();
        
        const contentDataURL = canvas.toDataURL('image/png');
        
        pdfGenerator.addImage(contentDataURL, 'PNG', 0, 0, imageWidth, imageHeight, '', 'FAST');
        pdfGenerator.save("generated_document.pdf"); // Generated PDF
    });
}

Answer №2

Despite the challenges I faced, I was able to overcome them and successfully solve the issue at hand. I ended up utilizing the jsPDF library instead of relying on pdfMake.

Custom Styles

.content {
    margin: auto;
    padding: 50px 0;
    width: 1000px;
    height: auto;
}

Javascript Function

function createPdf(){

    const pages = document.querySelectorAll(".content");
    let count = 0;
    
    pages.forEach(page => {
        html2canvas(page, {
            onrendered: function (canvas) {
                var data = canvas.toDataURL('image/png');
                var imgWidth = pdf.internal.pageSize.getWidth();
                pdf.addImage(data, 'PNG', '', '', imgWidth, 0);
                pdf.addPage(page);
                count++;
                
                if (count === pages.length) {
                    pdf.save("document.pdf");                        
                }
            }
        });
    });  
} 

Note: For better resolution when setting up PDF page size, consider avoiding the use of internal.pageSize.getHeight(); and simply give it a value of 0.

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

Sorting columns containing English, Japanese entries, and null values using a customized sorting algorithm in MUI Data Grid is a straightforward process

I am working with an MUI data grid and I am looking to implement a custom sorting algorithm for columns that can override the default options provided by MUI. The data in my fields is in English, Japanese, as well as empty/null values. My desired output sh ...

Looking to enforce limits on the values and character counts within input boxes with JavaScript

Having issues with my code for restricting input box entry to only numbers and limiting the characters per box to 3, 3, and 4 respectively. Despite my efforts, I can't prevent users from entering special characters or restrict the character limits as ...

Produced inputs and preset values

I have a question regarding the use of generated input elements in my App's form. I want to keep it as simple as possible, which is why I am using native form reset for these elements. It appears that the 'default value' becomes bound to th ...

The function for the Protractor promise is not defined

UPDATE: After some troubleshooting, I believe I have identified the issue causing it not to work. It seems that I am unable to pass arguments along when calling flow.execute(getSpendermeldung). Does anyone have a better solution than wrapping the ApiCall i ...

Can JavaScript trigger an alert based on a CSS value?

Hello, I am facing an issue. I have created a blue box using HTML/CSS and now I want to use JavaScript to display an alert with the name of the color when the box is clicked. Below is my code: var clr = document.getElementById("box").style.background ...

Adding an Icon to a Tab in Ant Design - A Step-by-Step Guide

Is there a way to include an icon before the title of each open tab? I am currently using the antd library for tab creation, which doesn't provide a direct option for adding icons. Here is my code snippet along with a link to the jsfiddle https://jsfi ...

Upgrading Xeditable button designs using AngularJS

Have a query. Can you replace the save(submit) button and cancel buttons with links in Xeditable for AngularJS? Appreciate your help ...

Successor in a JavaScript array with multiple dimensions

I am grappling with a complex nested multidimensional array that resembles the following structure in JSON format: [ { "Object": "Car", "Child": [ { "Object": "Toyota", "Child": [ ...

transforming a JavaScript array into an object

output: Array(5) [ "Samsung", "Iphone", "Nokia", "Xiomi", "Blackberry" ] another output: Array(5) [ Object { id: "Samsung", label: "Samsung" },Object { id: "Iphone", label: ...

Error encountered when attempting to add headers to a request, resulting in an HTTP status code

Encountering difficulties when making get requests to a server with headers set using Axios/http request. Adding any header (excluding the content-type header) triggers the same error: "Response for preflight has invalid HTTP status code 405." This issue p ...

Steps for assigning distinct identifiers to information entered through an input form

I have a question that I just can't seem to figure out: So, I have this input form: <form @submit.prevent="customSubmit"> <label>Name</label> <input type="text" v-model="newUser.name" id=&quo ...

SignalR is exclusively accessible within the active SILO environment

Currently, I am working on a real-time application using SignalR in combination with MVC and AngularJS (SILO). Each cshtml page serves as a Single Page Application (SPA), and within my AngularJS common service, I have incorporated generic operations such a ...

There are mistakes in the code that I am struggling to fix

I am encountering an issue where my website only functions properly on Firefox and not on Chrome. However, when I run the HTML using NetBeans on Chrome, the website works fine. I'm unsure of what to do as I need to submit this project within the next ...

Is Kendo Telerik grid capable of applying conditional formatting while filtering?

Is it feasible to modify the background color of rows in a Kendo Telerik grid when a filter is implemented within an ASP.NET MVC application? ...

Having trouble with the if/else statement in JavaScript? Check out the Odin Project's Rock, Paper, Scissors tutorial

I have been working on solving the Rock, Paper, and Scissors project, but I am struggling with constructing the if/else statement. Despite multiple attempts, I still can't seem to get the correct output when running the program. For instance, when I ...

Error Alert: jQuery Ajax Not Executing

Looking to send form data to PHP using jQuery. Check out the code below. -------------HTML FORM-------------- <div id="createQuestionBlock"> <form id="createQuestionForm" action="" method="POST"> Question Code: <input id="code" ...

Extracting information from JSON and presenting it in a structured table format

I've hit a wall with this JavaScript issue on my website. I'm trying to convert API JSON data into a table, and it's working fine when the data is on separate lines. However, when I introduce nested arrays in the JSON data, everything ends u ...

Can Facebox's settings be adjusted during runtime? If so, how can this be done?

Can Facebox settings be accessed and customized? For instance, I am interested in setting the location of the loading image dynamically as shown on line 4: <script type="text/javascript" src="<?php echo base_url(); ?>media/facebox/facebox.js" > ...

Developing Attributes in JSON

Greetings stackOverflow Community, I'm struggling a bit with creating JSON objects. I have code snippet that is meant to populate a list called members with names, and then add a property to each of those names. Here is the specific snippet in questi ...

Having trouble connecting a JavaScript file from my local directory to an HTML document. However, when I try to access it in the browser, I keep getting

Currently, I am attempting to connect a javascript file to my html document. Following the directions at this link, I am trying to enable the selection of multiple dates from a calendar as input in a form. The instructions mention that I need to include ...