Troubleshooting window.print alignment problems with Javascript

Whenever I use window.print in my JavaScript code to print a specific div, I encounter alignment issues on the printed page.

Below is the snippet of code that I am using for printing along with links to images showing the output and the layout after printing:

  function PrintPopup() {
        var data = $("#viewCoupon").html();
        var mywindow = window.open('', 'Print Data', 'height=540,width=980');
        mywindow.document.write("<html><head><title>Bonus Box Offer</title>");
        mywindow.document.write("<link href=\"Content/style.css\" rel=\"stylesheet\" />");
        mywindow.document.write("<style>.userwinners{margin-top: 51px;margin-left: 0;} .no-Print{display:none;}  @media print {.no-Print{display:none;} title {display:none;} }</style>");
        mywindow.document.write("</head><body >");
        mywindow.document.write(data);
        mywindow.document.write("</body></html>");

        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10

        mywindow.print();
        //mywindow.close();

        return true;
    }

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

https://i.sstatic.net/9t2By.png

Answer №1

To optimize the alignment of your page, consider utilizing a separate CSS file. This will allow you to customize the layout with more precision. Below is an example of how to include a CSS file specifically for printing:

<link rel="stylesheet" type="text/css" href="print.css" media="print">

You have the freedom to add any necessary CSS rules to appropriately align your printed pages.

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

Determining the age range using JavaScript

Struggling lately to tally the duplicate elements in an array and convert them into objects. Currently, I am attempting to calculate the frequencies of age ranges. Here is a code snippet that counts duplicate ages: const age = [5, 5, 16, 5, 16]; const su ...

Guide on changing all website addresses ending with .net in the web.config file

My current project in Sitefinity version 10.2 has the default url set to 'url/Sitefinity'. However, I need to change it so that everything in the website appears as 'url/Portal/Sitefinity'. I am relatively new to .Net and unsure of how ...

Is there a way to transfer the content of a div into a fresh window while retaining its original formatting

Here is a way to copy a new page: var yourDOCTYPE = "<!DOCTYPE html..."; // the doctype declaration var printPreview = window.open('about:blank', 'print_preview'); var printDocument = printPreview.document; printDocument.open(); pri ...

Guide to selecting a specific year on a calendar using Selenium with JavaScript

While attempting to create a Selenium test using JavaScript, I encountered an issue with filling in calendar data through a dropdown menu: const {Builder, By, Key} = require('selenium-webdriver') const test2 = async () => { let driver = awa ...

Refreshing data in Laravel after an AJAX request

Currently, he is working on coding that involves filtering data within a table. Using Ajax to call the link will retrieve a response (json) with the answers. However, there has been an issue. The task at hand is to render tables without using append or sim ...

"Troubleshooting form handling in a .NET MVC Core application with jQuery/AJAX inside a for loop -

Having trouble ensuring the correct IDs are saved when moving through questions and answers in a form loop. The code functions properly, creating new records in the database with each submit click using jquery/ajax to avoid page redirection. However, when ...

What is the best way to navigate through multiple layers of nested JSON elements in C#?

Received a JSON response from a public API with a specific structure as shown below. [ { "ID": "12345", "company": [ { "contract_ID": "abc5678", "company": [ { &quo ...

Unable to dynamically add values to drop-down menu using PHP

Looking for some assistance. I am trying to populate a dropdown menu with values fetched from a database using PHP. Below is my code: <?php $getcustomerobj = $dbobj->getFeedbackData($db,$id); echo ($getcustomerobj->companypro); ?> <sel ...

Will synchronous programming on an Express server prevent other users from accessing the page simultaneously?

Currently working on a simple one-page web app that depends on loading weather data from a file. To avoid multiple HTTP requests for each visitor, I have a separate script refreshing the data periodically. In this particular instance, I am using fs.readFi ...

What caused the failure of JQGrid in displaying data?

The issue I encountered was with the GetData() method in the code below. It seemed to have data, as indicated by the pager component displaying multiple pages and the blue border color appearing when clicking on rows. However, the rows themselves did not d ...

Guidelines for executing a PHP script upon a button click

I am new to learning PHP. I have a jQuery code that I need to implement in PHP. The active class simply changes display:none to display:block. You can find the code here. $(document).ready(function(){ $(".cecutient-btn").click(function(){ event. ...

When trying to fetch JSON data, the outcome is two pending promises: [ Promise { <pending> }, Promise { <pending> } ]

I am struggling to fetch the JSON data from the API endpoint below: https://api.hatchways.io/assessment/blog/posts When using node.js and making HTTPS requests, I keep getting an array of [ Promise { }, Promise { } ]. The challenge is that I can only se ...

When dynamically adding rules to jQuery validate, I encountered an unexpected error

My dynamic form validation with jQuery validate involves a drop-down menu on my HTML that includes values 1, 2, 3, and 4. Depending on the selection made from the drop-down, different div elements are displayed with corresponding fields. All the input fie ...

Make sure to hold off on proceeding until the JavaScript function has fully executed and the PHP script

I am facing an issue with my registration form, which is displayed in an iFrame on my main window. After the user submits the form, a PHP script is supposed to insert the data into the database. The problem arises when I try to close the iFrame using a fun ...

Checking a bcrypt-encrypted password in an Express application

I am encountering an issue with my login password verification code. Even when the correct password is entered, it is not being validated properly. Can anyone provide assistance with this problem? login(req, res) { const { email, pass } = req.body; ...

Unfortunately, the pseudo-selector `:hidden` fails to function properly when applied to controls that have the CSS property

Hey, I'm currently using the jquery validation plugin to validate my aspx page. To hide the deliveryToDiv, I've used the following code: document.getElementById("deliveryToDiv").style.display = "none"; This particular div contains other control ...

Is there a way to verify if an AJAX request calls HTML content?

Here is the HTML code for a mosaic of images. <div id="container"> <img id="1" /> ... <img id="20" /> </div> This script creates a mosaic layout from the images on the page after it has loaded or been resized. <script& ...

What is the process for accessing extra scope information with next-auth?

I have integrated next-auth with Discord authentication and included guilds in my scope, but I am unable to retrieve the guild data. How can this issue be resolved? const options = { providers: [ Providers.Discord({ clientId: process.env.DISC ...

How can I associate a column value with a dynamically generated button in WPF?

I'm currently working on a WPF application that involves a database with two columns: product_id and product_name. I need to dynamically add buttons based on the number of products in the database table. I want to bind these two columns with the dynam ...

Using JSON with escaped slashes in a filepath may cause the image to not display

I am utilizing PHP in conjunction with a for loop to organize data into valid HTML and then utilize JSON to append the data and showcase it on the page. However, the HTML display appears incorrect due to JSON slash escaping. Here is my PHP for loop: $jso ...