How to cleanly print HTML pages with the use of page breaks

Having trouble with creating a table and printing the data in a specific structure. The format should be:

Title Data Sum

The challenge is to ensure that the title does not end up at the bottom of the page, and the sum does not start at the top of the page when printed. To overcome this issue, I tried using HTML tables with Divs and set sizes in millimeters. However, I ran into problems calculating when the page breaks because the height varies on different computers.

Below is the JavaScript code I used for calculation and handling page breaks:

$(document).ready(function(){
        var mydiv ='<div class="page-break"></div>';
        var i=0;
        var h = px2cm($("#myinfo").last().height())*10;
        var limit=297;
        var g =0;

        $('#content div.ptr').each(function(){
            g=0;
            h = h + px2cm($(this).height())*10;
            var nexth=px2cm($(this).next().height())*10;
            if(h>=limit-nexth)
            {               
                if($(this).hasClass("ptrtitle")){
                    $(this).before(mydiv);
                    h = px2cm($(this).height())*10;
                    i++;
                    g=1;
                }else{                  
                    if(String($(this).next().attr("class"))==="ptr ptrsum"){
                        if($(this).prev().hasClass("ptrtitle"))
                        {
                            $(this).prev().before(mydiv);
                            h = px2cm($(this).height()+$(this).prev().height())*10;
                        }else{
                            $(this).before(mydiv);
                            h = px2cm($(this).height())*10;
                        }
                        //h=0;
                        i++;
                        g=1;
                    }else{
                            $(this).after(mydiv);
                            h=0;i++;
                    }
                }
            }
        });
    });
    function px2cm(px) {
      var d = $("<div/>").css({ position: 'absolute', top : '-1000cm', left : '-1000cm', height : '1000cm', width : '1000cm' }).appendTo('body');
      var px_per_cm = d.height() / 1000;
      d.remove();
      return px / px_per_cm;
    }

Setting limit=297 (for A4 height) works correctly on some computers but not all. On certain devices, it prints 40 rows on one page while on others, some rows spill over to the next printed page.

Any suggestions on how I can improve the consistency of printing across all computers?

Answer №1

To simplify your page breaks, consider implementing the CSS2 property page-break within your page-break class using @media print instead of manually calculating the breaks. You can also adjust the scale specifically for printing if necessary.

@media print {
    .page-break {page-break-after: always;}
}

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

Locate the hyperlink within a div using JavaScript and navigate to it

I stumbled upon an element (div1) and now I am looking for a link within that element (link) so that I can navigate to it. <div class="div1"> <p> <a href="link">Link</a> </p> </div> ...

Changing the state variable upon clicking to display varying components

Being new to React, I am exploring how to load different components based on state variables. I am looking for a way for my handler to dynamically determine which state variable I am updating without explicitly passing the state name as a string. List of ...

Challenges when working with AJAX/jQuery in terms of fetching JSON data and setting dataType

I am currently facing a challenge with my practice of AJAX/jQuery coding. Despite my efforts to learn and improve, I find the concepts of jQuery and AJAX quite perplexing. Specifically, I am struggling to understand dataTypes and how to manage different ty ...

"Combining jQuery and JavaScript to handle form submissions in un

What happens when you combine the Javascript onSubmit handler and jQuery submit handler? <form action="" method="post" onSubmit="myJavascriptHandler();"> <input type="submit" /> </form> <script type="text/javascript"> $("form") ...

Embedded video player is failing to display and play the video file

Currently, I am in the process of developing a PHP backend for my mobile application. One specific requirement involves displaying and playing a video file that is hosted. This is the approach I have taken: $data[$i]['video'] = '<vide ...

Struggling to insert a high-quality image into inline divs of exactly 33.3333% width

After creating 3 inline divs, each taking up 33.333% of their parent width, I encountered an issue while trying to insert images into them. Whenever the image exceeds the 33.333% width of the div, it overflows outside the container. My goal is to make the ...

Steer clear of Cross-Site Request Forgery through

As someone who is still learning about web security, I am curious about the best practices for using tokens on JavaScript requests to prevent CSRF attacks. Is it possible for someone to provide a code example? I already know how to implement this properly ...

The synchronization and network bandwidth optimization of Angular and Firebase's three-way binding system

Is it possible to synchronize the text box content across various clients using Angular and Firebase? I am curious to know if Firebase will update the database with each letter I type. How does this process impact network bandwidth? Can you explain how it ...

Unlocking the Power of Typescript and ReactJS: Maximizing Efficiency with Previous State

I'm encountering difficulties implementing the previous state in React 18 with Typescript version 4.8.3. Here is my refreshToken code and I'm receiving the following error: Value of type '(prev: any) => any' has no properties in c ...

PHP: Converting messy CSV data into beautifully formatted HTML tables

My client regularly sends CSV text files to my PHP application, where the elements in each row follow a consistent format but the commas that separate them vary. This inconsistency poses a challenge when trying to extract data and present it in an HTML tab ...

Incorporating AJAX functionality into anchor interactions while preserving href links for search engine optimization benefits

Is it possible to create a link/button that triggers an AJAX/jQuery function to load new content, while still providing a link to the same content on a separate page? I am particularly concerned about SEO and how search engine crawlers will index my sitem ...

Transform a div's style when hovering over another div using absolute positioning without repetition

I am facing an issue with multiple divs positioned absolutely on top of a primary div with relative positioning. I want one specific div to change its background-color when hovering over another div within the same parent div. Though I know about ad ...

Utilizing Bootstrap's column grid system (col-sm) to set the width of form controls

Is it possible to utilize col-sm or col-xs within the input tag to specify its width? <div> <input type="button" class="col-sm-2" value="Clear"> <input type="button" class="col-sm-2" value="Confirm"> </div> ...

Integrating a YouTube video in the Google Maps info window with the help of Ajax technology

Currently working on a project for Udacity, my goal is to develop a neighborhood map using Google Maps API alongside Knockout and Ajax to integrate with another 3rd party API. A unique aspect of my approach is focusing on bars in the neighborhood and utili ...

Node.js backend includes cookies in network response header that are not visible in the application's storage cookies tab

I am currently working on creating a simple cookie using express's res.cookie() function. However, I am facing an issue where the cookies are not being set correctly in the application tab. My project setup includes a React frontend and a Node backend ...

Error in refreshing JWPlayer page: Plugin loading failure - File not located

I'm implementing JWPlayer on my Localhost environment. Here's the code snippet I'm using: <div id="Player">loading...</div> <script type="text/javascript"> jwplayer("Player").setup({ file: "<?php echo $video[' ...

The concept of transparency and visual representation

Is there a way to prevent the opacity of the parent div from affecting the opacity of the img? <div class="parent_div" style="opacity:0.2"> <p>Some text</p> <img class="gif" style="opacity: 1;" src="ht ...

Executing a Sequence of SQL Queries in Node.js

I am facing the challenge of performing nested queries to retrieve values from the database in order to generate a chart. The current approach involves executing a total of 12 queries, each aggregating the number of customers for every month of the year. ...

Extract the value from JSON data

I am faced with the challenge of extracting the value of slug from each child in a JSON dataset. The issue lies in the fact that I cannot predict how many children will be generated whenever new data is received. The generation of nested children is dynam ...

Bootstrap's nested grid system allows for intricate and dynamic layouts within

I am looking to design a grid with two columns, where on small and larger screens the width of the right column adjusts itself to accommodate its content, while the left column takes up the remaining space. On extra small screens, the layout changes to two ...