skip to Main Content

I am trying to create some elements to print and use the CSS of a stylesheet I already have, but the style is not applied:

let printWindow = window.open('', 'Print', 'height=600,width=800');
printWindow.document.write('<html><head><title>Print</title>');
printWindow.document.write('<link rel="stylesheet" href="https://my.website/css/mystylesheet.css" type="text/css" />');
printWindow.document.write('</head><body>');
printWindow.document.write('<p id="test">Hello</p>');
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();

And in the css file:

#test {
  color: green;
}

But it doesn’t work. Why?

Update: The following did not work either:

let printData = '';
printData += '<link rel="stylesheet" href="https://my.website/css/mystylesheet.css" type="text/css" />';
printData += '<p id="test">Hello</p>'

let printWindow = window.open('', 'Print', 'height=600,width=800');
printWindow.document.write(data);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();

2

Answers


  1. I write the same code but delete printWindow.close() to see the output

            function test(){
                let printWindow = window.open('', 'Print', 'height=600,width=800');
                printWindow.document.write('<html><head><title>Print</title>');
                printWindow.document.write('<link rel="stylesheet" href="./css/mystylesheet.css" type="text/css" />');
                printWindow.document.write('</head><body>');
                printWindow.document.write('<p id="test">Hello</p>');
                printWindow.document.close();
                printWindow.focus();
                printWindow.print();
            }
    #test {
      color: green;
    }
    
    h1{
      color: red;
    }
    <h1 href="#" onclick="test()">test</h1>

    this the result when I clicked on ‘test’ word:
    result image

    So make sure that you put the right path to the css file

    Login or Signup to reply.
  2. You need to give the css time to load. It won’t need much but this snippet gives it generous time just to prove a point.

    <script>
    let printData = '';
    printData += '<head><link rel="stylesheet" href="mystylesheet.css" type="text/css" /></head>';
    printData += '<body><p id="test">Hello</p></body>'
    
    let printWindow = window.open('', 'Print', 'height=600,width=800');
    printWindow.document.write(printData);
    printWindow.document.close();
    printWindow.focus();
    function myprint() {
      printWindow.print();
      printWindow.close();
      }
    setTimeout( myprint,  1000)
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search