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:

https://i.sstatic.net/RLE7d.png

Second Page:

https://i.sstatic.net/ZMEo3.png

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.

https://i.sstatic.net/0XDZa.png

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.

https://i.sstatic.net/ueUEy.png

This adjustment resulted in the accurate display of page numbers on a single page.

https://i.sstatic.net/UldOK.png

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

What is the best way to update a targeted component in React when triggered by an event handler?

Your goal may seem straightforward, but getting a reference to a specific component using this is proving to be tricky. Here we have our App.js file: import React, { Component } from 'react'; import CoolBox from './coolBox.js'; import ...

Create HTML content dynamically with JavaScript and then utilize AngularJS to interpret and render it

I am creating an HTML table that looks like this: <table id="#webappname"> <tr ng-repeat="data in d"> <td>1 {{data}}</td> <td>2 hey !</td> </tr> </table> To create this, I am using a ...

Creating an autocomplete feature with just one input field to display information for two to three additional input fields

I'm working on implementing an autocomplete feature similar to this example: . Feel free to test it out with the code snippets provided: 1000, 1001. I've successfully implemented the autocomplete functionality where typing in Pa suggests Paris. ...

"Exploring locations with Google Maps and integrating them into interactive

I recently encountered an issue while working on a node express application and integrating the google maps javascript api. The problem arose when I attempted to transfer the sample code from the google website, along with my API key, into a .ejs file. S ...

Removing or hiding elements using jQuery

My HTML code includes a select tag, and when the value changes, I want to retrieve data from the database based on this new value. The data is then displayed in a new div. This new div contains a close sign that should hide the div when clicked by the user ...

Approximately 20% of spoken words are not accurately conveyed by Speech Synthesis Google Voices, failing to adhere to the intended voice selection

When using speechSynthesis.speak(utterance) in Chrome with the "Google UK English Female" voice, there is an issue where a male voice is randomly spoken instead. Any thoughts on how to resolve this? Latest Update: July 26th, 2022 This appears to be a bug ...

Delete items within the first 10 minutes of shutting it down

Is there a way to temporarily remove a newsletter element for 10 minutes after closing it on a webpage? The idea is that once the panel is closed, it should stay hidden even if the page is refreshed within that timeframe. I was considering using local stor ...

I am looking to sort users based on their chosen names

I have a task where I need to filter users from a list based on the name selected from another field called Select Name. The data associated with the selected name should display only the users related to that data in a field called username. Currently, wh ...

Converting HTML to PDF: Transform your web content into

I have a couple of tasks that need to be completed: Firstly, I need to create a functionality where clicking a button will convert an HTML5 page into a .PDF file. Secondly, I am looking to generate another page with a table (Grid) containing data. The gr ...

Is there a way to change TextBox multiline to uppercase in Opera browser?

Does anyone know how to convert TextBox multiline to Uppercase in Opera? I tried using "text-transform:uppercase" but it only seems to work with IE ...

Bringing the Jquery cursor into focus following the addition of an emoji

Looking to add emojis in a contenteditable div but facing an issue with the cursor placement. Here is a DEMO created on codepen.io. The demo includes a tree emoji example where clicking on the emoji adds it to the #text contenteditable div. However, after ...

Configuring settings for gulp-jshint

I'm currently utilizing gulp to compile my JavaScript code. My intention is to run jshint on the files before concatenating them, but I'm encountering difficulties in configuring the options properly. Am I handling this process correctly? var re ...

Tips for retaining the value of a variable when the page is reloaded

I need to store the value of the variable loggedIn, as it determines the behavior of a function in appComponent.html. Can you explain how I can achieve this? Template of app component: <li class="nav-item"> <a class ...

Transform an asynchronous callback into an asynchronous generator format

I have the following function from a third-party package that I am unable to modify async function runTransaction(callback) { const client = await createClient(); try { await client.query("BEGIN"); await callback(client); } ...

Is it possible to add information to the form data object?

When I send an image to the server using form data, everything seems fine until I try to add data from a crop plugin. Here is the code snippet: //create form data from form var formData = new FormData($('#my-form')[0]); //append the image formD ...

"Challenges Arising in Deciphering a Basic JSON Array

After countless attempts, I am still struggling to solve this issue. My PHP code is functioning properly, as it returns the expected data when "Grove Bow" is selected from the dropdown menu: [{"wtype":"Grove Bow","was":"1.55","wcc":"5","wbdmin":"12","wbdm ...

Styled-Component: Incorporating Variables into Styled-Component is my goal

Currently, I am working on an app and have created a separate file for styling. I decided to use style-components for custom CSS, but faced an issue where I couldn't access variables instead of HEX values. Even after storing color values in a variable ...

Interactive HTML5 canvas: Dragging and dropping multiple items

I'm currently working on a project that involves allowing users to drag and drop multiple objects within a specified area. To achieve this, I am utilizing the html5 canvas tag. While the functionality works smoothly when dragging and dropping a single ...

Websites are operating at a sluggish pace

Yesterday, out of nowhere, we encountered a vserver issue. If you visit this particular Website: You will notice that it takes forever to load. This problem is affecting all websites hosted on the vserver. I reached out to the Provider to see if there we ...

Generate an array containing the IDs of the chosen objects

Suppose I have an array like this: var aaa = [ {"id": 1, "text": "Ann"}, {"id": 2, "text": "Bob"}, {"id": 3, "text": "Carol"}, {"id": 4, "text& ...