Convert html to pdf using pure js and jshtmlpdf using jshtmlpdf

Source: Internet
Author: User

Convert html to pdf using pure js and jshtmlpdf using jshtmlpdf

The project has encountered an abnormal requirement. You need to export an entire page to pdf format and retain all the tables, svg images, and styles on the page.
In short, we want to cut down the entire page and save it as a pdf.
Why not go to heaven ......
I checked that there are still many ways to convert html to pdf. There are probably the following:
1. Most browsers have this function. However, this is not what our customers want. What they want is the ability to actively trigger the export to pdf function in the system, so this solution passes.
2. Use third-party tools. I found a method to export using wkhtmltopdf. I tried it in our project, and the effect was not good, and the support for svg images was not good. Pass.
3. Use the iText class background to generate java files. However, because the page to be exported is a dynamic page, and a large number of styles are lost when the page is directly transferred to the background, it is still pass.
In the end, there is no good solution. I have to go back to the next step. I want to convert the html page into an image first, and then export the image as a pdf. To support user export and download, and retain the style, it is best to implement it on the js frontend only.
If html is converted to canvas, html 2canvas js will be used. This is a lot of introduction on the Internet and it will not be nonsense here.
The trouble is that svg images can't be converted into a canvas by using html2canvas directly. After checking a circle of data, the canvg js is locked. Canvg is a plug-in of Google. It can convert the content of svg labels to canvas. Another difficulty in our project is how to convert the font icons such as glyphicons to canvas, because the support for such font icons is completely different in different browsers. The final method is to replace the font icons with the char code and redraw them into a canvas. No nonsense is required to generate images from canvas. Use jsPDF to generate pdf files from images. After a long time, the entire process was finally integrated, and the code was pasted step by step.

Step 1: replace all svg elements in the corresponding dom node with canvas

1 svg2canvas: function (targetElem) {2 var svgElem = targetElem. find ('svg '); 3 svgElem. each (function (index, node) {4 var parentNode = node. parentNode; 5 // because the current IE does not support getting content directly from the svg label node, you need to set a div outside the current label, obtain 6 var tempNode = document through the innerHTML attribute of the outer div. createElement ('div '); 7 tempNode. appendChild (node); 8 var svg = tempNode. innerHTML; 9 var canvas = document. createElement ('canvas '); 10 // convert 11 canvg (canvas, svg); 12 parentNode. appendChild (canvas); 13}); 14}

Step 2: Convert the glyphicons font to canvas. Skip this step if the glyphicons font icon is not used in the project.

1 glyphicons2canvas: function (targetElem, fontClassName, fontFamilyName) {2 var iconElems = targetElem. find ('. '+ fontClassName); 3 iconElems. each (function (index, inconNode) {4 var fontSize = ((inconnode).css ("font-size"); 5 var iconColor = ((inconnode).css ("color "); 6 var styleContent = $ (inconNode ). attr ('style'); 7 // remove "px" 8 fontSize = fontSize. replace ("px", ""); 9 var charCode = getCharCodeByGlyphiconsName (iconName); 10 var myCanvas = document. createElement ('canvas '); 11 // increase the width and height of canva by 2 to display the complete icon 12 myCanvas. width = parseInt (fontSize) + 2; 13 myCanvas. height = parseInt (fontSize) + 2; 14 myCanvas. style = styleContent; 15 var ctx = myCanvas. getContext ('2d '); 16 // set the color of the drawing content 17 ctx. fillStyle = iconColor; 18 // set the font size of the drawing and the font-family name 19 ctx. font = fontSize + 'px '+ fontFamilyName; 20 ctx. fillText (String. fromCharCode (charCode), 1, parseInt (fontSize) + 1); 21 $ (inconNode ). replaceWith (myCanvas); 22}); 23} 24 // obtain the char code25 getCharCodeByGlyphiconsName: function (iconName) {26 switch (iconName) based on the class name of the glyphicons/glyphicon) {27 case ("glyphicons-resize-full"): 28 return "0xE216"; 29 case ("glyphicons-chevron-left"): 30 return "0xE225"; 31 default: 32 return ""; 33} 34}

Step 3: convert html to canvas, convert image to pdf

1 html2canvas ($ ("# myExportArea"), {2 onrendered: function (canvas) {3 var imgData = canvas. toDataURL ('image/jpeg '); 4 var img = new image (); 5 img. src = imgData; 6 // set the pdf specification based on the image size. The reason why * 0.225 is required when the image is loaded successfully is because the proportion is 7 img. onload = function () {8 // note that the horizontal and vertical attributes of pdf must be adjusted according to the ratio of width to height, otherwise, the display is incomplete. 9 if (this. width> this. height) {10 var doc = new jsPDF ('l', 'mm', [this. width * 0.225, this. height * 0.225]) ; 11} else {12 var doc = new jsPDF ('P', 'mm', [this. width * 0.225, this. height * 0.225]); 13} 14 doc. addImage (imgData, 'jpeg ', 0, 0, this. width * 0.225, this. height * 0.225); 15 // save as different file names according to the download 16 doc. save ('report _ pdf _ '+ new Date (). getTime () + 'hangzhou'); 17} 18}, 19 background: "# fff", 20 // The Default background of the generated image. Otherwise, if the background is not set for your html root node, it will be black. 21 allowTaint: true // avoid some unrecognized image interference. The default value is false. In case of unrecognized image interference, html2canvas22} Will be stopped });

Although the customer's requirements were barely met at the end, the generated pdf was not as clear as it was ...... This method is the only option for the time being. If you have a better solution, please advise.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.