uniapp generates pdf files
1. Two plug-ins need to be installed
(1) html2canvas - convert web pages into images
(2) jspdf - convert images into pdf.
After uniapp is created, open it in the root directory with a terminal.
1.Initialize the project
npm init
2. Install the required plug-ins
npm install html2canvas jspdf --save
3. After installation, import it to the required page
import html2canvas from 'html2canvas';
import jspdf from 'jspdf';
4. Define the method to generate pdf
downPdf() {
window.scrollTo(0, 0) //首先滚动到顶部 如果要某一个元素 就滚动到元素位置
let that = this;
html2canvas(document.querySelector('#main'), {
//对应的dom元素id(class也可以)
allowTaint: true,//是否允许跨域图像渲染画布
useCORS:true,//是否尝试使用 CORS 从服务器加载图像 解决图片跨域问题
}).then(function (canvas) {
//生成的canvas实例
var contentWidth = canvas.width;//所选元素宽度
var contentHeight = canvas.height;//所选元素高度
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 595.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//pdf页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 555.28;
var imgHeight = 555.28 / contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);//转成jpg格式
var pdf = new jspdf('', 'pt', 'a4');//生成pdf实例
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight);
} else {
while (leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
//保存
pdf.save('文件名.pdf');
//可以吧生成的pdf转成其他格式 如 base64
pdf.output('datauristring')//获取到base64 的pdf
})
}
pdf There are other format documents known
If you want to pass the generated pdf to the backend, convert it to base64 format.
Please support me by following me