項目中需要將html字符串打印成pdf证鸥,找一下網(wǎng)上的解決方案:
- 使用
html2canvas.js
將網(wǎng)頁轉(zhuǎn)換為圖片- 使用
jsPdf.debug.js
將canvas
生成的圖片轉(zhuǎn)換為pdf文件
但是并不希望html顯示在頁面上敌土,因此給截取的html
節(jié)點加了
"display:none;"
然后生成的pdf是空白的运翼。一開始一直在以為是生pdf
的時候失敗了兴枯,直到我留意到這個
"display:none;"
因為html2canvas
第一個參數(shù)就是拿到html
的dom
節(jié)點。如果display:none
的話這個節(jié)點就不存在了呀悠夯,順著這個思路搜了一下,果然:
可能這個題目不是很好的描述問題乳蓄。我先描述一下問題所在夕膀,由于
html2canvas
生成圖片所在的html
必須是真實存在的,否則生成canvas
為空白魂奥。也就是需要生成html
不能設(shè)置disabled: none; visibility: hidden;
等屬性易猫。
因此表明在調(diào)用html2canvas
生成canvas
過程中必須dom
節(jié)點渲染完成。因此這就會導(dǎo)致在生成canvas
會出現(xiàn)原有html
的閃現(xiàn)准颓。這個問題其實也比較好解決,用了一個小技巧买鸽,使用top 屬性,把html 移除視野top:100%
參考自--html2canvas 生成圖片踩坑記
我的解決方式跟上述的類似給pdf繪制的根節(jié)點加上了決定定位眼五,把html 移出可視范圍之外彤灶,然后pdf
生成完將原來的節(jié)點置空。但是找了一下沒看到jspdf
的save
方法的回調(diào)幌陕。于是點進了源碼:
/**
* Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf').
* Uses FileSaver.js-method saveAs.
*
* @memberOf jsPDF
* @name save
* @function
* @instance
* @param {string} filename The filename including extension.
* @param {Object} options An Object with additional options, possible options: 'returnPromise'.
* @returns {jsPDF} jsPDF-instance
*/
API.save = function (filename, options) {
filename = filename || 'generated.pdf';
options = options || {};
options.returnPromise = options.returnPromise || false;
if (options.returnPromise === false) {
saveAs(getBlob(buildDocument()), filename);
if (typeof saveAs.unload === 'function') {
if (global.setTimeout) {
setTimeout(saveAs.unload, 911);
}
}
} else {
return new Promise(function (resolve, reject) {
try {
var result = saveAs(getBlob(buildDocument()), filename);
if (typeof saveAs.unload === 'function') {
if (global.setTimeout) {
setTimeout(saveAs.unload, 911);
}
}
resolve(result);
} catch (e) {
reject(e.message);
}
});
}
}; // applying plugins (more methods) ON TOP of built-in API.
// this is intentional as we allow plugins to override
// built-ins
瞬間明白了設(shè)置options.returnPromise === true
就會返回一個promise對象棚唆,就能快樂的使用.then
了