Html2canvas and JSPDF are needed

The first is to use HTML2Canvas to generate base64 pictures of the page, and then use JSPDF to insert the pictures into PDF

The renderings are as follows

CreateImage (){// createImage -> PDF let _this = this; Window. PageYoffset = 0; //---- document.documentElement.scrollTop = 0; document.body.scrollTop = 0; ' //---------------------------------------- let canvas = document.createElement("canvas"); let context = canvas.getContext("2d"); let _articleHtml = document.getElementById('imageTofile'); let _w = _articleHtml.clientWidth; let _h = _articleHtml.clientHeight; //----- here to solve the problem of the generated PDF is not clear, first enlarge 3 times ---- then reduce 3 times let scale = 3; canvas.width = _w * scale; canvas.height = _h * scale; context.scale(scale, scale); let opts = { scale: 1, width: _w, height: _h, canvas: canvas, useCORS: true }; (window.html2canvas || html2canvas)(_articleHtml, Opts). Then (canvas => {//IOS13.4 invalid resolve and {(intermediate value)(intermediate value)} is not a function+; _this.createPdfAll(canvas, scale); }); },Copy the code

I inserted the entire IMG directly into the PDF, not truncating the page, because truncating the img would require adjustment, which is not very friendly, or it would truncate the text from the middle

createPdfAll (canvas, Scale) {/ / generated image - > PDF / / -- -- -- -- -- -- -- -- -- -- - wide high narrow 3 times -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - let contentWidth = canvas. Width/scale let contentHeight =  canvas.height / scale //-------------------- let pdf = new jsPDF('', 'pt', [contentWidth, (+50 here is the last blank distance from the bottom of the PDF. Let pageData = Canvas. ToDataURL ('image/jpeg', 1.0); // Only one page of PDF is generated, not truncated, AddImage (pageData, 'JPEG', 0, 0, contentWidth, File file let filename = 'question.pdf'; let datauri = pdf.output('dataurlstring'); let file = this.dataURLtoFile(datauri,filename); This.uploadimg (file)}Copy the code

Stream the file to file

dataURLtoFile(dataurl, filename) { var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?) ; / [1]); var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while(n--){undefined u8arr[n] = bstr.charCodeAt(n); Return new file ([u8arr], filename, {type:mime}); // Return new blob ([u8arr],{type:mime}); },Copy the code

The solution is pure front-end implementation, without back-end cooperation, and the page restore degree is relatively high, for PDF operation requirements are not high demand, or a more suitable solution.

The disadvantage is that it cannot be copied and is not compatible with PDF operations