环境及插件配置:(理论上vue2应该也可以使用,没有试验过)
javascript
"vue": "^3.2.36",
"webpack": "^5.94.0",
"webpack-cli": "^5.1.4",
"html2canvas": "^1.4.1",
"jspdf": "^2.5.2",
必须安装 html2canvas 与 jspdf
该方法中用到了一个判断数据类型的小方法
javascript
* 判断数据类型
* @param {any} value
* @returns {String}
* 返回数据为:
* "[object Number]","[object String]","[object Boolean]","[object Date]","[object RegExp]"
* "[object Object]","[object Array]","[object Function]","[object Null]","[object Undefined]"
*/
function getDataType(value) {
return Object.prototype.toString.call(value)
}
将html页面导出为PDF
javascript
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
function getDataType(value) {
return Object.prototype.toString.call(value)
}
/**
* 将页面导出为PDF
* @param {Object} 参数为{},具体属性参数参照详细解释
* @param {html} htmlDom 要导出的DOM片段
* @param {String} exportTitle 导出文件的文件名
* @param {String} watermark 水印 需要水印时传入即可 非必填
* @param {String} color 水印颜色 - 默认 opacity 为0.3
* @param {String} bgColor 导出的PDF背景色 - 默认为白色
*/
function exportToPDF({ htmlDom, exportTitle = "导出文件", watermark, color = '184,184,184, 0.3', bgColor = "#fff" }) {
const A4Width = 197;
const A4Height = 297;
html2canvas(htmlDom,
{
scale: 2,
useCORS: true,
dpi: 300,
backgroundColor: bgColor
}
).then(canvas => {
const pdf = new jsPDF('p', 'mm', 'a4')
const ctx = canvas.getContext('2d')
// 水印
if (watermark) {
const contentWidth = canvas.width
const contentHeight = canvas.height
console.log(watermark)
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.rotate((20 * Math.PI) / 180);
ctx.font = '20px Microsoft Yahei';
ctx.fillStyle = color;
for (let i = contentWidth * -1; i < contentWidth; i += 400) {
for (let j = contentHeight * -1; j < contentHeight; j += 400) {
// 填充文字,x 间距, y 间距
ctx.fillText(watermark, i, j);
}
}
}
const imgHeight = Math.floor(A4Height * canvas.width / A4Width)
let rendereHeight = 0
while (rendereHeight < canvas.height) {
const page = document.createElement('canvas')
page.width = canvas.width
page.height = Math.min(imgHeight, canvas.height - rendereHeight)
page.getContext('2d').putImageData(ctx.getImageData(0, rendereHeight, canvas.width, Math.min(imgHeight, canvas.height - rendereHeight)), 0, 0)
pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'PNG', 10, 10, A4Width, Math.min(A4Height, A4Width * page.height / page.width))
rendereHeight += imgHeight
if (rendereHeight < canvas.height) {
pdf.addPage()
}
}
pdf.save(exportTitle + '.pdf')
})
}
export {
exportToPDF
}