一、PDF
1、安装html2canvas和jspdf
npm install --save html2canvas
npm install --save jspdf
2、创建生成PDF的js文件
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
install (Vue, options) {
//id:根据id作为生成PDF的内容,title:生成文件的名称,调用时直接使用getPdf方法名调用
Vue.prototype.getPdf = function (id,name) {
html2Canvas(document.querySelector(`#${id}`), {
// allowTaint: true
useCORS:true//看情况选用上面还是下面的,
}).then(function (canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(name + '.pdf')
}
)
}
}
}
3、在main.js里引入该js文件
//'/utils/htmlToPdf'是我的文件路径
import htmlToPdf from '@/utils/htmlToPdf'
Vue.use(htmlToPdf)
4、调用
无需在使用页面引入js文件,直接调用方法名即可
this.getPdf('id',name)
二、图片
1、安装html2canvas(和上述一样)
2、创建生成图片的js文件
import html2canvas from 'html2canvas';
//下载页面为图片格式
export default {
install (Vue, options) {
Vue.prototype.downPageToImage = function (id, name) {
//var scrollHeight = $('#contentDiv').prop("scrollHeight");
//$('#contentDiv').scrollTop(scrollHeight);
//var height = $('#contentDiv').height();
html2canvas(document.querySelector(`#${id}`),{
//height: scrollHeight,
//y: height-(scrollHeight+20)
}).then(canvas => {
/**
* 获取mimeType
* @param {String} type the old mime-type
* @return the new mime-type
*/
var type = 'jpeg';
var imgData=canvas.toDataURL(type);
var _fixType = function(type) {
type = type.toLowerCase().replace(/jpg/i, 'jpeg');
var r = type.match(/png|jpeg|bmp|gif/)[0];
return 'image/' + r;
};
// 加工image data,替换mime type
imgData = imgData.replace(_fixType(type),'image/octet-stream');
/**
* 在本地进行文件保存
* @param {String} data 要保存到本地的图片数据
* @param {String} filename 文件名
*/
var saveFile = function(data, filename){
var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
save_link.href = data;
save_link.download = filename;
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
save_link.dispatchEvent(event);
};
// 下载后的文件名
var filename = '图片' + (new Date()).getTime() + '.' + type;
// download
saveFile(imgData,filename);
})
}
}
}
3、在main.js里引入该js文件
Vue.use(htmlToPdf)
import downToImage from './util/download/img/downToImage'
4、调用
与上述一样,无需在使用页面引入js文件,直接调用方法名即可
this.downPageToImage('id',name)