Tips for preserving CSS formatting during printing from a designated section of a webpage

When I try to print a specific section of my webpage, all the CSS styles are getting removed. Here is my HTML document:

const button = document.createElement('button') //this is the print button
button.classList.add('printButton')
button.textContent = 'Print'

const entryContainer = document.getElementById('container')
const card = document.createElement('div') //this will be the card to print
card.classList.add('card')
card.setAttribute('id', 'printcard')
card.textContent = 'I failed the first quarter of a class in middle school, so I made a fake report card. I did this every quarter that year. I forgot that they mail home the end-of-year cards, and my mom got it before I could intercept with my fake. She was PISSED—at the school for their error. The teacher also retired that year and had already thrown out his records, so they had to take my mother’s “proof” (the fake ones I made throughout the year) and “correct” the “mistake.” I’ve never told her the truth.'

entryContainer.appendChild(card)
entryContainer.appendChild(button)

button.addEventListener('click', () => {
  var prtContent = document.getElementById("printcard");
  var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
  WinPrint.document.write(prtContent.innerHTML);
  WinPrint.document.write('<link rel=stylesheet href="style.css">')
  WinPrint.document.close();
  WinPrint.focus();
  WinPrint.print();
  WinPrint.close();
})
ul {
  display: flex;
  flex-direction: column;
  font-size: 20px;
  margin-top: 50px;
  text-decoration: none;
  width: 500px;
  list-style: none;
  gap: 10px;
}

body {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.card-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 20px;
  width: 700px;
  height: 450px;
  border: 2px solid rgb(8, 8, 8);
}

.card {
  width: 500px;
  height: 350px;
  background-color: red !important;
  font-size: 1.2em;
  padding: 20px;
  border: 2px solid rgb(8, 8, 8);
}

.printButton {
  width: 120px;
  height: 40px;
  font-size: 1.5em;
  cursor: pointer;
}
<ul>
  <li>This is</li>
  <li>The content that </li>
  <li>I dont want </li>
  <li>printed</li>
  <li>on the page</li>
</ul>
<div class="card-container" id="container"></div>

I need guidance on how to resolve this issue. Here is an image of what I am currently getting https://i.sstatic.net/1LojQ.png

The expected outcome should look like the example below, where only the text, borders, and colors are visible, and everything else is blank https://i.sstatic.net/0g3HE.png

Answer №1

Give this a shot --> include a no-Print class:
CSS

@media print { 
  .no-Print { display : none; }
  }

HTML

<ul class="no-Print">
  <li>This content</li>
  <li>Should not be </li>
  <li>Displayed when </li>
  <li>Printing</li>
  <li>The page</li>
</ul>
<div class="card-container" id="container"gt;
   More information
</div>

prior solution :
HTML

<!DOCTYPE html>
<html lang="en  
...

<style media="print">
  .no-Print { display : none; }
</style>
</head>
<body>

  <ul class="no-Print">
    <li>This content</li>
    <li>Should not be </li>
    <li>Displayed when </li>
    <li>Printing</li>
    <li>The page</li>
  </ul>
  <div class="card-container" id="container">
     More information
  </div>

...

Answer №2

After analyzing the issue, I realized that the old code contained unnecessary lines of JavaScript code. Here is an example of the old code:

const button = document.createElement('button') //this creates a print button
button.classList.add('printButton')
button.textContent = 'Print'

const entryContainer = document.getElementById('container')
const card = document.createElement('div') //this will be the printed card
card.classList.add('card')
card.setAttribute('id', 'printcard')
card.textContent = 'I failed the first quarter of a class in middle school, so I made a fake report card every quarter that year. However, my plan backfired when my mother received the real end-of-year cards and was upset with the school for their mistake. The teacher had already retired and discarded his records, leading to a situation where my fake reports were used as evidence to correct the error.'

entryContainer.appendChild(card)
entryContainer.appendChild(button)

button.addEventListener('click', () => {
  //code for printing
  var prtContent = document.getElementById("printcard");
  var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
  WinPrint.document.write(prtContent.innerHTML);
  WinPrint.document.write('<link rel=stylesheet href="style.css">')
  WinPrint.document.close();
  WinPrint.focus();
  WinPrint.print();
  WinPrint.close();
})

Below is the revised code that functions correctly:

const button = document.createElement('button')  //creates a print button
button.classList.add('printButton')
button.textContent = 'Print'

const entryContainer = document.getElementById('container')
const card = document.createElement('div') //represents the card to be printed
card.classList.add('card')
card.classList.add('card', 'print');
card.setAttribute('id','printcard')
card.textContent = 'I failed the first quarter of a class in middle school, so I created fake report cards throughout the year. After my mom discovered the truth by receiving the actual end-of-year report card, she was understandably angry at the school. The retiring teacher's lack of records meant that my fake reports became crucial in correcting the mistake.'




entryContainer.appendChild(card)
entryContainer.appendChild(button)

button.addEventListener('click',()=>{

    //printing code
    var prtContent = document.getElementById("printcard");
    print(prtContent)

})


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

Extracting and passing a JSON object to a Spring controller

I have a file upload feature on my jsp page that specifically accepts json format files. I want to retrieve the uploaded json file and pass it to a Spring controller for further processing. This is how my javascript code appears: var file = this.files[0] ...

Text overlaps when li element is nested inside another element

Seeking assistance in creating a CSS/HTML menu bar that triggers list elements on hover. Facing difficulty arranging the list in two columns. Code Sample:http://jsfiddle.net/Km922/1/ <!DOCTYPE html> <html lang="en"> <head> <meta ...

Tips on preventing form submission when clicking on another button within the same form

I created a shopping cart page with functionality to adjust the quantity using JavaScript. I have shared some of the HTML code below, <form action="payment.php" method="post"> <div class="qty__amount"> ...

How can we extract validation data from a function using Ajax and then transfer that information to another Ajax query?

I have an AJAX function that validates a textbox on my page. After validating, I need to perform an action with that value (search in the database and display results in the textbox). However, I also need the validation function for another separate functi ...

Is there a way to automatically generate and allocate an identifier to an input field?

I've written the code below, but I'm having trouble figuring out if it's accurate. Specifically, I can't seem to access the text inputs that have been created by their respective id attributes. for (i=0;i<t;i++) { div.innerHTML=div. ...

Ways to reach the standard look

Check out this follow-up to a previously posted issue. Click here to view it I am currently facing an issue with the code below, where I am unable to make the second button inherit the default border and padding styles. Any assistance would be greatly app ...

Exploring the method of dynamically adding a row to a table on button click using Angular 2

In the midst of my Angular2 project, I am exploring the possibility of dynamically adding rows to a table when a button is clicked. While I am aware that *ngFor can achieve this, I am curious if it can be implemented only upon the clicking of a button. ...

Reloading a webpage does not clear HTML tables containing jQuery interactions in Firefox

Apologies if this question has already been asked. I incorporated hide/unhide features using jQuery into a simple HTML table. The table functioned correctly in Chrome 24.0.1312.52 m and IE8+. Yet, upon refreshing the page in Firefox 15.0.1, the pr ...

What steps do I need to take to modify the MUI Badge component and insert custom text inside?

Is there a way to replace the number with a label next to a new row added to my table using MUI Badge? For example, instead of displaying a number like 4, I want it to show the word "New" as shown in this image: enter image description here This is the co ...

Tips for making a tray-shaped bottom border similar to the Android input field

I recently encountered an issue with a custom input I created in a JavaScript file for an application built on Phonegap. The border of the input was not displaying correctly on Android devices compared to regular inputs. https://i.sstatic.net/PmSmI.png M ...

Duplicate the Date object without retaining previous data

Struggling with creating a custom deep clone feature that's encountering issues with the Date object. For instance, let now = {time: new Date()} or let now = {data: new Date().getDay()}. When attempting to copy it, the goal is not to replicate the cur ...

Adjusting Picture Sizes to Fit the Dimensions of a Photo Frame

Currently, I am in the process of developing a website that incorporates two distinct image types: Portrait photos https://i.sstatic.net/rmIXQ.jpg Landscape photos https://i.sstatic.net/Z7mr3.jpg As you can see, there are two different categories of ...

Generate all possible arrangements of zeros and ones in a two-dimensional matrix with dimensions of n by n

Looking to create a function that will generate an array of all possible 2D arrays consisting of 0s and 1s in JavaScript within a square 2D array. Essentially, this is similar to the question posed here: Make every possible combination in 2D array However ...

What are the steps to automatically populate the location or name in the trip advisor widget?

I have encountered an issue with my website where I have multiple hotel lists but the trip advisor widget only shows one. Is there a solution, such as a script or other method, that can use variables to automatically set the location or name in the widget? ...

How can I preloaded self-hosted fonts in Next.js without receiving a console warning for not using the resource within a few seconds?

I am working on a project in Next.js and I want to preload my self-hosted fonts. In my code, I have the following setup: Inside my _app.js file: <Head> <link rel="preload" href="/fonts/leira/Leira-Lite.t ...

Having difficulty in displaying database values in HTML modal using PHP

On my PHP page, I have a setup that displays data based on the fetched id from the URL. Everything is working smoothly, but when I click a button to show a modal with additional information, the modal appears blank. Here is the code snippet I am using: ...

Exciting effects activated by hovering on a button

I'm attempting to create an animated effect by having a rectangle expand over the button when hovered by the user. However, I am unsure how to achieve this and have hit a roadblock. Here's what I want: There's a button. There's a rect ...

"React and Next.js are causing a return value of undefined on

After spending a few hours working with NextAuth and utilizing the Twitter API for login and tweet searching, I have encountered a minor issue. Setting up most of the things was smooth, but I am facing some problems with fetching API routes on the client ...

React - Effective Ways to Update State Following an AJAX Call

I'm currently in the process of transitioning one page within my web application from using jQuery and Vanilla JS to utilizing React. However, I'm facing some challenges as React is still relatively new to me. On this particular page, I have an ...

Missing Ajax Functionality in Laravel Application

The code snippet below was created by me... <script> $('#spielAuswahl').on('change', function(e){ console.log(e); var spielID = e.target.value; //ajax $get.('/spieler?spielID=' + sp ...