DEV Community

Cover image for How to add Signatures to a text Field of a PDF in MERN Stack
MUNEEB WAQAS
MUNEEB WAQAS

Posted on

How to add Signatures to a text Field of a PDF in MERN Stack

Introduction:

In today's digital age, electronic signatures play a vital role in various applications, from signing contracts to validating transactions. Integrating signature functionality into web applications is crucial for streamlining processes and enhancing user experience. In this guide, we'll explore how to implement a signature pad in React.js and then incorporate that signature into a text field within a PDF document in a MERN (MongoDB, Express.js, React.js, Node.js) stack.

Part 1:

Implementing Signature Pad in React.js First, let's set up a React.js project and integrate a signature pad component. We'll be using the

react-signature-canvas

Library for this purpose, which provides an easy-to-use API for capturing signatures.This is the link for the npm package

Npm Package if react-signature-canvas

Step 1:

Installing the Signature Pad Library
Next, install the react-signature-canvas library using npm or yarn:

npm install react-signature-canvas

Step 2:

Integrating the Signature Pad Component Now, let's create a component called SignaturePad and integrate the SignatureCanvas component provided by react-signature-canvas.This is my ReactJS Code

const Done = ()=>{
    seturl(sign.getTrimmedCanvas().toDataURL('image/png'));
}
const Clear = ()=>{
  sign.clear();
}

const Forward = ()  => {
          console.log(url);
          axios.post('http://localhost:8080/send-data',{mydata  , price , IBAN , Rechnungsanschrift , Kontoinhaber , Gebäude , Gebäudeinhaber , url},{withCredentials : true}).then((response)=>{
                alert('PDF Saved'); 
        }).catch((error)=>{
        console.log(error);
              alert(error + 'in the PDF');
        })
  }

const [sign,setsign] = useState();
  const [url , seturl] = useState('');
Enter fullscreen mode Exit fullscreen mode

This is my JSX Code

<div className='justify-content-center align-items-center canvas'>
                              <SignatureCanvas penColor='black'
               canvasProps={{className: 'sigCanvas canvas'}}
                  ref={data=>setsign(data)}
              />
                    </div>

                    <Button className={`rounded-5 w-25 m-3 btn-white`}  onClick={Clear}>
Cancel
                    </Button>
                    <Button className={`rounded-5 w-25 m-3 btn-white`}  onClick={Done}>
Save
                    </Button>
Enter fullscreen mode Exit fullscreen mode

Explanation of the code

This code snippet is a React component that allows a user to draw a signature on a canvas using the SignatureCanvas component.

Here's a breakdown of the functionality:

Done: This function is called when the user clicks the "Save" button. It retrieves the data URL of the signature canvas, representing the drawn signature, and sets it in the component's state variable url.

Clear: This function is called when the user clicks the "Cancel" button. It clears the signature canvas.

Forward: This function is called when the user clicks a button to send data to a server. It sends various data, including the signature URL (url), to an endpoint using an Axios POST request.

useState: This hook is used to initialize state variables. sign is used to hold a reference to the SignatureCanvas component, and url is used to store the data URL of the drawn signature.

SignatureCanvas: This component provides a canvas for the user to draw a signature. It's configured with a black pen color and assigned a reference using the ref attribute, allowing access to its methods and properties.

Buttons: Two buttons are rendered for the user to interact with the signature canvas. One button clears the canvas (Clear), and the other saves the drawn signature (Done).

Part 2:

Adding Signature to a PDF Text Field in MERN Stack
Now, let's move on to integrating the signature captured in our React.js application with a PDF document in the MERN stack.

Step 1:

Create an Express.js API Endpoint Set up an Express.js server and create an API endpoint to receive and store signature data.

app.post('/send-data' ,  async (req,res)=>{

  const {mydata  , price , IBAN , Rechnungsanschrift , Kontoinhaber , Gebäude , Gebäudeinhaber , url} = req.body;
}
// Now this image object has the URL of the captured
Enter fullscreen mode Exit fullscreen mode

Step 2:

Add Signature to PDF Document Using a library like pdf-lib, you can dynamically generate a PDF document with the signature added to a text field.
const pdfDoc = await PDFDocument.load(await readFile('NameofPDFFILE.pdf'));

Fetching and Embedding Image in PDF Document
 
This code snippet demonstrates the process of fetching an image from a URL and embedding it into a PDF document

 

const imageBytes = await fetchImageFromUrl(URL);
const image = await pdfDoc.embedPng(imageBytes);

Enter fullscreen mode Exit fullscreen mode

Get the Signature/Text Field from the PDF and paste the image there

const signature = form.getTextField('Datum und Unterschrift');
signature.setFontSize(25);
signature.setImage(image);

Enter fullscreen mode Exit fullscreen mode

Tutorial for Making Frontend in order to capture end user's Signature

Top comments (0)