在js window.open之后打印html / css布局

时间:2017-04-19 14:58:45

标签: javascript html css twitter-bootstrap

我在打开的窗口中通过javascript打印输出有问题。我通过window.open创建了新文档,其中包含指向引导程序文件的CDN链接。在打开的窗口中,一切看起来都不错但是如果我使用print(XPS文档编写器),这里有一些样式(.btn-group),但布局或内联样式不是。

问:我如何在新窗口中打印出来的内容?

在CDN上的链接中我有media='all'(但也试过media='print')。

工作示例: jsfiddle

$('#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)

});

2 个答案:

答案 0 :(得分:1)

我不知道为什么,但Bootstrap 3打印工作的XS大小(col-xs- *),所以你可以重写你的弹出窗口打印到XS或找到css修复

答案 1 :(得分:0)

一般情况下,如果你有自己的默认自动宽度尺寸,并且在主体中只有浮动/不受限制的div,它们将以隐式浏览器的方式用于打印方块。

您应该定义固定的主体宽度,并在其中定义浮动/定位的不受限制的div,(或者定义divs宽度等等)

您可以在打印专用样式文档中定义不希望影响主文档的其他样式(例如固定的主体宽度),例如:

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

然后进行实验,直到您检测到缺少合适的样式,因此纸质就绪文档将按您的意愿运行。我猜测定义的body元素宽度足以让布局看起来正确。