Created
December 20, 2018 02:50
-
-
Save annaliahsiao/9ab396ffb90fb6e711686c7f5797e8cd to your computer and use it in GitHub Desktop.
html to pdf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function add_iframe(){ | |
var html_content = $('#html_content').html(); | |
$("#download").contents().find("#wrapper").html(html_content); | |
setTimeout(function(){ | |
$("#download").get(0).contentWindow.print_html(); | |
},500) | |
} | |
function print_html(){ | |
var random = new Date().getTime(); | |
var pdf = new jsPDF('p','pt','a4'); | |
// 設置輸出比例 數值越大比列越小 | |
pdf.internal.scaleFactor = 2; | |
var options = { | |
pagesplit: true, //設置是否自動分頁 | |
"background": '#ffffff' //如果導出的pdf為黑色背景,需要將導出的html模塊內容背景 設置成白色。 | |
}; | |
var printHtml = $('#download').get(0); // 頁面某一個div裏面的內容,通過id獲取div內容 | |
pdf.addHTML(printHtml,15, 15, options,function() { | |
pdf.save('htmltopdf_'+random+'.pdf'); | |
parent.closeLoading(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
本篇將來介紹jspdf這支js套件,jspdf支援圖片、文字、html、表單、圖形列印,可以使用js產生文本,也可以列印好單頁的html,而這次的主題就是將html轉成pdf
Step1.首先我們要先載入套件
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
Step2.定義好要列印的區塊或是整頁列印,本次的範例使用區塊列印,區塊列印就需要製作一個iframe,將選擇的區塊以html的方式吐上新頁面,再控制iframe頁面的下載
而jspdf會碰到的問題是
html的轉換有時間問題
html的轉換有時間問題
html的轉換有時間問題
這點真的是太重要了要特別提醒,因此轉換成功前要測試你的網頁需要花多少時間轉換,來設置 settimeout 控制 loading 的時間!
function add_iframe(){ var html_content = $('#html_content').html(); $("#download").contents().find("#wrapper").html(html_content); //將選擇的區塊push到iframe上 setTimeout(function(){ //設置轉換時間 $("#download").get(0).contentWindow.print_html(); },500); }
Step3.再來就進入到轉換成pdf的步驟了
function print_html(){ var random = new Date().getTime(); var pdf = new jsPDF('p','pt','a4'); // 設置輸出比例 數值越大比列越小 pdf.internal.scaleFactor = 2; var options = { pagesplit: true, //設置是否自動分頁 "background": '#ffffff' //如果導出的pdf為黑色背景,需要將導出的html模塊內容背景 設置成白色。 }; var printHtml = $('#download').get(0); // 頁面某一個div裏面的內容,通過id獲取div內容 pdf.addHTML(printHtml,15, 15, options,function() { pdf.save('htmltopdf_'+random+'.pdf'); parent.closeLoading(); }); }