Joh*_*ohn 8 javascript pdf jspdf
我想保存包含IFrame内容的PDF文件.我正在使用jsPDF.当我点击调用该函数的按钮时,脚本会创建一个空的PDF页面.
框架的内容如下:https://jsfiddle.net/ss6780qn/
我使用以下脚本:
<script src="../jspdf/plugins/standard_fonts_metrics.js"></script>
<script type="text/javascript">
function toPDF(){
var pdf = new jsPDF('p', 'in', 'letter');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#frame')[0]
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'div': function(element, renderer){
// true = "handled elsewhere, bypass text extraction"
return true
}
}
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source // HTML string or DOM elem ref.
, 0.5 // x coord
, 0.5 // y coord
, {
'width':7.5 // max width of content on PDF
,'elementHandlers': specialElementHandlers
}
)
pdf.save('Test.pdf');
}
Run Code Online (Sandbox Code Playgroud)
有人知道什么是错的,我怎么能解决这个问题?
要从 iframe 打印 html,您需要从 iframe 获取内容。从 iframe 获取内容的源代码(我从中得到):
function getFrameContents() {
var iFrame = document.getElementById('frame');
var iFrameBody;
if (iFrame.contentDocument) { // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
} else if (iFrame.contentWindow) { // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
//alert(iFrameBody.innerHTML);
return iFrameBody.innerHTML
}
Run Code Online (Sandbox Code Playgroud)
所以你替换:
source = $('#frame')[0]
Run Code Online (Sandbox Code Playgroud)
和
source = getFrameContents();
Run Code Online (Sandbox Code Playgroud)
或者用 jQuery 简单地实现:
source = $("#frame").contents().find('body')[0];
Run Code Online (Sandbox Code Playgroud)
然而,CORS(跨源资源共享)仍然存在问题。要解决这个问题,您可以创建 Web 服务器并将 html 代码和 iframe src 放在那里,看看它是如何工作的。
| 归档时间: |
|
| 查看次数: |
4914 次 |
| 最近记录: |