我有一个独特的问题--虽然我见过类似的问题和答案--但没有一个能很好地解决我的挑战。
目前,我提供了一个" print“按钮,它基于嵌入式和隐藏的iframe在浏览器上加载打印对话框。这可以很好地工作,但我不想通过为大型PDF拉入iframe来减慢页面加载速度。
因此,我想加载一个不带源代码的iframe,然后在用户单击打印图标时编写正确的源url,然后重新加载iframe,最后显示对话框。
不幸的是,打印对话框在我重新加载iframe之前弹出,所以在对话框中加载了一个空白页面。在随后的单击中,将加载PDF并准备打印。
<a href='#' id='load_pdf' ><i class='fa fa-2 fa-print'></i></a>
<iframe id="iFramePdf" src="" style="display:none;"></iframe>
<script type="text/javascript">
jQuery(document).ready(function() {
$("#load_pdf").click(loadPDF);
function loadPDF() {
$('#iFramePdf').attr('src', "my.pdf");
// Attempt to reload iframe
$('#iFramePdf').load("my.pdf");
sendPrint('iFramePdf')
}
function sendPrint(elementId) {
var iframe = $(element_id)[0];
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
});
</script> 我尝试了以下不同的方法来重新加载:
// Attempt 1
$('#iFramePdf').attr('src', function () { return
$(this).contents().get(0).location.href });
// Attempt 2
$('#iFramePdf').attr("src", $('#iFramePdf').attr("src"));
$('#iFramePdf').attr('src', function () { return $(this).contents().get(0).location.href });
// Attempt 3
$('#iFramePdf')[0].contentWindow.location.reload(true);
// Attempt 4
var getMyFrame = document.getElementById(elementId);
getMyFrame.contentWindow.location.reload(true);我甚至尝试过使用jQuery的defer方法,但没有成功(可能是因为我缺乏知识)。如果我能得到任何指导,我将不胜感激。
发布于 2015-09-03 06:49:30
试着改变这一点:
function loadPDF() {
$('#iFramePdf').attr('src', "my.pdf");
// Attempt to reload iframe
$('#iFramePdf').load("my.pdf");
sendPrint('iFramePdf')
}类似这样的东西:
function loadPDF() {
$('#iFramePdf').attr('src', "my.pdf");
}
$('#iFramePdf').load(function(){
sendPrint('iFramePdf')
})它应该是可行的
发布于 2015-09-03 08:40:09
你可以试试。由于明显的原因,我不能测试它,但我认为3秒应该足够加载iframe。请注意,这在语法上是正确的,我可以在不进行测试的情况下获得它。相应地调整fadeIn(1800)和delay(1200)。
HTML
<a href='#' id='load_pdf' ><i class='fa fa-2 fa-print'></i></a>
<p id="msg" style="display: none;">Printing Document...</p>
<div id="printPort" style="opacity: 0; width: 1px; height: 1px;"></div>jQuery
$(function() {
$("#load_pdf").on('click', loadPDF('my.pdf'));
// Create the iframe, and put it inside #printPort
// Change it's src to the file argument
// Animate the #msg for 3 seconds
var loadPDF = function(file) {
$('<iframe id="iFramePdf" src="blank.html"></iframe>').appendTo("#printPort");
$("#iFramePdf").att('src', file);
return $('#msg').fadeIn(1800).delay(1200).fadeOut();
}
var sendPrint = function(elementId) {
var iframe = $(element_id)[0];
iframe.contentWindow.focus();
iframe.contentWindow.print();
}
// Once the animation is done the promise will resolve and sendPrint will execute on callback.
$.when(loadPDF).done(sendPrint('iFramePdf'));
});https://stackoverflow.com/questions/32364088
复制相似问题