Tips for preventing page breaks (when printing or saving as a PDF) in lengthy HTML tables

Here is the link to a single HTML file (including style and scripts): FQ.html

The problem I'm facing can be seen in this image: https://i.sstatic.net/Nr4BZ.png

I've tried several solutions, the latest of which involves the following CSS...

@media print{
  @page {
    size:1080px 1080px;
    margin: 0px;
  }
  .page-break-before  { page-break-before: always; display:block; width:200%;}
  .page-break  { display:block; page-break-after: always; width:200%; }
}

...and some Javascript.

//set viewport height in print mode.
var height = 780;
//pick up the total table.
var table = $('#identification_section > table')[0];
//initialize the sum variable with height of title (h2 tag)
var sum = 24;
//loop all table rows including child tables 
for (var i = 0, row; row = table.rows[i]; i++) {
  //tr is the parent table row which may contain child table.
  var tr = row;
  if (tr.offsetHeight > height) {
    var child_table = tr.cells[0].children[0]; 
    if (child_table.className=="group-table") {
      var child_sum = 0;
      for (var j=0, subrow; subrow = child_table.rows[j]; j++) {
        var subtr = subrow;
        child_sum += subtr.offsetHeight;
        if (child_table.rows[j+1]!=null)
          if (child_sum + child_table.rows[j+1].offsetHeight > height) {
            child_table.rows[j+1].classList.add('page-break-before');
            subtr.classList.add('page-break');
            child_sum = 0;
          }
      }
    }
  }

  sum += tr.offsetHeight;
  if (table.rows[i+1]!=null)
    if (sum + table.rows[i+1].offsetHeight>height) {
      table.rows[i+1].classList.add('page-break-before');
      tr.classList.add('page-break');
      sum = 0;
    }
}

Despite my efforts, I am still struggling with the issue. Instead of avoiding breaks on text, I thought it might be easier to avoid breaking on a div element. However, there are still 2 main issues with my attempted solution - excessive breaks and the width setting not working properly.

I would appreciate any advice on how to prevent breaks on text or divs, preferably text.

Answer №1

To ensure proper page breaks, it is necessary to implement the page-break-before and page-break-after rules for all elements within the document.

For example, when dealing with tables, you can target specific elements using selectors like table tr.

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

Bootstrap Progress Animation Not Scaling Properly

I am encountering an issue with my Bootstrap 2.3 progress bars. They are supposed to show async file reads and be animated by updating their CSS properties using jQuery. However, the problem I'm facing is that the scale seems to be off - when the prog ...

What is the best way to transform this unfamiliar CSS element into JavaScript code?

I'm facing an issue where I want to animate a CSS image based on time constraints, but since it's in CSS, I'm unable to achieve the desired effect. The animation in question is not the sun itself, but rather a yellowish half-circle animation ...

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

Managing actions with IconMenu and ListItem in React using MaterialUi

Currently, I am delving into the world of React and attempting to create a simple TODO list using Material-UI. However, I have encountered an issue with handling IconMenu menu actions within a listItem element. I am struggling with triggering the deleteI ...

Is the Date Epoch a reliable form of unique identification?

Currently, I'm developing a Node API and encountered a situation where I need to create a unique 15-digit random number for a model without using autoincrement. The challenge is to ensure that the generated number is not trivial. I am hesitant about ...

What is the best way to adjust the layout of these two elements using CSS in order to display them on

I need assistance with adjusting the layout of a dropdown list next to its label in an Angular html page. <div *ngIf="this.userRole == 'myrequests'" class="col-2" [ngClass]="{ 'd-none': view != 'list&apo ...

Divide the division inside the box by clicking on it

I am looking to create a unique div with a random background color and a width of 100px. Additionally, I want to have a button that, when clicked, will split the original div into two equal parts, each with its own random background color. With each subs ...

I'm having trouble obtaining accurate results for $....<...$ within the <li> tags using MathJax

I have gained extensive experience working with LaTeX formatting, but not every document follows the standard practice of having a space before and after the symbols < and >. When I attempt to use MathJax to display these documents, they fail to rend ...

Incorporating lazy loading for diverse content to enhance pagination

I'm currently using jpaginate for pagination on a large dataset, but I've noticed that all the content loads at once. Is there a jQuery plugin available that will only load the content for the current page? ...

When NuxtImg is utilized, the image will rotate 90 degrees with Nuxt3 NuxtImg

Recently, I have encountered an issue when using NuxtImg where my images appear rotated by 90°. This problem specifically arises with vertical mobile images that are read from supabase and displayed. Interestingly, the images look fine before uploading th ...

Distinguishing between a video or image when uploading files in JavaScript

I've been researching whether JavaScript can determine if a file is a video or an image. However, most of the information I found only shows how to accept these types using the input tag. What I really need is for JS to identify the file type and the ...

Connect ng-models with checkboxes in input field

I am facing an issue with binding ng-models using ng-repeat in an input checkbox tag. Let me share my code and elaborate further. app/main.html: <div ng-repeat="feature in features"> <input type="checkbox" ng-model="features[$index].name"> ...

The function and if-else statement are experiencing malfunctions

Currently in the early stages of learning coding, I've been focusing on building a solid foundation by practicing with CodeWars. Utilizing this platform for practice has been beneficial because it offers solutions for guidance. While attempting to wor ...

How to stop an AJAX request using Chrome developer tools?

Is there a way to cancel an initiated ajax request from Chrome Developer Tools? I want to test if my fallback message displays correctly without changing the code. Setting No throttling to Offline will make all calls fail, but I just need one API to fail f ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

What is the process for generating an attribute in a system?

If I want to create an element using plain JavaScript, here is how I can do it: var btn = document.createElement('button'); btn.setAttribute('onClick', 'console.log(\'click\')'); document.body.appendChild( ...

Just a snippet of a webpage shown

My website focuses on online magazines. I'm looking for a way to selectively display specific parts of articles that are in regular HTML format with a global CSS stylesheet applied. There are no images, only text. How can I extract certain segments of ...

JavaScript communication between clients and servers

I am looking to develop two scripts, one for the client-side and one for the server-side. I came across a snippet that allows for asynchronous calling of JavaScript: <html> <head> </head> <body> <script> (function() { ...

AngularJS directives and controller scope

I'm looking to create a custom directive in AngularJS that generates a div element as a title and a ul list below it. The title should be customizable through an attribute, while the list content is controlled by a designated controller. Check out t ...