How can I edit this code in JSPDF to print two pages instead of just one?

Currently, I have a script that can generate a PDF from one DIV, but now I need to create a two-page PDF from two separate DIVs.

How can I modify the existing code to achieve this?

The first DIV is identified as #pdf-one and the second DIV is #pdf-two.

public exportHtmlToPDF() {
    let dataOne = document.getElementById('pdf-one')!;
    let dataTwo = document.getElementById('pdf-two')!;

    html2canvas(dataOne).then(canvasOne => {

        html2canvas(dataTwo).then(canvasTwo => {

            let docWidth = 208;
            let docHeight = canvasOne.height * docWidth / canvasOne.width;
            let position = 0;

            const contentDataURLOne = canvasOne.toDataURL("image/jpeg", 1.0);
            const contentDataURLTwo = canvasTwo.toDataURL("image/jpeg", 1.0);

            let doc = new jsPDF('p', 'mm', 'a4');

            doc.addImage(contentDataURLOne, 'JPG', 0, position, docWidth, docHeight, 'FAST');
            doc.addPage();
            
            position = docHeight;

            let docHeightTwo = canvasTwo.height * docWidth / canvasTwo.width;
            doc.addImage(contentDataURLTwo, 'JPG', 0, position, docWidth, docHeightTwo, 'FAST');

            doc.save('two-pages.pdf');
    
        });
    });
}

Answer №1

Consider utilizing the break-after property on your initial div element, as shown below:

#pdf-one {
    break-after: always; 
}

For more detailed information about break-after, you can visit here

It is important to ensure that the height of your div matches the height of the PDF page.

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

Toggle textboxes using jQuery depending on the radio button choice

I'm trying to make specific textboxes appear when a particular radio button is clicked on my form, but I want them to remain hidden otherwise. Here's an example of what I've implemented: HTML: Radio buttons: <p>Show textboxes<inpu ...

React - group several elements within a wrapping container

I am dealing with an array of words that make up sentences: let words = [ { "start_time": "2.54", "end_time": "3.28", "alternatives": [ { "confidence": "1.0", ...

Tips for determining the time and space complexity of this JavaScript code

Here are two codes utilized by my platform to establish relationships between nodes. code1 : const getNodeRelationship = (node1, node2) => { // if node1 and node2 are the same node if (node1 === node2) return null; // check direct parent ...

A guide to accessing the currently hovered element on a Line Chart with Recharts

Just diving into this community and also new to ReactJS :( https://i.stack.imgur.com/k682Z.png I'm looking to create a tooltip that displays data only when hovering over the value 1 line. Unfortunately, the current tooltip is not behaving as expecte ...

Connecting with Node JS, utilising the power of Socket.IO, Express, and establishing

Hey everyone, I have an interesting concept that I'd like to discuss with you to get your thoughts on its feasibility. The idea is to set up an RFID reader connected to a MacMini (with the Mini hidden and only the RFID visible). An iPad would also be ...

Achieving dynamic HTML element addition through JavaScript while maintaining their record in PHP

There is an input box where the user specifies the number of new DIV elements to be added dynamically. This request is then sent to PHP via Ajax, where it prepares an HTML DIV with some inner input tags. Each DIV has a unique id attribute generated increme ...

Structuring files with AJAX, PHP, Javascript, and HTML

Explaining my dilemma in detail might be a bit abstract, but I'll try to do my best. In one of my PHP files, I have HTML code that includes text boxes and a submit button. This file serves as the main page and is named mainHTML.php The text boxes ar ...

Encountering a JavaScript runtime error while trying to access and interpret JSON

Currently, I'm facing a challenge with converting a C# list of string types into a JSON object. The issue arises when trying to read this JSON object later in JavaScript. On the other hand, the process seems to work fine when dealing with a C# list of ...

Is there a way to convert datetime format to date in a Vue component?

With my Vue component set up like this: <template> ... <td>{{getDate(item.created_at)}}</td> ... </template> <script> export default { ... methods: { getDate(datetime) { ...

Improve the efficiency of the function for retrieving data from a lengthy string and organizing it into key-value pairs within an object

I am dealing with a string extracted from a text file, which is structured in the following way on each line. 1=abc|2=TsMarketDataCache|3=1|4=141061|6=2023-02-27T05:04:50.472|36=F|7=1584A Format: key1=value1|key2=value2|key3=value3|key4=value4...|keyN=va ...

Pass the output of one function as an argument to another function in a Node.js Express application

I'm having trouble retrieving the value declared in the first function CreateTag and using it as a variable in the second function CreateStream. Despite working with nodejs Express, I've attempted to use RETURN without success. I've tried v ...

Retrieve the value of EJS depending on the JavaScript variable

I am in the process of developing a website for booking appointments using Express, EJS, and MongoDB. When a request is made to '/booking', the book page appears displaying all details about the doctor. Upon clicking the book button next to each ...

JQuery function fails to execute upon first page load

I am currently facing a situation where I need to wait for a specific image to load before either swapping out its src or showing/hiding the next image. The desired outcome is to display a placeholder image (silhouette) until the main image loads, then hi ...

Utilizing ElementRef in Angular 4 to close dropdown when clicking outside of it

I recently came across this helpful tutorial, but I'm having trouble grasping how it actually functions. Here's the code snippet I've incorporated into my TypeScript file: @Component({ host: { '(document:click)': 'onOuts ...

Dealing with an empty req.body in an Express.js POST request

Having trouble solving this issue with a simple search. Can anyone provide clearer guidance? In the client-side code, I attempted to attach an object using xhr.send(obj). Currently, I'm trying to append to the formData object, but the result remains ...

Assign a value to a hash object based on a specific location stored within an array

I'm struggling to figure out how to retrieve the original JSON data when its structure is variable. var jsonData = { "parent": { "child": "foo" } }; fu ...

Incorporating additional value attributes without replacing the existing ones

Is there a way to add a value attribute through jQuery without removing the old attribute, similar to how addClass works? I have 7 input fields that are being typed in, and I need to combine them into one word and pass it to another input field. When I try ...

Tips for consolidating all functions into a single file for ReactJS inheritance:

I'm curious about something. In Angular JS, we have the ability to create a global service file that can be inherited by every component. This allows us to use the functions written in the global service file within each respective component. Is ther ...

`Passing JavaScript variables through HTML anchor tags`

I am currently attempting to pass the id to the controller using this method: {{ route("admin.service.edit", '+val[0]+' )}} However, the '+val[0]+' is being interpreted as a string in the URL http://localhost:8000/admin/servi ...

Improving Javascript Arrays for Easier Reading

A dataset has been organized into a table format as shown below: +------+---------+----+----+----+----+-------+----------+ | Year | Subject | A | B | C | F | Total | PassRate | +------+---------+----+----+----+----+-------+----------+ | 2015 | Maths ...