繁体   English   中英

使用 jsPDF 从 iframe 创建 PDF

[英]Using jsPDF to create a PDF from an iframe

好的,我已经在互联网上搜索了解决方案,但我找不到任何东西。 我正在尝试找到一种将 iframe 的内容保存为 PDF 的方法。 我总是遇到 PDF 只是空白的问题。 似乎jsPDF是唯一的方法。 我有点想知道这不起作用的原因是否是因为 fromHTML() 函数。 我不知道。 如果你们中有人找到了解决方案,我将不胜感激!!

以下是您可以在 HTML 文件中尝试的一些示例代码:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script>
    function demoFromHTML() {
    var pdf = new jsPDF('p', 'pt', 'letter');
    source = $('#frame')[0];
    specialElementHandlers = {
        '#bypassme': function (element, renderer) {
            return true
        }
    };
    margins = {
        top: 80,
        bottom: 60,
        left: 40,
        width: 522
    };
    pdf.fromHTML(
    source,
    margins.left,
    margins.top, {
        'width': margins.width,
        'elementHandlers': specialElementHandlers
    },

    function (dispose) {
        pdf.save('Test.pdf');
    }, margins);
}
</script>
<button onclick="javascript:demoFromHTML();">PDF</button>
<iframe id="frame" src='https://wikipedia.org/wiki/Main_Page' style="width: 75%;height: 75%;"></iframe>

阅读本文: 使用 jsPDF JavaScript 库将 HTML/CSS 内容转换为流畅的多页 PDF 文件 提供的脚本允许您将任何 HTML 元素转换为 PDF。 我稍微修改了generate()函数,以便它采用任何 HTML 元素 ID 名称并将其导出为PDF文件:

 generate = function(doc) { var pdf = new jsPDF('p', 'pt', 'a4'); pdf.setFontSize(18); pdf.fromHTML(document.getElementById(doc), margins.left, // x coord margins.top, { // y coord width: margins.width// max width of content on PDF },function(dispose) { headerFooterFormatting(pdf, pdf.internal.getNumberOfPages()); }, margins); var iframe = document.createElement('iframe'); iframe.setAttribute('style','position:absolute;right:0; top:0; bottom:0; height:100%; width:650px; padding:20px;'); document.body.appendChild(iframe); iframe.src = pdf.output('datauristring'); };

它在 Chrome 上 100% 工作,但我不确定其他浏览器。

试试这个解决方案。

<button id="generatePDF">Generate PDF</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
$( '#generatePDF' ).click( function()
{
    var pdf = new jsPDF('a4');
    pdf.text("Some text inside PDF", 10, 10);

    $( '#docpdf' ).attr('src', pdf.output('datauristring'));
});

</script>

<iframe id="docpdf" style="background-color:#EEE; height:400px;">
    PDF goes here 
</iframe>

这是一个疯狂的猜测,但我认为这与来自其他域的 Iframe 受到保护的事实有关。 阅读“跨域策略”,如果这是原因,我很确定你不能很容易地解决它。

尝试

    var source = window.document.getElementsByTagName(tagName)[0];

代替

 source = $('#frame')[0];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM