Is there a way to maintain the original style of an HTML element when printing it?

When attempting to print an HTML element using window.print();, the original style is not preserved. How can this issue be resolved?

printInvoice() {
    var mywindow = window.open("", "PRINT");

    mywindow.document.write("<html>");
    mywindow.document.write("<body>");
    mywindow.document.write($("#html2pdf")[0].outerHTML);
    mywindow.document.write("</body></html>");

    mywindow.document.close();
    mywindow.focus();

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

    return true;
  }

CSS for printing:

@media print {
  #invoice {
    padding: 30px;
  }

  .invoice {
    position: relative;
    background-color: #fff;
    min-height: 680px;
    padding: 15px;
  }

  .invoice header {
    padding: 10px 0;
    margin-bottom: 20px;
    border-bottom: 1px solid #3989c6;
  }
}

Answer №1

In order for rendering to occur on a web page, the presence of html, css, and js is essential. These three components work together to create the visual display of content.

If your css and js are located in the head section of the document, you can execute the following function:

generateReport() {
    var newWindow = window.open("", "PRINT");

    newWindow.document.head.append(document.head)
    newWindow.document.body.innerHTML = $("#reportContent")[0].outerHTML;
    newWindow.focus();
    newWindow.print();
    newWindow.close();

    return true;
  }

Answer №2

Appreciate the assistance, below is the solution that worked for me:

function printInvoice() {
    var mywindow = window.open("", "PRINT");

    mywindow.document.write("<html>");

    mywindow.document.write(document.head.outerHTML);
    mywindow.document.write("<body>");
    mywindow.document.write(document.getElementById("html2pdf").outerHTML);
    mywindow.document.write("</body></html>");

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

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

    return true;
}

To style your print page in your css file, use the following:

@media print {...} 

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

AngularJS ng-onclick method sending value to Thymeleaf

I am facing an issue with the integration of Thymeleaf and AngularJS. Below is the Thymleaf page I have: <div ng-controller="ctrlsubcomment" > <div class="media" th:fragment="comments" th:each="newsComment : ${comments}"> <img ...

Error: The property 'rows' cannot be read because it is undefined

While working through the steps outlined in Getting started with Postgres in your React app, specifically when processing and exporting the getMerchants, createMerchant, and deleteMerchant functions, I encountered an error that says: "TypeError: Cannot rea ...

I am interested in retrieving all users along with the places they have created using virtual population

const fetchAllUsers = async (request, response) => { try { await User.find({}).populate('place').exec(function(err, data) { console.log(data.places) console.log(data) res.json(&quo ...

Mocking a function from within the method under test

I need to run tests on a method in my code that runs a series of functions, one of which sends an email. Is there a way to prevent this function from sending emails during testing? I want to avoid using conditional statements like the one below in my cod ...

Dealing with Unwanted Keys When Parsing JSON Objects

Struggling with parsing a list of Objects, for example: After running the code JSON.parse("[{},{},{},{},{}]"); The result is as follows: 0: Object 1: Object 2: Object 3: Object 4: Object 5: Object Expecting an array of 5 objects like this: [Object,Ob ...

What is the best method for adding lengthy text into a mySQL database with PHP?

My current setup involves using a basic HTML form and PHP to insert strings into a MySQL Database. This method works well for shorter strings, but I've encountered issues with longer strings. Interestingly, when using phpmyadmin, I can successfully i ...

Investigating Javascript compatibility problems with Firefox 4

In FF3.X and IE7 to 9, the code below is functioning correctly, but in FF4, there seems to be an issue. The following code is used in two different locations within my file: var args = "method=getoptions"; args += "&dr ...

Tips for maintaining an open sub menu while hovering over a link

I'm currently working on a navigation menu using jQuery that includes categories, subcategories, and their subsequent subcategories. However, I am facing some issues with it not functioning as intended. To avoid cluttering this space with excessive HT ...

Strategies for addressing frontend challenges in Bootstrap 4

Currently, I am enrolled in a program to enhance my knowledge of Angular and have encountered a challenge. My project is utilizing the most recent version of bootstrap, which is bootstrap 4. However, I am facing issues with the main page not functioning co ...

Instructions on how to dynamically show specific text within a reusable component by utilizing React and JavaScript

My goal is to conditionally display text in a reusable component using React and JavaScript. I have a Bar component that I use in multiple other components. In one particular ParentComponent, the requirement is to show limit/total instead of percentage va ...

Understanding how to incorporate a URL parameter using HTML and Javascript

I have a web application section where users can search for locations on a map successfully. However, I'd like the text of the location to be displayed in the URL so that users can easily copy and share it for consistent searches. What is the most ef ...

Comparison of Static Site Generation (SSG) with Server-Side Rendering and Client-Side Rendering

The lack of concrete information surrounding the inner workings of Client-Side Rendering (CSR), Server-Side Rendering (SSR), and Static Site Generation (SSG) is truly perplexing to me. Despite numerous articles that vaguely touch on these concepts, I have ...

What is the best way to extract the text from the initial column of a table?

I came across a table on a webpage (specifically, http://developer.chrome.com/extensions/api_index) containing various method names in Stable APIs. My goal is to create an array that includes all the entries from the first column of the table. Is there a ...

Move the element to the top within the navigation bar

I am currently enhancing the appearance of my navbar by adding two "Stripes" on top. I am using bootstrapv4 as a base, but facing an issue where bootstrap centers my decorations. How can I prevent this? Below is a simplified version of my code: HTML: &l ...

Is it possible to create a Vue JSX component inside a Single File Component using the <script setup> syntax and then incorporate it into the template of the S

I am impressed by how easily you can create small components within the main component file in React. Is it possible to do something similar with Vue 3 composition API? For example: Component.vue <script setup> const SmallComponent = <div> ...

`Achieving object placement on top of another object in ThreeJS`

Being new to ThreeJS, I am seeking help with a basic question. I have loaded multiple GLTF files into my scene and I need to position one object on top of another (but the position should be adjustable later on) For instance: https://i.sstatic.net/oJq1BIi ...

Implement the CSS display flex property for more flexible layouts

After working on some HTML code, I found the following: <section class = "personal_proyects"> <article> <div class = "personal_details"> <h3>Canal YT: Codigo RM</h3> < ...

Troubleshooting Checkbox Problem in a Perl Script Triggered by an HTML Form

Prior to presenting the inquiry, a few notes must be made clear: As someone who is not a programmer, I have been given the challenging task of making this work. My knowledge is limited to the basics, with minimal experience from previous dabbling. My skill ...

How does the <link type=“”> affect your document?

I understand that this tag specifies the file type you are linking to (usually "text/css") for . But what is the reason behind including this information? ...

Tips for resizing the h1 tag on a mobile device using Bootstrap 2.3

As a beginner in using bootstraps, I encountered an issue. I have placed an h1 tag at the beginning of my website and styled it to look great on desktop. However, when I view it on a mobile device, the font size is too large. This goes against the princi ...