When printing, the CSS for media print is not correctly displaying the table format

I have a basic table with a button underneath. This code snippet is located in the body section of my JSP file:

<div id="myDivForPrint">
            <table class="t1">
                <tbody>
                <tr>
                    <th>One</th>
                    <th>Two</th>
                    <th>Three</th>
                </tr>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                </tr>
                <tr>
                    <td>4</td>
                    <td>5</td>
                    <td>6</td>
                </tr>
                </tbody>
            </table>
        </div>
        <button onclick="printDiv()">Print</button> 

Here is the CSS code with @media rule designed to style the table. The CSS can be found in the head section of my JSP file:

    @media print,screen{
        table.t1 { 
                margin: 1em auto; 
                border-collapse: collapse; 
                font-family: Arial, Helvetica, sans-serif; 
                } 

            .t1 th, .t1 td { 
                padding: 4px 8px; 
                } 

            .t1 thead th { 
                background: #4f81bd; 
                text-transform: lowercase; 
                text-align: left; 
                font-size: 15px; 
                color: #fff; 
                } 

            .t1 tr { 
                border-right: 1px solid #95b3d7; 
                } 

            .t1 tbody tr { 
                border-bottom: 1px solid #95b3d7; 
                } 

            .t1 tbody tr:nth-child(odd) { 
                background: #dbe5f0; 
            } 

            .t1 tbody th, .t1 tbody tr:nth-child(even) td { 
                border-right: 1px solid #95b3d7; 
            } 

            .t1 tfoot th { 
                background: #4f81bd; 
                text-align: left; 
                font-weight: normal; 
                font-size: 10px; 
                color: #fff; 
                } 

            .t1 tr *:nth-child(3), .t1 tr *:nth-child(4) { 
                text-align: right; 
            }
        }
    </style>

Below is the JavaScript function used to print the div containing the table. It is placed in the body section of my JSP file:

<script type="text/javascript">
            function printDiv()
                {
                    var divToPrint=document.getElementById("myDivForPrint");                
                    newWin= window.open("");
                    newWin.document.write(divToPrint.outerHTML);
                    newWin.document.close();
                    newWin.document.focus();
                    newWin.print();
                    newWin.close();
                }

    </script>

The webpage appears well-formatted on screen. However, when I attempt to print the page as an XPS document by clicking the print button, all the CSS styling is not retained, resulting in a poorly formatted output with only the table content printed.

What could be causing this issue? I am using IE8 and cannot switch to a different browser or newer version of IE.

Answer №1

To customize the appearance of your table for both screen and print media, you can define different styles in your CSS stylesheet.

@media screen
{
    table.test {
        font-family:"Times New Roman",Georgia;
        font-size:10px;
        // additional styles for screen
    }
}

@media print
{
    table.test {
        font-family:Verdana, Arial;
        font-size:10px;
        // additional styles for print
    }
}

When printing the table, only the styles specified for print media will be applied.

Check this out for more information

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 store types in a TypeScript-based React/Next application?

I'm currently in the process of setting up a Next.js page in the following manner const Index: NextPage<PageProps> = (props) => { // additional code... Prior to this, I had defined my PageProps as follows: type PageProps = { pictures: pi ...

What is the best way to set up a list of states in React using hooks?

Suppose I have a variable, n, which can take on any value. My objective is to generate n input fields while maintaining the state of each input. However, I am currently facing challenges in figuring out how to achieve this. For instance, when n = 3, my des ...

Right-align the span and vertically align the header to the left

Seeking guidance on aligning a span to the right of a div, where the span is nested within a button. Although I have successfully achieved the above, I am encountering difficulties in vertically aligning the header while also keeping it to the left. .s ...

Ways to adjust timestamps (DayJs) by increments of 1 minute, 5 minutes, 15 minutes, 30 minutes, and more

Currently, I am exploring time functionality within React Native by utilizing DayJs. I have noticed a slight inconsistency when comparing 2 different points in time to calculate the time difference. Typically, everything works smoothly such as with 10:00 ...

Looping through data in Vue.js with a specific condition

There is an object structured like this: groupedContacts: { 4: [ {name: 'foo'}, {name: 'bar'} ], 6: [ {name: 'foo bar'}, ] } Additionally, we have another array: companyList.models: models: [ ...

Converting a variable with a cloned object from jQuery to vanilla JavaScript

const clonedBoardCode = $('#board_code').contents().clone(false); alert( clonedBoardCode.filter('div').eq(x).children().eq(y).text() );//need to fix this I am looking for a code similar to this $('#board_code_dup > div') ...

How can you tell if a contenteditable div is currently in focus?

Essentially, my setup consists of: HTML: <div class="div1"> <div class="as-text-box" contenteditable="true"></div> </div> CSS: .div1{ position:absolute; height:50px; width:200px; background:white; border:1px solid #c ...

Steps for importing a json file into Chrome

Inside my file named data.json, there is a JSON object structure: { "k": : "..some object...", "a": [ "...", "bbb" ] } When working with Node.js, I can easily import this data into a variable using: let data = require("./data.json"); However, how can I ...

essential elements for mapping an array using typescript

Struggling to iterate through an array of objects, each with a unique id created by uuidv4(), resulting in a string type. TypeScript is giving errors (( Type 'String' is not assignable to type 'Key | null | undefined')) due to the &apos ...

Styling for Print Media: Adjusting the horizontal spacing between inline elements

I have been developing a custom AngularJS point-of-sale (POS) system that requires printing receipts upon completing a sale. To achieve this, I am using ng-print to print out a sales summary displayed within a specific div element after hiding all other un ...

Navigating through an array of latitude and longitude pairs during an AJAX request

Just starting out with PHP/AJAX and I could use some guidance. Currently, I have a leaflet map where I'm attempting to link two AJAX calls together. The initial AJAX call retrieves data based on a selected country ISO code. Subsequently, I've ut ...

Callback function in Aframe not triggering

My camera motion callback function in aframe is not being called. I have registered the component like this: window.onload = function () { AFRAME.registerComponent('listener', { tick: function () { console.log("TICK IS CALLED"); ...

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...

Prevent form submission when processing is in progress

I've got this code working perfectly: $(function() { $("input,textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events ...

Utilize the dropdown menu across all table cells in a table

My p-table has a unique feature - the last column contains three dots that trigger a dropdown menu when clicked. The only issue is that the fixed position of the dropdown menu does not align properly with the td element in each row. Check out the HTML cod ...

MERN Stack - Table Ordering Solution

After spending countless hours trying to order the list items in the table, I am still unable to figure it out. The data is being fetched from a MongoDB using Axios. I am currently working with MongoDB Express React and NodeJS If you'd like to check ...

Integrating AJAX functionality into a PHP webpage with various options selected

I'm a beginner coder looking for some assistance. Currently, I have a page with four select inputs, each with two options. When all selections are made and the submit button is clicked, a specific song out of 16 based on the choices will play in an a ...

A guide to smoothly transition box-shadow with jQuery's addClass() function

UPDATED I have a div with the class .shadow-circle-lg: <div class="shadow-circle-lg"></div> To add a different border styling to the div, I am using another class called .circle-highlight: .circle-highlight{ box-shadow: 0 0 0 1px rgba(0,0, ...

Exploring the Benefits of Using a Try-Catch Block for Creating an Audio Element

While reviewing the Jbox plugin code, specifically focusing on the audio addition part, I encountered the following snippet of code: jBox.prototype.audio = function(options) { options || (options = {}); jBox._audio || (jBox._audio = {}); // ...

Tips for utilizing sendToDevice multiple times in a function return value

In my Firebase Cloud Functions script, I have successfully implemented sending push notifications to users using a specified set of token arrays returned by a function: return getTokens(array1).then(tokens => { return (admin.messaging().sendToDevice( ...