使用javascript打印动态内容

Printing dynamic content with javascript

本文关键字:动态 打印 javascript 使用      更新时间:2023-09-26

问题

我们有带表单的页面。
用户填写表单并提交。
我需要打印包含表单数据和其他内容的页面。

代码#1

$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "<p>Test " + $('#form').serialize() + "</p>";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.body.innerHTML = print_text;
  newWin.print();
  });
});

冷却,

  1. 我需要特定的css
  2. 在加载内容之前出现"打印"窗口。。。ooops

好的!

代码#2

$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns='http://www.w3.org/1999/xhtml'> <head> <meta http-equiv='Content-Type' content='text/html; charset=windows-1251' /> <title>Оформление доверенности (простая письменная форма)</title> <link rel='stylesheet' type='text/css' href='/css/print_forms/warrant.css'> </head> <body> <p>Test " + $('#form').serialize() + "</p></body><script type='text/javascript'>window.print();</script></html>";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.write(print_text);
  });
});
  1. document.write-在其他情况下css未加载
  2. 在内容的和处添加了"window.print((">

这在所有浏览器中都能很好地工作,不在IE窗口中,在没有打印对话框的情况下成功加载内容。我需要帮助
p.s.
CSS with media="print"-出于某种原因,这不是一个很好的解决方案。

$(document).ready(function($){
 $('input[name=sumb_but]').bind('click', function(e){
  e.preventDefault();
  var print_text = "<p>Test " + $('#form').serialize() + "</p>";
  var newWin = window.open('','printWindow','Toolbar=0,Location=0,Directories=0,Status=0,Menubar=0,Scrollbars=0,Resizable=0');
  newWin.document.body.innerHTML = print_text;
  newWin.document.body.onload = function() { newWin.print(); }   
  });
});

这可以帮助