What is the method for tallying CSS page breaks in printed HTML documents?

Currently, for my report generation process using HTML and CSS to manage page breaks dynamically. I've enabled the option for users to print multiple reports at once by combining them into different sections within a single HTML document. This helps prevent print spooling issues by reducing it to one job.

However, I am facing an issue regarding numbering the section pages within the larger dynamic HTML in the format "page x of n." When left to the printer, the entire document is numbered as one entity instead of each section separately.

I'm looking for a way to predict CSS page breaks to count them before printing and insert custom pagination elements, such as HTML tags, for each section within the extensive single document.

Despite searching for a solution, I haven't been able to find one yet. So, turning to Stackoverflow for assistance seems like the next best step.

UPDATE: Resolution Implemented:

I decided to follow Christopher's suggestion, which led me on the right path, although not executed verbatim. Using jQuery, I conducted calculations based on factors like paper size, margins, and font size to determine where page breaks should occur. By inserting designated elements with CSS properties for page breaking, I tracked the number of breaks and updated the "page x of n" information accordingly once all content was processed. This approach eliminated the need to pre-determine total pages at the start (thanks to jQuery .each method).

While this solution isn't flawless and has its limitations:

  1. The inclusion of "page x of n" elements doesn't align them as traditional footers but places them at the bottom of every page's content. In my context, this compromise is acceptable.

  2. Segmenting oversized content elements proved slightly challenging, especially since most content originated from PHP scripts. Despite some complexity, I managed to work around these issues, making assumptions that could be problematic with diverse printing conditions.

  3. The accuracy of calculations hinges on presumptions about printed material dimensions, margins, font sizes, etc. Given my intranet setup, I can tolerate these compromises as they are controllable variables. Additional coding may accommodate minor variations in the future, such as changes in paper size.

Although it's not a perfect or robust solution, it resolves my immediate problem, enabling batch printing while managing spooling timeouts, maintaining pagination consistency, without resorting to generating intermediary PDFs for printing purposes.

Solving this challenge posed unexpected difficulty; thus, additional feedback and insights are still welcome.

Thanks!

UPDATE 2: Final Thoughts - Save Yourself the Hassle:

Despite diving deep into my unconventional strategy yielding some small successes, ultimately, the complications became unwieldy and prone to breakage upon any slight alterations in report structures, content updates, or paper sizes!

So, what did I learn from this experience? "Resistance is futile!" Just stick with PDFs. Feel free to begin the chorus of "we told you so" – I can handle it ;-)

Transitioning to the TCPDF library provided a solid resolution, albeit challenging to initially navigate. The library's examples were instrumental in empowering complete customization over my reports, now seamlessly generating them as intended. Consolidating multiple reports into a cohesive PDF resolved print spooling concerns, incorporating page groups for accurate numbering alignment.

If tackling similar endeavors, my advice would be to bypass the frustrations entailed with HTML/CSS reporting methods and opt for PDF solutions right away.

Answer №1

If you want to show page numbers without displaying the total number of pages, you can use the following CSS:

footer {
    position:fixed;
    bottom:0;
    left:0;
}

body {
    counter-reset: page_number;
}

#page-number:after {
    counter-increment: page_number;
    content: "Page " counter(page_number);
}

You can add an empty paragraph element with the id 'page-number' in the footer to display the page number.

Tested on Firefox 19.0.2

Answer №2

When generating PDFs for printing, I successfully implemented page breaks using wkhtmltopdf. While my solution may not be fully compatible with non-webkit browsers, adding a vendor prefix should address this issue.

My approach involved utilizing page-break-inside: avoid; and page-break-after: always; to manage page breaks within the document. Through jQuery, I calculated section heights and determined the number of breaks needed for optimal A4-sized pages. Dynamically generated page numbers were then assigned using jQuery and incorporated into PDF footers before download, ensuring accurate pagination upon viewing.

To enhance user experience, I suggest including visible page numbers in the print stylesheet layout, possibly through absolute positioning for better visibility. However, this method may not guarantee foolproof results.

Offering a downloadable PDF for printing can provide greater control over formatting without relying on web-specific stylesheets, as long as the download link is prominently displayed for easy access.

Answer №3

It is presumed that a CSS page break is placed at the end of each report automatically rather than manually at the conclusion of each page. Thus, the challenge lies in predicting when a page break will naturally occur within a lengthy HTML document. Unfortunately, this task proves to be unattainable. Even if one possesses knowledge of how many lines of a table can fit on a page based on specific page dimensions and print settings, there are external variables such as printing on legal paper at 200% scaling that cannot be accounted for. Consequently, it seems that the only feasible options are either to make an educated guess or simply not concern oneself with the issue.

Answer №4

While page breaks cannot be counted, column breaks can serve as a similar alternative.

To manage page break styles, it is recommended to use corresponding column break styles:

-webkit-column-break-inside: avoid;
-webkit-break-inside: avoid;

Ensure the report layout utilizes columns that mirror the size of a printed page:

.page.precalc {
    width: 16800mm;
    height: 257mm;
    -webkit-column-width: 168mm;
    .content {
        width: 168mm;
    }
}

Column breaks function similarly to page breaks, allowing you to determine an element's page number by assessing its horizontal position.

var left = el.getBoundingClientRect().left;
pageNumber = Math.round(left/635) + 1

While CSS columns may not consistently print correctly due to varying support, the .precalc style can be removed after completing layout calculations to revert to the original vertical layout. Alternatively, a screen/print media query could be employed based on specific needs.

This approach has proven successful for generating a table of contents with phantomjs, although implementing it in a user-controlled browser may pose additional complications.

Answer №5

This code snippet will trigger a page break before each h2 element on the webpage.

Referenced from this source

<style type="text/css>
  h2 {
    page-break-before: always;
  }
</style>

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

Is there a way I can incorporate v-for with a computed variable?

I am trying to display navigation items based on my authority and other conditions. Below is the code I am using: <template v-for="(subItem, index2) in item.children"> <v-list-item sub-group link :to="subItem.link" exact ...

Is it possible to target the initial sibling of a parent element using a CSS selector?

Is there a way to target the <p> element using only the id "Standort" as a constant? Any suggestions on how to accomplish this? <section> <header> <h2 class="licht"><span id="Standort" class="-sitemap-select-item-select ...

Is it possible to send an ajax request to a user control file with the extension .ascx?

I am trying to interact with a user control on my page through ajax. Is it possible to make an ajax request directly to the user control (.ascx) instead of .aspx or .ashx files? ...

Choose a group of radio buttons inside a container when a button is clicked

I have a bunch of containers containing radio buttons. The goal is for the container of a selected radio button to appear different: input[type="radio"]:checked+.container { border: 5px solid red; } <div class="container"> <input class="btn ...

The utilization of bootstrap can lead to CSS interruptions

I am trying to create a navigation button that transforms from 3 horizontal lines to an X shape when clicked. var anchor = document.querySelectorAll('button'); [].forEach.call(anchor, function(anchor) { var open = false; an ...

Creating a React component in Typescript to utilize lodash helper functions

I have a component that looks like this: import React, { Component } from 'react'; import throttle from 'lodash.throttle'; interface Props { withScroll: boolean; } class Image extends Component<Props, {}> { throttledWindowS ...

Angular throws an error when trying to parse undefined data outside of an async function

I'm having trouble parsing data retrieved from an http call and passing it to ngOnInit. Can you assist me in finding a solution? My project is built with Angular 4. Here's the async function: async getAsyncData() { this.asyncResult = awai ...

Swapping stylesheets using a hyperlink - a simple guide

Currently, I am creating a website that utilizes PHP, XHTML strict, and jQuery. The main goal is to ensure the site is adaptable for mobile and desktop devices by implementing the principles of Responsive Web Design. This involves serving different stylesh ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

What is the reason for me continuously receiving the error "cannot read map of undefined"?

Having trouble debugging my redux sagas and react integration. No matter what initial state I set, I keep running into undefined errors when trying to map through the data. I've tried null, undefined, and empty arrays but nothing seems to work. Can a ...

Could somebody provide clarification on the functions being called in the Angular Test Code, specifically evaluate() and dragAndDrop()?

Exploring the drag and drop functionality of an angular-Gridster application using Protractor with a test code. I have some questions about the functions being used in the code snippet below. Can someone clarify the purpose of evaluate() - the API definit ...

The subfolder and HTML page have identical names and are not functioning properly

I recently updated my webpage by removing the .html extensions using htaccess. My website includes a page named "blog.html" and a subfolder called "blog" with additional html pages inside. RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ ...

Navigating in AngularJS with various URL parameters

Within my application, I am in need of using routes that require multiple attributes from the URL to be passed into PHP. The current setup that is functioning correctly is as follows: .when('/jobs/:type', { templateUrl: function(attrs){ ...

Utilizing the map() function to parse a Json object

Looking for guidance with working with a JSON object structured like this: {"Title":"asb","Date":"2019","Other":"not important"} How can I correctly read this object and render it in <ul><li> format? Please Note: I have attempted to assign th ...

ngResource transformResponse guide on dealing with both successful and erroneous responses

When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401). This poses a challenge on my ...

Please send the element that is specifically activated by the onClick function

This is the HTML code I am working with: <li class="custom-bottom-list"> <a onClick="upvote(this)"><i class="fa fa-thumbs-o-up"></i><span>upvote</span></a> </li> Here is my JavaScript function for Upvot ...

What is the best approach to streamline and optimize this JavaScript logic code for greater efficiency?

Working on a project, I find myself dealing with 21 buttons that can be in either an active or inactive state. The state of certain buttons is influenced by the press of other buttons as well as their own activation. To handle this in my HTML, I utilize ng ...

Page cannot be adjusted to fit the viewport

My goal is to have the page fit perfectly within the viewport, but despite using the body properties below, I am still seeing a vertical scrollbar. body { display: grid; grid-template: .8fr 4fr / 1fr 4fr; max-height: 100vh; margin: 0; } I'm w ...

Bookmarklet in JavaScript that automatically extracts and displays Meta keywords in a new tab within the browser

I successfully implemented a script that extracts site meta keywords and writes them into the DOM. javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i=0;i<metaCollection.length;i++) { nameAttri ...

matching patterns within HTML div elements

Within my Notepad++ text editor, I am attempting to remove all spaces within a div tag except for those between the comma and the last name. This is what the input looks like: <div class="n"> Joe , Williams </div> And this is the desire ...