簡體   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