JS generate the HTML and PDF Download

HTML to share with you today at the JS and generate PDF download of knowledge.

1 html2canvas

Introduction
We can use html2canvas directly in the browser, the whole or partial pages "shot." But this is not really shot, but the page by traversing the DOM structure, to collect information on all the elements and the corresponding style, rendering the canvas image.
Since html2canvas can only be generated canvas image it can handle, and therefore rendered the result is not 100% consistent with the original. But it does not require a server to participate, the entire picture is generated by the client browser, very easy to use.

Use
the use of API is very simple, the following code can be an element rendered as canvas:

html2canvas(element, {onrendered: function(canvas) {
        // canvas is the final rendered <canvas> element
    }
});

, The canvas may be generated by onrendered callback method, such as inserting into the page:

html2canvas(element, {onrendered: function(canvas) {
       document.body.appendChild(canvas);
    }
});

Examples to be small (the demo1) code is as follows: <html>

 <head>
    <title>html2canvas example</title>
    <style type="text/css">...</style>
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li>one</li>
          ...
        </ul>
      </nav>
    </header>
    <section>
      <aside>
        <h3>it is a title</h3>
        <a href="">Stone Giant</a>
        ...
     </aside>
      <article>
        <img src="./Stone.png">
        <h2>Stone Giant</h2>
        <p>Coming ... </p>
        <p>以一团石头...</p>
      </article>
    </section>
    <footer>write by linwalker @2017</footer>
    <script type="text/javascript" src="./html2canvas.js"></script>
    <script type="text/javascript">
        html2canvas(document.body, {
          onrendered:function(canvas) {
            document.body.appendChild(canvas)
          }
        })
</script>
  </body>
</html>

This example of an element in the body page rendered canvas, and inserted into the body.

2 jsPDF

jsPDF library browser can be used to generate PDF.

Text PDF generation
using the following method:

// 默认a4大小,竖直方向,mm单位的PDF
var doc = new jsPDF();
// 添加文本‘Download PDF’
doc.text('Download PDF!', 10, 10);
doc.save('a4.pdf');

Picture PDF generation
using the following method:

// 三个参数,第一个方向,第二个单位,第三个尺寸格式
var doc = new jsPDF('landscape','pt',[205, 115])
// 将图片转化为
dataUrlvar imageData = ‘data:image/png;base64,iVBORw0KGgo...;
doc.addImage(imageData, 'PNG', 0, 0, 205, 115);
doc.save('a4.pdf');

Text and images generated PDF:

// 三个参数,第一个方向,第二个尺寸,第三个尺寸格式
var doc = new jsPDF('landscape','pt',[205, 155])
// 将图片转化为
dataUrlvar imageData = ‘data:image/png;base64,iVBORw0KGgo...;
//设置字体大小
doc.setFontSize(20);
//10,20这两参数控制文字距离左边,与上边的距离
doc.text('Stone', 10, 20);
// 0, 40, 控制文字距离左边,与上边的距离
doc.addImage(imageData, 'PNG', 0, 40, 205, 115);
doc.save('a4.pdf')

Pdf need to add elements to generate transformed into jsPDF instance, there are added html features, but some elements can not be generated in the pdf, it is possible to use html2canvas + jsPDF manner pages into pdf.

By html2canvas will traverse the page elements, and rendered with the canvas, then add canvas picture format to jsPDF instance, generate pdf.

3 html2canvas + jsPDF

Leaflet
The demo1 Examples of modifications:

<script type="text/javascript" src="./js/jsPdf.debug.js">
</script><script type="text/javascript">      
var downPdf = document.getElementById("renderPdf");      
downPdf.onclick = function() {          
html2canvas(document.body, {              
onrendered:function(canvas) {                  
//返回图片dataURL,参数:图片格式和清晰度(0-1)                  
var pageData = canvas.toDataURL('image/jpeg', 1.0);      
 //方向默认竖直,尺寸ponits,格式a4[595.28,841.89]                 
  var pdf = new jsPDF('', 'pt', 'a4');                  
  //addImage后两个参数控制添加图片的尺寸,此处将页面高度按照a4纸宽高比列进行压缩                  
  pdf.addImage(pageData, 'JPEG', 0, 0, 595.28, 592.28/canvas.width * canvas.height ); 
    pdf.save('stone.pdf');              }          })      }
          </script>

If the page content based on the conversion ratio of a4 a4 paper height exceeds the height of it, generated pdf What happens? Paging will do?

You can try, test their ideas.

jsPDF API provides a useful, addPage (), we can pdf.addPage (), to add a pdf, then pdf.addImage (...), which gives the picture pdf page to display.

So how do we determine where pagination?

Well to answer this question, we can set a pageHeight, exceeding the height of the content into the next page pdf.

To stroke his thoughts, generate the html page content canvas picture, the first picture added by addImage page to pdf, the contents of more than one, add pdf pages by addPage (), and then add the picture to the next page by addImage the pdf.

~ Ah, well! Bart, do not find it a problem?

The premise of this method implementation is - - we split into small picture based on the corresponding pageHeight first full page generated content canvas picture, then a carrot a pit, page by page addImage inside.

? What we think is swollen to the canvas, do not pull up, looking directly at the following:

html2canvas(document.body, {
    onrendered:function(canvas) {
     //it is here we handle the canvas
    }
})

body here is to generate a canvas element object, and an element to generate a canvas; then we need a canvas one, that is. . .

Do you think that's possible? I do not think the reality, according to this thinking to get DOM elements in different locations on the page, then processed by htnl2canvas (element, option), I will not speak just can not find just a DOM element in the position of each pageHeight, even if found , and tired to do so.

:) tired, then you can take a look at this approach.

Multi-page
idea I offer is that we only generate a canvas, for it is a conversion element that you want to turn into a pdf contents of the parent element, in this demo there is a body; the other unchanged, but also more than one content on addPage then addImage, but added here is the same canvas.

Of course, multi-page pdf repeated it would only appear, that in the end how to achieve the correct page display. In fact, the main advantage jsPDF two points:

  • Examples of format size than jsPDF content is not displayed (var pdf = newjsPDF ( '', 'pt', 'a4'); demo the paper size is a4)
  • addImage There are two parameters to control the picture position in pdf
    although the picture displayed on each page pdf is the same, but we adjust the picture position, delusional paging.

In the second page, for example, be provided on offset in the vertical direction is a height -841.89 i.e. paper a4, a4 ​​and because the paper over the height range does not show images, the second page displays the image in the vertical direction content in the range of [841.89,1682.78], which give the effect of paging, and so on.

Or look at the code it:

html2canvas(document.body, {
  onrendered:function(canvas) {
      var contentWidth = canvas.width;
      var contentHeight = canvas.height;
      //一页pdf显示html页面生成的canvas高度;
      var pageHeight = contentWidth / 592.28 * 841.89;
      //未生成pdf的html页面高度
      var leftHeight = contentHeight;
      //页面偏移
      var position = 0;
      //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
      var imgWidth = 595.28;
      var imgHeight = 592.28/contentWidth * contentHeight;
      var pageData = canvas.toDataURL('image/jpeg', 1.0);
      var pdf = new jsPDF('', 'pt', 'a4');
      //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
      //当内容未超过pdf一页显示的范围,无需分页
      if (leftHeight < pageHeight) {
      pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
      } else {
          while(leftHeight > 0) {
              pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
              leftHeight -= pageHeight;
              position -= 841.89;
              //避免添加空白页
              if(leftHeight > 0) {
                pdf.addPage();
              }
          }
      }
      pdf.save('content.pdf');
  }
})

Margin left sides
modifications imgWidth, and the x-direction parameter to be set in your addImage margins, the specific code as follows:

var imgWidth = 555.28;
var imgHeight = 555.28/contentWidth * contentHeight;
...
pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight );
...
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight);

About JS generate the HTML and PDF download, you learn how much? Comments are welcome in the comments area!

Published 180 original articles · won praise 13 · views 7170

Guess you like

Origin blog.csdn.net/weixin_45794138/article/details/104883098