Having trouble displaying DIV Content with CSS through printing

<script type="text/javascript">
    function PrintElem(elem) {
        Popup($(elem).html());
    }
    function Popup(data) {
        var mywindow = window.open('', 'mydiv', 'height=550,width=750');
        mywindow.document.write('<html><head><title></title>');
        mywindow.document.write('<link rel="stylesheet" href="~/Content/Site.css" type="text/css" media="print" />');
        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;
    }
</script>

My JavaScript code successfully prints the DIV, but I am facing an issue with loading CSS. To test this, I set a pink color which is not reflecting in the print output. Below is my CSS:

@media print {
    .mydiv {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
        color:pink;
    }
}

Answer №1

One possible issue could be that your CSS is attempting to target the NAME of the WINDOW instead of an object within it. Without knowing what data contains, consider making this adjustment:

replace with

mywindow.document.write("<div class='mydiv'>" + data + "</div>");

Answer №2

My approach to a task similar (in fact identical) to this involved the following steps:

To start, I opened the "Print Version" document (an empty template) and within its onload event, I retrieved the necessary div from its parent.

<!-- parent doc -->
<input type="button" value="Printer Version" onclick="doIt()" />
<div id="divPrint" style="display:none;">
   <iframe id="frPrint"></iframe>
</div>
<script>
function doIt(){
   document.getElementById('divPrint').style.display = '';
   document.getElementById('frPrint').src = "print.html?a=" + Math.random();//to avoid caching
}
function getContent(){
   return document.getElementsById('divData').innerHTML;
}
</script>

<!--print.html -->
...
<script type="text/javascript">
    window.onload = function () {
        var a = this.parent.getContent();
        document.body.innerHTML = a;
    }
    function printMe() {
        window.print();
    }
</script>
<style type="text/css">
    .right
    {
        float: right;
    }
</style>
<link href="/Styles/print.css" media="print" rel="stylesheet" />
...

Answer №3

There appears to be a missing reference in your code that links the CSS with the HTML tag. Consider modifying your code snippet like so:

myWindow.document.write('</head><body><div class="myDiv">');
myWindow.document.write(data);  
myWindow.document.write('</div></body></html>');

Best regards

Answer №4

@media print is effective only when you invoke the window.print() function directly. In this situation, a popup is being created and your HTML content is being placed inside it. Therefore, all CSS styles must be included in a specific way. Take a look at the following example.

$(".printtt").on("click",function(e){ 
                var mywindow = window.open('', 'my div', 'height=400,width=600');
                                    mywindow.document.write('<html><head><title>my div</title>');
                                    //mywindow.document.write("<link rel=\"stylesheet\" href=\"css/bootstrap.min.css\" type=\"text/css\" media=\"print\" />");
                                    //mywindow.document.write("<link rel=\"stylesheet\" href=\"css/sb-admin.css\" type=\"text/css\"  />");
    mywindow.document.write('<style>.printtt{color:pink;}</style>');
                                    mywindow.document.write('</head><body >');
                                    mywindow.document.write($("#page-wrapper").html());
                                    mywindow.document.write('</body></html>');
                    
    setTimeout(function () {
                            mywindow.print();
                        },1000);
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="aaaaa">
    </div>
    <div id="page-wrapper">
    <a href="javascript:void(0);" class="printtt">Print</a>
    </div>

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

Increase and decrease thumbnail size using an onclick event

I've been experimenting for hours to try and create a functionality where the thumbnail image on my HTML page enlarges when clicked, and then shrinks back down when clicked again. However, I'm encountering an issue where it only gets bigger and d ...

How to Customize the Navbar Position in Bootstrap 3 when the Brand/Logo is Collapsed

I am currently in the process of creating my first website and experimenting with the Bootstrap 3 framework. The navbar I have selected is designed to adjust based on screen size, collapsing into a small button for use on tablets and mobile devices. Howe ...

Styling with CSS: A guide to reducing paragraph margins within a div element

My current project involves using javascript to dynamically insert paragraphs inside a div element. Essentially, the script grabs the value entered into an input form when a button is clicked and adds it as a new paragraph within a specific div. However, I ...

I'm struggling to find a way to showcase my JSON data in HTML. Update: I have a clear vision of how I want it to look, but I'm struggling to display it in any format other than raw JSON

I've been trying to figure this out for hours, scouring every resource I can find, but I'm stuck. I've left the API URL in there, so feel free to take a look (it's public). If my message doesn't make sense due to exhaustion, please ...

What are the drawbacks of incorporating side effects into JavaScript constructors?

In my coding, I often utilize a design pattern similar to the concept of custom objects. However, JSLint disapproves of code constructs like this: function MyClass() { this.init(); } new MyClass(data); The reason being that the newly created object is d ...

Uploading files seamlessly without the need for refreshing the page

On my HTML page, I have a form input that allows users to upload a file. Here is the code snippet: <form action = "UploadFile.jsp" method = "post" target="my-iframe" enctype = "multipart/form-data"> <input type = "file" name = "file" ...

Enable row selection in UI-Grid by clicking on a checkbox with AngularJS

I am a newcomer to angular js and I am looking to have the checkbox automatically selected when clicking on a row to edit that specific cell. I have implemented a cell template to display the checkbox in the UI-grid, but now, when I select a row, the row i ...

Unable to transfer files, encountering issues with PHP and AngularJS integration

I am currently working on uploading files using both AngularJS and PHP. For the AngularJS part, I am utilizing angular-file-upload from https://github.com/danialfarid/angular-file-upload. I suspect that the issue lies in my PHP code, as it fails to move ...

Transferring information from a Jade file to a Node.js server

I'm currently working on creating a data object within my Jade view page that will be used in my server-side JS. The data object involves dynamic HTML generation that inserts input boxes based on user input. function addDetail() { var det ...

Managing paths for JavaScript and CSS scripts using Jquery Ajax for both direct and remote access

When using Jquery Ajax, I have a main entry script called "index.php." This script allows the user to request "/folder2/index.php" using ajax. I also use the same path "/folder2/index.php" for direct access. However, because of the ajax call, I need to ...

How can I detect a click event on an SVG element using JavaScript or jQuery?

Currently, I am developing a web application that utilizes SVG. However, I have encountered an issue: I am struggling to add a click event to each element within the SVG using jQuery. The problem arises when attempting to trigger the event; it seems like t ...

Utilizing Symfony and Star Ratings: Incorporating jQuery Input with Symfony2 for Maximum Impact

Currently using symfony2 and interested in implementing a star rating widget... Utilizing jquery as well... If anyone has insight on how to achieve this, please share your knowledge! Appreciate it, Sam ...

Instead of using colons, display the separation of hours, minutes, and seconds with underscores

Currently, I am utilizing moment.js to retrieve the present date and time with the intention of formatting it in the specific format below 'MMMM Do YYYY, h:mm:ss a' Unfortunately, the problem arises as the delineation between hours, minutes, and ...

React animation failing to render underline animation

After tinkering with the underline animation while scrolling down on Codepen using Javascript, I successfully implemented it. You can check out the working version on Codepen. This animation utilizes Intersection Observer and a generated svg for the underl ...

Is there a way to address this scrollbar issue without relying on HTML?

Currently, I am working on a website where the only customization allowed is related to CSS. While I've been able to make progress, I've encountered an issue with the scrollbar placement. The scrollbar is extending beyond the boundaries of the di ...

Inaccuracies arise when trying to interpret a JSON string as an object

I have tried various solutions found on stack overflow, but none of them seem to work for me. I am attempting to call an asmx web service using jQuery. Below is my code: <script type="text/javascript"> $(document).ready(function () { ...

Nested jQuery UI Selectable causing propagation problems

My issue lies in the nested jQuery UI selectable functionality. When I click on Item 1, it is selected as expected. However, when clicking on Item 111 or 1111, it selects all the way up to Item 2. What I require is for only the element that is clicked on t ...

Adding setTimeout within the Axios Scope can enhance the functionality and performance of your

Show an alert in the catch block of Axios. The issue at hand: Error message does not disappear after the specified time when using setTimeout. ...

If the div element contains an <li> element, jQuery animate() will not function properly

Initially, my div was animating perfectly. However, when I inserted a list inside the divs, the animation only became visible once it reached the bottom of the height of the lists. To trigger the animation, click on the Products option in the top menu. T ...

Techniques for sending PHP variables to window.location using JavaScript

How can I successfully include a PHP variable in a JavaScript window.location function? The current code snippet below does not seem to be working for me. echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.&apos ...