3
Please indicate the source for reprinting: Grape City official website , Grape City provides developers with professional development tools, solutions and services, and empowers developers.

Everyone must be familiar with electronic forms in daily work and study. From the summary analysis of work data to the various electronic invoices of outgoing receipts, these are all produced by electronic forms.

But everyone’s impression of the spreadsheet may stay here:

图片1.png

The table style of standard row and column data statistics.

 

But in fact, the table can also look like this:

3.png

The forms that need to be implemented in the work are often more complicated than everyone thinks. Recently, we encountered a customer in the process of doing customer support, and he needed to use the electronic form to implement the electronic signature in the contract.

Generally speaking, electronic signature is to load an electronic signature on an electronic document through technical means, and its function is similar to a handwritten signature or a stamped official seal on a paper contract. It is widely used in enterprise workflow approval, invitations, document preservation and other scenarios.

Today, when the economy is more and more active and cross-regional, as an important use scenario of electronic forms, electronic contracts can be signed in different places, and the time and point of signing are more free; in the face of large-volume contract signing, it can also be easily solved; At the same time, the management of traditional paper contracts is more convenient, avoiding damage to paper contracts due to preservation management issues.

 

Today, what customers need to achieve in actual projects looks like this:

6.png

Seeing this, some friends may say that this is difficult, although this thing looks exactly like a word,

But isn't it just that the border line of the spreadsheet is removed?

1.jpg

If it is just a simple table box content, the next code can simply draw the table.

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>02Canvas案例-绘制表格</title>

</head>

<body>

<div id="container">

    <canvas id="cavsElem">

        

    </canvas>

</div>

<script>

    (function(){

        var canvas=document.querySelector('#cavsElem');

        var ctx=canvas.getContext('2d');

        canvas.width=600;

        canvas.height=600;

        canvas.style.border='1px solid green';

        var rectH=10;

        var rectW=20;

        ctx.lineWidth=.5;

        //绘制表格

        // 第一步: 绘制横线

        for(var i=0;i<canvas.width;i++){

            ctx.moveTo(rectW*i,0);

            //如果不设置moveTo,当前画笔没有位置

            ctx.lineTo(rectW*i,canvas.height);

        }

        //第二步:绘制竖线:如果绘制的格子的宽高相等,可以将for循环放到一个里面;

        for(var i=0;i<canvas.height;i++){

            ctx.moveTo(0,rectH*i);

            ctx.lineTo(canvas.width,rectH*i);

        }

        ctx.stroke();

    }())

</script>

</body>

</html>

But if you zoom in and take a closer look, you will find that the situation is not as simple as we thought.

2.jpg

3.jpg

4.jpg

In this contract, in addition to hiding the border lines, we also need to consider issues such as margins, image spanning, and incomplete screenshots after page scrolling. With the help of the inherent advantages of electronic forms in data processing and analysis, electronic signature functions can be easily implemented.

 

Let's try together today to realize the project development requirements of electronic signature and export PDF through Canvas-based electronic forms.

Realization ideas

Environmental preparation

1. Environment preparation: Install the SpreadJS front-end table plug-in, and draw the canvas through the plug-in.

  1. Initialize the Spread workbook and import the contract template
  2. Create Canvas canvas and reference esign.js drawing method to realize handwritten signature area
  3. Jump commands through custom hyperlinks, call out in the signature area
  4. Convert the signature area into a picture and set it as a background picture
  5. Use the export PDF interface provided by SpreadJS to export the signed file

The realization of electronic signature

Initialize Spread workbook

1. Introduce the following files

<link rel="stylesheet" type="text/css" href="node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css">

<script src="node_modules/@grapecity/spread-sheets/dist/gc.spread.sheets.all.min.js" type="text/javascript"></script>

<script src="new2.ssjson" type="text/javascript"></script>

1. Create a DOM for hosting SpreadJS

<div id="ss" class="sample-spreadsheets" style="height: 900px;">

2. Use JS to get the DOM object and initialize it

var spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));

3. Import the contract template

spread.fromJSON(str);

At this point, our Spread workbook has been initialized. Of course, you can also add the corresponding CSS to adjust the size of the form.

Regarding the production of the template, you can draw according to your needs in the online form editor, export it as an ssjson file and import it into our form via fromJSON.

Next, use the Canvas canvas to implement the handwritten signature area.

Handwritten signature area

1. First, we first create the DOM element of the signature area and define a Canvas canvas, which is not displayed by default.

4.png

<div class="containter" id="box" style="display: none;">

       <div class="canvasDiv">

             <div id="editing_area">

                  <canvas id="canvasEdit"></canvas>

             </div>

       </div>

       <div class="btnDiv">

             <a id="sign_clear" class="clearBtn">清空</a>

             <a id="sign_clear2" class="clearBtn">签署</a>

       </div>

</div>

2. Quote esign.js and jQuery. Esign.js is a drawing method that uses the mouse to draw on the canvas.

`<script type="text/javascript" src="js/esign.js"></script>

<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>`

 

3. Initialization
`
$(document).esign("canvasEdit", "sign_show", "sign_clear", "sign_ok");

$(document).on('click', '#sign_clear2', takeScreenshot);`

 

Using custom cells in the Canvas canvas, in theory, it is also possible to develop cells that can be directly signed.

Users can sign directly in the cell, and interested friends can try to use custom cells to achieve it.

 

Custom hyperlink commands

1. Create a hyperlink

sheet.setValue(32, 10, "审核人签名:")

sheet.setHyperlink(32, 10, { command: "popup" });

 

2. Set the command for the hyperlink and click to pop up the canvas

spread.commandManager().register("popup",{

                    canUndo: true,

                    execute: function (context, options, isUndo) {

                    var Commands = GC.Spread.Sheets.Commands;

                    // 在此加cmd

                    options.cmd = "popup";

                    if (isUndo) {

                           Commands.undoTransaction(context, options);

                                  return true;

                           } else {

                                  Commands.startTransaction(context, options);

 

                                 document.getElementById("box").style.display = "block";

 

                                  Commands.endTransaction(context, options);

                                        return true;

                                  }

                           }

                });

Specify the DOM to be converted to a picture and set as the cell background

1. Use the canvas interface to convert the canvas to base64 and call the interface to set the background

function convertCanvasToImage(canvas) {

                    return canvas.toDataURL("image/png");

   };

 

  function takeScreenshot() {       

      var canvas = document.getElementById("canvasEdit");

      var imgUrl = convertCanvasToImage(canvas); //截取图片路径,该路径为服务器参数

      var sheet = spread.getSheet(0); 

      sheet.getCell(32,13).backgroundImage(imgUrl);

      sheet.getCell(35,13).backgroundImage(imgUrl);

      sheet.getCell(38,13).backgroundImage(imgUrl);

}

2. Close the signature canvas


function tishi(){

      document.getElementById("box").style.display = "none";

}

setTimeout(tishi,100)

Export electronic signature to PDF

The electronic signature content has been implemented above, but we all know that the contract needs to have a printout function. Next, we will continue to introduce how to use pdf to print out the electronic signature.

 

1. Quote PDF extension files and filesaver

<script src="node_modules/@grapecity/spread-sheets-pdf/dist/gc.spread.sheets.pdf.min.js" type="text/javascript"></script>

<script src="node_modules/file-saver/dist/FileSaver.min.js" type="text/javascript"></script>

 

1. Call the interface to export PDF

spread.savePDF(function (blob) {

    var fileName = 'download';

    saveAs(blob, fileName + '.pdf');

}, function (error) {

    console.log(error);

}, {

    title: 'Test Title',

});

 

Note: To export Chinese characters, you need to register the corresponding font.


Summarize

Above, we have realized the complete function of implementing electronic signature based on Canvas spreadsheet and exporting and printing using PDF. Since Canvas completely replaces the dom structure of the page, there is no need to traverse the child nodes of the dom node to be printed when printing, and there is no need to The height of the dom node that can be printed on one page is accumulated. This can eliminate the need to calculate the height of the dom node, which greatly saves system performance. At the same time, it achieves finer page granularity without causing large blanks. It is completely simulated The kind of effect that word generates pdf. At the same time, it also solves the three problems that we mentioned at the beginning of the article: marginal margins, picture spanning, and incomplete screenshots after page scrolling.

5.jpg

Next, we will bring you more interesting content encountered in the work project.

 

It's all here, just like it and let's go~


葡萄城技术团队
2.7k 声望31.8k 粉丝

葡萄城是专业的软件开发技术和低代码平台提供商,聚焦软件开发技术,以“赋能开发者”为使命,致力于通过表格控件、低代码和BI等各类软件开发工具和服务,一站式满足开发者需求,帮助企业提升开发效率并创新开发模式。