How to render a div in HTML with full CSS styling applied

I'm currently working on a project using asp.net MVC. My goal is to print a div with all the CSS styles applied, which may contain one or more nested divs. Despite trying various JavaScript print codes, I have not been successful. The page I want to print is shown here: Click here to view the page. Specifically, I only want to print the section below the input region that contains the details. However, whenever I attempt to use the JavaScript print method, the table view disappears. The print preview I see is depicted here: Click here to view the print preview page. I have attempted multiple methods, but none have worked. Any assistance would be greatly appreciated. Thank you in advance. Below are the front-end code files:

saleInvoice.cshtml

<script>
 function refresher() {
        $('#si, .si').load('/TallySet/cart');

    };

    function printDiv(divID) {
        debugger;
        var printContents = document.getElementById(divID).innerHTML;
        var originalContents = document.body.innerHTML;

        document.body.innerHTML = printContents;

        window.print();

        document.body.innerHTML = originalContents;
    };
</script>
<div class="col-lg-12 popblk">
    <p>New Sales Invoice</p>
</div>

<div class="col-lg-12" style="background-color:white">
    <div class="row">
        <div class="col-lg-2">
            <p>Customer : </p>
        </div>

        <div class="col-lg-4">
            @Html.DropDownList("customers")
        </div>
    </div>

    <div class="row">
        <div class="col-lg-4">
            @Html.DropDownList("items")
        </div>
        <div class="col-lg-4">
            @Html.TextBoxFor(x => x.quantity)
        </div>
        <div class="col-lg-2">
            <button value="Add to cart" onclick="addToCart()">Add to cart</button>
        </div>
        <div class="col-lg-2">
            <button value="Refresh" onclick="printDiv('si')">Refresh Cart</button>
        </div>
    </div>

    <div class="row" id="si" style="margin-left:50px;">
        @{Html.RenderAction("cart", "TallySet");}
    </div>

    <div class="row" style="background-image:url('../../viewData/sale_footer.png')">

    </div>
    <button class="rButtonCancel" value="X" data-dismiss="modal" onclick="listVoider()">X</button>
</div>

cart.cshtml

@model IEnumerable<Fast_Tally_Accounter.Models.salesCart>
<img src="~/viewData/sale_head.png" />
@if(Model!=null)
{
    foreach(var v in Model)
    {
        <div class="row" style="background-image:url('../../viewData/sale_row.png'); background-repeat:no-repeat;margin-left:0px;margin-bottom:0px">
            <div class="col-lg-2">
                <p>@v.quantity KG</p>
            </div>

            <div class="col-lg-4">
                <p>@v.itemName</p>
            </div>

            <div class="col-lg-1">
                <p>@v.itemPrice</p>
            </div>

            <div class="col-lg-1">
                <p>@v.itemTotal</p>
            </div>
        </div>
    }
}

<div class="row" style="background-image:url('../../viewData/sale_footer.png'); background-repeat:no-repeat; margin-left:0px; height:120px">

    <div class="row myRow" style="height:20px; margin-left:536px; margin-bottom:2px; margin-right:0px" id="myRow">
        <p>@ViewBag.dt</p>
    </div>

    <div class="row myRow" style="height:20px; margin-left:536px; margin-bottom:2px; margin-right:0px" id="myRow">
        <p>Daniyal humayun</p>
    </div>

    <div class="row myRow" style="height:20px; margin-left:536px; margin-bottom:10px; margin-right:0px" id="myRow">
        <p>@ViewBag.qt</p>
    </div>

    <div class="row myRow" style="height:20px; margin-left:536px; margin-bottom:0px; margin-right:0px" id="myRow">
        <p>@ViewBag.pr</p>
    </div>

</div>

Answer №1

There are several concerns to address in this situation. Firstly, it is important to note that you are not utilizing an actual table but rather utilizing Bootstrap's grid styles to mimic a table. Using a traditional HTML table would not only provide consistency but also improve accessibility.

Secondly, the "borders" of your "table" are created using background images. While Chrome may allow users to print background images, this is not the default setting and other browsers may not support this feature. As a result, this method may not be effective in all scenarios.

Thirdly, when printing, the contents of this div are replacing the entire HTML document, including any stylesheets present. This outdated approach eliminates important elements such as the Bootstrap stylesheet. Nowadays, it is recommended to use print-specific styles to hide elements not intended for printing, like a page header, as shown in the example below:

@media print {
    #Header { display:none; }
}

This same method can also be used to adjust styles for printing, such as changing the font size. By adding body { font-size:12pt; } within this block, you can customize the print layout further.

Lastly, the only necessary JavaScript function is window.print(). By incorporating this into your print button, you can rely on the print-specific CSS to make any necessary modifications for the print version.

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

Click to switch divs

I am struggling and in need of help. I have been trying to rotate divs on click using jQuery, which was successful until I had two sets of divs that needed to be rotated independently on the same page. When clicking on the arrows to rotate the content in t ...

Display resize grip when hovering

Is there a way to make elements resizable using resize: both, but only show the corner handle when hovering over the element? https://i.sstatic.net/cGIYf.png I am looking for a solution to display that specific handle only on hover. ...

Retrieve JSON data by making a POST request to a website's API

Can you help me retrieve Json data from a website API using JavaScript? I'm trying to fetch quotes from the following website: for my quotes generator page. While I have some understanding of making GET requests, it seems that this API requires POST ...

Activate validation when the scope of a custom validator is modified

Consider a scenario where we have a custom validator with an input as the attribute's value. app.directive('inputRequired', function() { return { require: 'ngModel', scope: { inputRequired: '=& ...

Unit testing an API built with Express and Mongoose using Jest

I have decided to implement a TDD approach for a user API that I am working on. Specifically, I am looking to add unit tests for two functions: userRegister and userLogin. Here is the code snippet from my app.js: 'use strict' const express = r ...

Deactivate background hover effects for bar charts in Recharts

Is there a way to disable the gray background that appears when hovering over bar charts in Recharts? I'm using version 1.4.1 and my code looks like this: import React from "react" // Recharts import { Bar, BarChart, CartesianGrid, ResponsiveContain ...

Searching using wildcards in a single text field in MySQL using PHP on a web page created with

Recently, I acquired some PHP scripts from a coworker that includes a search functionality for the "Notes" text field in a database named "Sheep". The search is conducted through a text box: https://i.sstatic.net/NbwMF.png Here is the code for the search ...

What steps can I take to guarantee that my grid always accommodates its child without being too small?

My current setup involves utilizing a grid layout to arrange elements in the z-direction. However, I have encountered an issue where a child element extends beyond the boundaries of the grid element: #z-stack { display: grid; border: 5px solid ...

passport.js and express: TypeError - Router.use() must be given a middleware function, but instead received a ' + gettype(fn)

I encountered an error while using passport.js with Express.js TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) This issue arose from the following code: passport/local.js var LocalStrategy = require("passport ...

Activate a module within a Vuex action only upon dispatching

Is there a way to import a package for use in a Vuex Action only when the Action is dispatched, in order to reduce the size of my entry bundle? Here's what I've tried: export const actions = { async createNewBin(store, bin) { const fireba ...

My attempts to use media queries are being ignored by Internet Explorer

While other browsers recognize and function properly, it seems like IE is not recognizing my media queries. Could there be something wrong with my code? I've created a similar design before without any issues, so why is this one causing problems? Her ...

Have you ever created a CSS class that you've had to reuse multiple times?

They always told me to consolidate repeated properties in CSS into one rule, like the example below (please forgive the poor example). I typically see this: .button, .list, .items { color: #444; } Having multiple rules like this can create a lot of clut ...

Having trouble with integrating Firebase and Vue database

While attempting to integrate Firebase with my Vue 4 application, I encountered the following error: Uncaught TypeError: db__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function The versions I am using are: "firebase": "^9.0.0&qu ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

JQuery is unable to initiate a keyup event

I am currently utilizing jQuery in a web application. On one of my pages, I have set up an event listener for keypresses as shown below: document.addEventListener('keyup', function (event) { event.preventDefault(); var key = event.k ...

What is the most efficient way to send an email with all fields from a massive PHP-enabled web form containing approximately 75 fields?

In the past, I have successfully created Ajax-enabled contact forms with around 12 fields. Now, I am facing a new challenge - developing a PHP-enabled web page for job applications that includes approximately 100 fields. My previous method of sending requ ...

What is the best method to dynamically assign a class to a TD element in a data table when adding

I am looking to apply a class to the td element when receiving data from an ajax call Here is the default HTML code snippet <tr> <td>@fisrt.System_Code.Code</td> <td>@fisrt.System_Code. ...

The date formatting issue persists in jqGrid 3.5 as the dates are not being displayed correctly

I have been experimenting with jqGrid 3.5.2 and currently, I am extracting data from a local JSON object. Upon researching date formatting, I realized that the dates in my JSON were not properly formatted, so I converted them all to ISO8601Long format. Now ...

Progress bar displaying during Ajax request

I'm currently working on an Ajax request that uploads images to the Imgur API and I want to implement a progress bar to show users the upload progress. I found some guidance in this thread, but it seems to display only 1 and stop working. This is the ...

What is the best way to import a background image from a different webpage?

I'm working on a project where I need to dynamically load content from other pages using jQuery. Here is the code snippet: $('#newPage').load('example.html' + ' #pageContent', function() { loadComplete(); }) ...