When creating a dynamic page number using JavaScript during a print event, the height of an A4 page is not taken into

While creating my A4 invoice using HTML, CSS, and JS, everything appears correctly in the print preview. However, I am encountering an issue where the page number is not aligned properly and extra empty pages are generated automatically.

Below is a snippet of the code:

<html>

<head>
    <script>function setPrintStyles(pagesize, standardSize) {
            var documentHeight = standardSize ? '' : (document.getElementsByTagName('html')[0].offsetHeight / 2) + 100 + 'px';
            var bodySize = standardSize ? '' : 'body { width: ' + pagesize + '; }';
            var css = `@media print { @page { size: ${pagesize} ${documentHeight}; } ${bodySize} }`,
                head = document.head || document.getElementsByTagName('head')[0],
                style = document.createElement('style');
            head.appendChild(style);
            style.type = 'text/css';
            style.appendChild(document.createTextNode(css));
        }</script>
    <style type="text/css">
     /* Styling for printing */
    </style>
    <style>
        html {
            height: 297mm !important;
            overflow-y: scroll;
        }
    </style>
</head>

<body><!--!-->
    <table>
       /*Invoice details*/
    </table>
    <div id="dpi" style="height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;"></div>
    <script>window.print();</script>
    <script>/* Script to add/remove page numbers */</script>
</body>

</html>

Issue Encountered:

Despite having code for generating a single-page A4 invoice, it results in two pages during print preview with visible page numbers on the invoice itself.

Visual Representation:

Second Page:

Script Used for Page Numbering:

/* Javascript function to handle page numbering */

Expected Result: The generated invoice should align properly within the defined 297mm height constraint of an A4 page.

If you save this code as an HTML file and view it in a browser, there might be differences in how the output is displayed compared to expectations.

Answer №1

In order to fully customize the dimensions of a page, such as when creating an invoice, additional CSS parameters must be specified...

body {

 position:absolute; left:0; top:0; width:95%; height:95%; /* This line of CSS was added */

 font-family: Calibri, monospace;
 font-size: 0.8rem;
 margin: 1rem;
 border: 1px solid;

}

By following these guidelines, you can generate a perfectly centered A4 invoice on a single page.

If I could figure out how to do so, I would share an image of my result here.

While your custom page numbering may need adjustment, it seems unnecessary since printing options already handle this effectively. Why duplicate existing features?

I believe there is a way to programmatically request page numbering adjustments, although I cannot recall the specifics at the moment.

Answer №2

By simply removing the @media print from the CSS, I was able to fix this issue. The presence of @media print caused a discrepancy in styles when viewed on the normal screen media, resulting in an incorrect page height and scroll bars appearing. This led to inaccurate page numbers being displayed across two pages.

However, without the @media print, the styles were properly applied in the normal screen media, ensuring the correct page height with no scroll bars present.

This adjustment resulted in the accurate display of page numbers on a single 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

CSS for Positioning Elements Side by Side Using Absolute Positioning

I'm having trouble figuring out how to position balloons like the ones shown in this image: <div class="red_frame"> <img src="https://i.sstatic.net/54SMF.png" class="r_over"/> <img src="https://i.sstatic.net/54SMF.png" ...

Creating a backup link for a video player component in NextJs

My aim is to make sure that two video player components in a NextJS application can still access and play videos even when the application is running locally using npm run dev without an internet connection. Currently, these two components.. <HoverVi ...

Having trouble retrieving information from the Redux store and displaying it in the user interface component

I'm currently diving into the world of Redux and working on a tracker app, but I've hit a roadblock that's had me stuck for days. Your help would be greatly appreciated. Thank you. store.js import { createStore, applyMiddleware, compose } f ...

Effortlessly glide to a specific div ID upon page load using the URL address

One way to implement smooth scrolling to an anchor on page load is by using jQuery. Here's an example code snippet: $(function(){ $('html, body').animate({ scrollTop: $( $('#anchor1').attr('href') ).offset(). ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

Creating a stunning display of six video textures on a cube through the power of three.js

My current project involves working with a video that has been segmented into six parts. Here is a screenshot of the input video. The goal is to project these 6 videos onto the six faces of a cube using JavaScript: <!DOCTYPE html> <html> &l ...

What is the best way to utilize recently added modules in React if they are not listed in the package.json "dependencies" section?

[I have updated my question to provide more details] As a newcomer to working with React, I may be asking a basic question. Recently, I installed several modules and will use one (example: @react-google-maps/api) for clarification. In my PC's termin ...

What is the syntax for creating ES6 arrow functions in TypeScript?

Without a doubt, TypeScript is the way to go for JavaScript projects. Its advantages are numerous, but one of the standout features is typed variables. Arrow functions, like the one below, are also fantastic: const arFunc = ({ n, m }) => console.log(`$ ...

The lack of flexibility in this element stems from the fact that it is not classified as a flex item

I'm facing an issue with flexbox and its unusual behavior. I have set up flexbox for the parent element and used flex: 1 1 100%, but it's not working as expected. When I checked in Firefox Developer Tools, it says that the parent is not a flex co ...

"Escape the confines of traditional div sections with the dynamic features of

In the beginning, I have arranged two rows of three divs on my webpage, which is how I intend to use them later. However, when testing the 'mobile view', the divs in the section overflow and move into the next part below the section. This causes ...

Is there a way to extract specific data from a JSON file and calculate the average in order to generate a line graph using JavaScript

I am working with data in json format and I want to create plots using plotly js. Specifically, I need to generate a plot showing different states by semester. To do this, I first need to filter the data for each state (for example, California), calculate ...

What steps should I take to resolve the "You do not have authorization to access this directory or page" error in Azure App Services?

Currently, I am attempting to deploy my Next.js 13 application to AppServices using Github Actions. The compilation process on Github was successful, however, I am encountering an issue where my application does not seem to be deploying or starting up prop ...

Is it possible to combine the index page with the login page for a web project, or is it recommended to create a separate login page?

Would it be a violation of any rules if the index page of my web project is used as the login page for users? Do I have to redirect them to a different page? Is this considered best practice? ...

Include a new feature within an onClick event

I'm looking to implement a single page application using React.js and I want to incorporate a list within a material-ui drawer. The goal is to dynamically add elements to an array every time a button is clicked, but I'm stuck on how to write this ...

Align the text on the same horizontal line

I have been struggling with this issue for hours. Here is my Header.js <div className="navbar-inner"> <h2>Text1</h2> <h3>Text2</h3> </div> This is the content of my Header.css: .navbar-inner { ...

Executing a series of tests using Postman

Is running multiple requests in a postman script feasible? I have an endpoint: http://localhost/gadgets/{id}/buy This endpoint sets a flag in a gadget object/entry based on its id. With hundreds of gadgets, can I use a shared file of ids to create and run ...

Action type is not recognized: modification

After browsing through multiple forums, I haven't found a solution that works for my particular issue with my VueJS app. The problem arises when I try to input something in my first component. Below is the code snippet: main.js import Vue from &apos ...

My locale NUXT JavaScript files are being blocked by Content Security Policy

I've been working on implementing CSP headers for my website to ensure data is loaded from trusted sources. However, I'm facing an issue where CSP is blocking my local JS files. Here's a snippet from my nuxt.config.js: const self = 'lo ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

Autofill functions may not be compatible with input fields generated using JavaScript

Having trouble with browsers not using autocomplete in login overlays generated with JavaScript? It can be really annoying. Any suggestions on how to fix this issue? Should I create a hidden form within the original HTML and then move it into the overlay? ...