首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印整个HTML页面,包括iframe内的pdf文件

打印整个HTML页面,包括iframe内的pdf文件
EN

Stack Overflow用户
提问于 2016-04-11 22:11:18
回答 5查看 3K关注 0票数 17

我的任务是在html页面中嵌入相对较小的pdf文件,并打印整个html pade,包括iframe中的pdf文件。下面是我的html页面的结构:

下面是我的代码:

代码语言:javascript
复制
@media print{
	body * {display:block;}
    .toPrint{display:block; border:0; width:100%; min-height:500px}
代码语言:javascript
复制
<body>
    <button onclick="window.print()">Print</button>

	<h3>MUST BE PRINTED</h3>
    <p> MUST BE PRINTED</p>
    <iframe class="toPrint" src="https://nett.umich.edu/sites/default/files/docs/pdf_files_scan_create_reducefilesize.pdf" style="width:100%; height:97vh;"></iframe>
	<h3>MUST BE PRINTED</h3>
    <p> MUST BE PRINTED</p>
</body>

目前我正在使用css @media query打印页面。但不幸的是,这个媒体查询只打印pdf的第一页

我能做什么打印整个pdf文件?

EN

Stack Overflow用户

发布于 2020-06-02 05:17:15

这里有一个使用javascript的更简单的解决方案。

代码语言:javascript
复制
<body>
        <h3 id='first_h3'>MUST BE PRINTED</h3>
        <p id ='first_paragraph'> MUST BE PRINTED</p>
        <div id="pdfRenderer"></div>
        <h3 id='second_h3'>MUST BE PRINTED</h3>
        <p id='second_paragraph'> MUST BE PRINTED</p>

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />

</body>

<script>

 pages =[] // initiate an empty list here

function printPage() {

var first_h3 = document.getElementById('first_h3');
// get the first h3 tag and
// then push its innerHTML into the list
   pages.push(first_h3.innerHTML); 

var first_paragraph = document.getElementById('first_paragraph');
// get the first paragraph and
// then push its innerHTML into the list
   pages.push(first_paragraph.innerHTML); 

var pdfRenderer = document.getElementById('pdfRenderer');
// get the pdfRenderer and
// then push its innerHTML into the list
   pages.push(pdfRenderer.contentWindow.document.body.innerHTML); 

var second_h3 = document.getElementById('second_h3');
// get the second h3 tag and
// then push its innerHTML into the list
   pages.push(second_h3.innerHTML); 

var second_paragraph = document.getElementById('second_paragraph');
// get the second paragraph and
// then push its innerHTML into the list
   pages.push(second_paragraph.innerHTML); 

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the different parts in the exact order we pushed them into the list.
window.print();
} 
else {
// do nothing
}


}
</script>

有了这个解决方案,避免了iframe超过一页就被切断的问题。其次,即使你有多个iframe,你也只能得到一个打印对话框。

票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36551150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档