SoFunction
Updated on 2025-02-28

Simple example of pure js implementing html to pdf (recommended)

During the project development, we encountered an abnormal requirement, which required exporting the entire page to pdf format, and retaining all tables, svg images and styles on the page.

In short, I hope to cut off the entire page like a screenshot and save it into a pdf.

Why don't you go to heaven...

After checking, there are quite a few ways to implement html to pdf, probably the following:

1. Most browsers have this function.However, what our customers want is not this. What they want is to be able to actively trigger the export to PDF function in the system, so this solution passes.

2. Use third-party tools.I found a solution to export using a tool like wkhtmltopdf. I tried it myself in our project, but the effect was not good, and the support for svg images is not good either. pass.

3. Another type is to use the iText class background to generate java files.However, because the page you need to export is a dynamic page, and passing the page directly to the background will lose a lot of styles, so it is still pass.

In the end, there is no good idea, so I can only settle for the second best. I thought about converting the html page into a picture first and then exporting the picture as a pdf. Because it is necessary to support users to export and download and retain styles, it is best to implement it in a pure JS front-end.

If you transfer html to canvas, use html2canvas js. This is a lot of introductions online, so I won’t talk nonsense here.

The more troublesome thing is the svg image. Using html2canvas directly cannot convert the content of the svg tag into canvas. Finally, after checking the information, I locked the js of canvg. canvg is a plugin from Google that can convert svg tag content into canvas. Specifically for our project, there is another difficulty, which is how to convert font icons such as glyphicons into canvas, because the support for this font icons is completely different under different browsers. The last method found is to replace these font icons with char code and repaint them into canvas. There is no need to talk nonsense about generating images from canvas. The pdf generated from the picture is implemented using jsPDF. After struggling for more than a long time, I finally opened up the entire process and posted the code step by step.

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

svg2canvas: function(targetElem) {
 var svgElem = ('svg');
 (function(index, node) {
  var parentNode = ;
  // Since the current IE does not support directly fetching contents of the svg tag node, it is necessary to cover a layer of div outside the current tag and obtain it through the innerHTML attribute of the outer div  var tempNode = ('div');
  (node);
  var svg = ;
  var canvas = ('canvas');
  //Convert  canvg(canvas, svg);
  (canvas);
 });
}

Step 2: Convert glyphics font to canvas. If the glyphicons font icon is not used in the project, this step can be ignored

glyphicons2canvas: function(targetElem, fontClassName, fontFamilyName) {
 var iconElems = ('.' + fontClassName);
 (function(index, inconNode) {
  var fontSize = $(inconNode).css("font-size");
  var iconColor = $(inconNode).css("color");
  var styleContent = $(inconNode).attr('style');
  // Remove "px"  fontSize = ("px", "");
  var charCode = getCharCodeByGlyphiconsName(iconName);
  var myCanvas = ('canvas');
  //Increase the width and height of the canva by 2 to show the complete icon   = parseInt(fontSize) + 2;
   = parseInt(fontSize) + 2;
   = styleContent;
  var ctx = ('2d');
  //Set the color of the drawing content   = iconColor;
  //Set the font size of the drawing and the name of the font-family   = fontSize + 'px ' + fontFamilyName;
  ((charCode), 1, parseInt(fontSize) + 1);
  $(inconNode).replaceWith(myCanvas);
 });
}
//Get the corresponding char code according to the class name of the glyphicons/glyphicon icongetCharCodeByGlyphiconsName: function(iconName) {
 switch (iconName) {
 case("glyphicons-resize-full"):
  return "0xE216";
 case ("glyphicons-chevron-left"):
  return "0xE225";
 default:
  return "";
 }
}

Step 3: Turn html to canvas to picture and then to pdf

html2canvas($("#myExportArea"), {
 onrendered: function(canvas) {
  var imgData = ('image/jpeg');
  var img = new Image();
   = imgData;
  //Set the pdf specification according to the size of the picture, and execute it when the picture is loaded successfully. The reason why it is *0.225 is because of the proportional problem   = function() {
   //It should be noted here that the two attributes of pdf horizontal and vertical need to be adjusted according to the ratio of width and height, otherwise there will be incomplete display problems.   if ( > ) {
    var doc = new jsPDF('l', 'mm', [ * 0.225,  * 0.225]);
   } else {
    var doc = new jsPDF('p', 'mm', [ * 0.225,  * 0.225]);
   }
   (imgData, 'jpeg', 0, 0,  * 0.225,  * 0.225);
   //Save it into different file names according to the download   ('report_pdf_' + new Date().getTime() + '.pdf');
  }
 },
 background: "#fff",
 //The default background for the generated image is given here. Otherwise, if your html root node does not have a background set, it will be filled with black. allowTaint: true //Avoid some unrecognized image interference. The default is false. If you encounter unrecognized image interference, you will stop processing html2canvas.});

Although the customer's requirements were barely completed in the end, the generated pdf effect was obviously not as clear as normal screenshots... Due to the limited level, I can only think of this method for the time being. If you have a better solution, please give me some advice.

The above simple example (recommended) of pure JS to implement html to PDF is all the content I share with you. I hope you can give you a reference and I hope you can support me more.