Display the HTML/CSS layout following the JavaScript window.open action

Encountering issues with printing output in an opened window using JavaScript. I'm creating a new document through window.open and including CDN links to Bootstrap files. While everything appears fine in the opened window, when attempting to print (XPS document writer), some styles such as .btn-group are present but layout or inline styles are missing.

Question: How can I print exactly what I see in the new window?

In the CDN link, I have specified media='all' (also tried media='print').

Working example: Check out the jsfiddle here

$('#openNewWindow').click(function(e){
    var printWindow = window.open('', '_blank', 'width=1100, height=500');

    printWindow.document.open();
    printWindow.document.write("<!doctype html><head><title>Title</title>");

    var cdn = `
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" media="all" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <!-- Optional theme -->
  <link rel="stylesheet" media="all" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">        
    `;

    printWindow.document.write(cdn);        
    printWindow.document.write("</head><body>");

    content = `
        <div class="container-fluid">
            <div class="row">
              <div class="col-md-8" style="background-color: red">.col-md-8</div>
              <div class="col-md-4" style="background-color: blue">.col-md-4</div>
            </div>            
        </div>

    <div class="btn-group" role="group" aria-label="...">
      <button type="button" class="btn btn-default">Left</button>
      <button type="button" class="btn btn-default">Middle</button>
      <button type="button" class="btn btn-default">Right</button>
    </div>
    `;

    printWindow.document.write(content);        
    printWindow.document.write('</body></html>');

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

    setTimeout(function () {
        printWindow.print();
    },1000)

});

Answer №1

It's strange that Bootstrap 3 doesn't seem to work with the XS size for printing. You may need to adjust your popup to use col-xs-* or find a CSS solution for this issue.

Answer №2

If your body has a default auto width dimension and only contains floating/unrestricted divs, they will be laid out for printing in a square manner according to the browser's implicit style.

To ensure that the layout is correct, you should either specify a fixed width for the body and place the floated/positioned unrestricted divs inside it, or define widths for the divs themselves.

If there are additional styles that you do not want to affect the main document, such as a fixed body width, you can create a separate print-specific style document like this:

<link href="printspecific.css" media="print" rel="stylesheet" /> 

Experiment with different styles until you achieve the desired layout for the printed document. It is likely that setting a defined width for the body element will help in achieving the correct appearance.

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

Certain HTML code on a webpage is currently inaccessible to me

Struggling with web scraping on a webpage due to inaccessible code. The part of the page's code that remains out of reach is only accessible through an anchor tag, with the following html: <a class="MTLink" href="#d192633539-47" title="example" &g ...

What is the best way to split an input field into distinct fields for display on the screen?

Take a look at this image: https://i.stack.imgur.com/LoVqe.png I am interested in creating a design similar to the one shown in the image, where a 4 digit one-time password (OTP) is entered by the user. Currently, I have achieved this by using 4 separate ...

Duplicate label issue with 'No files chosen' message on Bootstrap form control

After migrating to webpack for managing our assets (js, scss, ...), everything seemed to be working smoothly. However, we encountered a minor issue where the input label behind the file-selector-button is overflowing with its neighbor, as shown in the exam ...

Retrieve information using server-side rendering

I'm faced with a situation where my page utilizes query parameters to fetch data via SSR. The challenge arises when these query parameters frequently change, triggering a re-fetch of the data using SSR despite there being no client-side data fetching ...

Encountering a Selection Issue with IE8

I am encountering an issue with my script that involves a form with two select elements for region and state, allowing users to filter states based on the selected region. Everything works smoothly except for one problem - when testing in IE8, I receive th ...

When <li> elements are rendered via ajax, it is not possible to attach JavaScript Events to them

Hey there, I've got a drop down menu that's being shown using UL and LI tags. This is generated by a PHP script that echos out: '<li id='. $value .'>'.$value.'</li>' The JQuery function below works perf ...

Issues with border/padding and overlay in Packery Grid Layout

After spending some time working on a grid layout using the metafizzy isotope packery mode, I have encountered a few issues. To illustrate my problem, I have provided a link to a codepen below: http://codepen.io/anon/pen/EgKdpL Although I am satisfied wi ...

Encountered an error while running npm run dev on a NextJS application due to an

Upon running the npm run dev command, the next app is displaying an error message: $→mmoLD;%g?wŷ↓▬ovH0a5*ؒl͛Siy☺rO7%L]%∟hk ^ SyntaxError: Invalid or unexpected token at wrapSafe (internal/modules/cjs/loader.js:988:16) at Module._comp ...

Displaying one out of two elements when the button is clicked

Trying to implement two buttons on the parent component, each displaying a different component - one for itemlist and the other for itemlist2. Struggling to get it right, even after following an example at https://codepen.io/PiotrBerebecki/pen/yaVaLK. No ...

What could be causing my selenium tests to fail on travis-ci even though there have been no code changes, when they are passing successfully

I'm facing a tough challenge trying to troubleshoot a selenium test that passes when run locally but not on travis. Reviewing the travis build logs, I noticed that the test was passing in build #311 but started failing at build #312. It seems like th ...

Is there a way to view the contents of the dev server once it has been bundled by webpack?

From my understanding, webpack in dev mode stores all imported files in a certain location and then serves the bundle.js file to the client. If the code inside bundle.js requests a CSS file, the css-loader should have already been configured to provide t ...

Accessing the next and previous elements using jQuery

Aug: <input type="text" value="100000" name="targetMonth_8" id="targetMonth_8" class="targetMonth" disabled> Sep: <input type="text" value="100000" name="targetMonth_9" id="targetMonth_9" class="targetMonth" disabled> Oct: <input type="text" ...

What causes the offsetWidth attribute to be zero in an array of elements within the DOM?

I am encountering an issue with a script that sets widths for certain elements in the Dom. Specifically, when I use the code var elements = document.querySelectorAll("p.caption"), the first 12 elements display the correct offsetWidth, but the remaining hal ...

Best method for reusing a component in React?

Here is a simplified code featuring a reusable button component: import React from 'react' import styles from './Button.module.scss' const Button = (props) => { return ( <button type={props.type} className={styles.btn} onC ...

gh-pages: Images that should not be cached

Every time my build server completes a new build, it automatically uploads a pass/fail graphic to the gh-pages branch. I'm looking to showcase this graphic on my project's page. Unfortunately, it appears that gh-pages is caching the image. Any s ...

Having trouble getting @media queries to work effectively across various screen sizes

Currently, I am using Sass with Bootstrap and facing some challenges when implementing different media queries. Despite most discussions revolving around CSS problems only, I am uncertain of the source of my issue and how to effectively address it. The sty ...

The foundation grid system is experiencing difficulties when implemented on an Angular form

After successfully installing Foundation 6 on my Angular project, I am facing an issue with the grid system not working properly. Despite numerous attempts to troubleshoot and debug, I have not been able to resolve this issue. If anyone has any insights or ...

Can content be easily added to the header section of numerous HTML files simultaneously, eliminating the need to access each file individually?

I'm facing a challenge where I have to include a stylesheet in numerous HTML files. It seems like such a tedious task to do it manually for each file. Are there any tools or solutions available that can assist me with this process? Or perhaps there ar ...

The current context for type 'this' cannot be assigned to the method's 'this' of type '...'

Currently, I am in the process of defining type definitions (.d.ts) for a JavaScript library. In this specific library, one of the methods accepts an object of functions as input, internally utilizes Function.prototype.bind on each function, and then expos ...

Incapable of grasping the intricacies of condensed

I recently came across a code snippet on geekcode(dot)tk and I have a question about it. Specifically, I would like to understand why the section within the table data tag is written in that particular way (at the bottom of the provided code). Thank you fo ...