Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This paper mainly introduces some methods of front-end HTML to PDF and export, including browser’s own, VUe-print-NB, HTML2Canvas and JSPDF, WkHTMLTopDF and iText

The use of graphical statements in the system, so the export report is also essential, the general form of export is PDF file, this, a study, the following is to step on the pit experience.

Take the following report page as an example:

Window.print

Official website: developer.mozilla.org/zh-CN/docs/…

Detailed use can refer to the document: Window.print () front-end implementation of web page print details

By default, all content in the body of the page is printed, that is, global printing. If you want to print locally, you need to replace the content of the body, which will change the original web content, and the experience is not very good.

 <a-button type="primary" @click="window.print()">window.print</a-button>
Copy the code

vue-print-nb

Website to install and use the document: www.npmjs.com/package/vue…

The plugin is essentially implemented using the browser’s own printing window.print(), which creates an iframe by default to embed the content to be printed. It is a little more flexible than the first method, but the style support is still poor. The Ant Design Vue component style presentation is not complete, you need to rewrite the style, so it is troublesome.

/ / 1. Install
npm install vue-print-nb --save

// 2. Global registration (main.js)
import Print from "vue-print-nb";
Vue.use(Print);

/ / 3. Use
<a-button type="primary" v-print="printObj">
  vue-print-nb
</a-button>;

var printObj = {
  id: "pdfDom".popTitle: "good print".extraCss: "https://www.google.com,https://www.google.com".extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>'};Copy the code

html2canvas + jspdf

Html2canvas:github.com/niklasvh/ht…

Jspdf:github.com/parallax/js…

Html2canvas is used to convert HTML pages into canvas pictures, and then JSPDF is used to convert the pictures into PDF files.

Disadvantages:

  1. Lack of clarity
  2. When pagination occurs, the content is truncated and cannot be displayed intelligently
  3. If the page content is too long (width and height limit is 14400), the content cannot be printed and the page remains blank. This is really very unfriendly ah, the content of the report must be more ah…

Note:

  • The introduction of external chain picture, need to configure the picture cross domain, toimgLabel setcrossOrigin='anonymous'.
  • Improve the quality of the generated picture, can be properly enlargedcanvasCanvas, through SettingsscaleScale the canvas size, or setdpiImprove clarity.
  1. The installation
npm install html2canvas jspdf --save
Copy the code
  1. Defining utility functions
// utils/ htmltopdf. js: Export the page in PDF format
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

export default {
  install(Vue, options) {
    // id- export PDF div container; Title - The title of the exported file
    Vue.prototype.htmlToPdf = (id, title) = > {
      const element = document.getElementById(`${id}`);
      const opts = {
        scale: 12.// Zoom to improve the sharpness of the generated image
        useCORS: true.// Allow loading of images across domains
        allowTaint: false.// Allows images to cross domains, and cannot be used together with useCORS
        tainttest: true.// Check that each image has been loaded
        logging: true.// Log switch, set to false when publishing
      };

      html2Canvas(element, opts)
        .then((canvas) = > {
          let contentWidth = canvas.width;
          let contentHeight = canvas.height;
          // a PDF page displays the canvas height generated by the HTML page;
          let pageHeight = (contentWidth / 592.28) * 841.89;
          // Height of HTML page not generated PDF
          let leftHeight = contentHeight;
          // Page offset
          let position = 0;
          // The size of the A4 paper [595.28,841.89], the width and height of the image in the PDF generated by the CANVAS of the HTML page
          let imgWidth = 595.28;
          let imgHeight = (592.28 / contentWidth) * contentHeight;
          let pageData = canvas.toDataURL("image/jpeg".1.0);

          // A4 paper vertical, generally used by default; new JsPDF('landscape'); Horizontal page
          let PDF = new JsPDF(""."pt"."a4");

          // When the content does not exceed the size of a PDF page, no pagination is required
          if (leftHeight < pageHeight) {
            // addImage(pageData, 'JPEG', left, top, width, height) setting
            PDF.addImage(pageData, "JPEG".0.0, imgWidth, imgHeight);
          } else {
            // Print in pages of more than one page (height per page 841.89)
            while (leftHeight > 0) {
              PDF.addImage(pageData, "JPEG".0, position, imgWidth, imgHeight);
              leftHeight -= pageHeight;
              position -= 841.89;
              if (leftHeight > 0) {
                PDF.addPage();
              }
            }
          }
          PDF.save(title + ".pdf");
        })
        .catch((error) = > {
          console.log("Print failed", error); }); }; }};Copy the code
  1. Global registration
/ / the main js file
import htmlToPdf from "./utils/htmlToPdf";
Vue.use(htmlToPdf);
Copy the code
  1. use
export default {
  methods: {
    handleExportPdf() {
      // Scroll to the top to make sure the print is complete
      document.body.scrollTop = 0; / / IE
      document.documentElement.scrollTop = 0; / / other
      this.htmlToPdf("pdfDom"."Statistical Report"); ,}}};Copy the code

The next article introduces wkHTMLTopdf and iText