Skip to content
Snippets Groups Projects
utils.ts 5.55 KiB
Newer Older
  • Learn to ignore specific revisions
  • Zdravko Iliev's avatar
    Zdravko Iliev committed
    import {
      nopodofo as npdf,
      NPDFAnnotation,
      NPDFAnnotationFlag,
      pdfDate,
    } from "nopodofo";
    import path from "path";
    import { readFileSync } from "fs";
    import { PDFNet } from "@pdftron/pdfnet-node";
    
    Zdravko Iliev's avatar
    Zdravko Iliev committed
    
    export const pdf = (document: any): Promise<any> => {
      return new Promise((resolve, reject) => {
        const doc = new npdf.Document();
        return doc.load(document, { forUpdate: true }, (e, data: any) => {
          if (e instanceof Error) {
            reject(e);
          }
          resolve(data);
        });
      });
    };
    
    Zdravko Iliev's avatar
    Zdravko Iliev committed
    
    export const write = (document: any): Promise<Buffer> => {
      return new Promise((resolve, reject) => {
        document.write((err, buf) => {
          if (err instanceof Error) {
            reject(err);
          }
          resolve(buf);
        });
      });
    };
    
    export const getSignatureField = (doc: any) => {
      const rect = new npdf.Rect(360, 685, 50, 20),
        page = doc.getPage(0),
        annot = page.createAnnotation(NPDFAnnotation.Widget, rect);
      annot.flags = NPDFAnnotationFlag.Print;
    
      const image = new npdf.Image(doc, path.join(__dirname, "/qrcode.png"));
      const painter = new npdf.Painter(doc);
      painter.setPage(page);
      painter.drawImage(image, rect.left, rect.bottom, {
        width: rect.width,
        height: rect.height,
      });
      painter.finishPage();
      // end apply image to page
    
      const field = new npdf.SignatureField(annot, doc);
    
      // Set field properties
      field.setReason("test");
      field.setLocation("here");
      field.setCreator("me");
      field.setFieldName("signer.sign");
    
      // This will set the date as now
      field.setDate();
    
      return field;
    };
    
    export const sign = (signer: any): Promise<Buffer> => {
      const certificate = Buffer.from(
        readFileSync(path.join(__dirname, "/certificate.pem"))
      );
      const pkey = Buffer.from(readFileSync(path.join(__dirname, "/key.pem")));
    
      return new Promise((resolve, reject) => {
        signer.loadCertificateAndKey(
          certificate,
          {
            pKey: pkey,
          },
          (error, signatureLength) => {
            if (error) {
              reject(error);
            }
            signer.write(signatureLength, (e, d) => {
              if (e) {
                reject(e);
              }
              resolve(d);
            });
          }
        );
      });
    };
    
    function writeAp(pdfWriter, { w, h }, text, objId) {
      const xf = pdfWriter.createFormXObject(0, 0, w, h, objId);
    
      // draw text starting 1/4 of the way up
      const textY = h / 4;
    
      xf.getContentContext().writeText(text, 0, textY, {
        size: fontSize,
        colorspace: "rgb",
        color: 0xfc2125,
        font: arialFont,
      });
    
      pdfWriter.endFormXObject(xf);
    }
    
    export const TimestampAndEnableLTV = async (
      in_docpath,
      in_trusted_cert_path,
      in_appearance_img_path
    ) => {
      const doc = await PDFNet.PDFDoc.createFromBuffer(in_docpath);
      doc.initSecurityHandler();
      const doctimestamp_signature_field = await doc.createDigitalSignatureField();
      const tst_config = await PDFNet.TimestampingConfiguration.createFromURL(
        "http://rfc3161timestamp.globalsign.com/advanced"
      );
      const opts = await PDFNet.VerificationOptions.create(
        PDFNet.VerificationOptions.SecurityLevel.e_compatibility_and_archiving
      );
      /* It is necessary to add to the VerificationOptions a trusted root certificate corresponding to 
      the chain used by the timestamp authority to sign the timestamp token, in order for the timestamp
      response to be verifiable during DocTimeStamp signing. It is also necessary in the context of this 
      function to do this for the later LTV section, because one needs to be able to verify the DocTimeStamp 
      in order to enable LTV for it, and we re-use the VerificationOptions opts object in that part. */
      await opts.addTrustedCertificateUString(in_trusted_cert_path);
      /* By default, we only check online for revocation of certificates using the newer and lighter 
      OCSP protocol as opposed to CRL, due to lower resource usage and greater reliability. However, 
      it may be necessary to enable online CRL revocation checking in order to verify some timestamps
      (i.e. those that do not have an OCSP responder URL for all non-trusted certificates). */
      await opts.enableOnlineCRLRevocationChecking(true);
    
      const widgetAnnot =
        await PDFNet.SignatureWidget.createWithDigitalSignatureField(
          doc,
          new PDFNet.Rect(0, 100, 200, 150),
          doctimestamp_signature_field
        );
      await (await doc.getPage(1)).annotPushBack(widgetAnnot);
    
      // (OPTIONAL) Add an appearance to the signature field.
      const img = await PDFNet.Image.createFromMemory2(doc, in_appearance_img_path);
      await widgetAnnot.createSignatureAppearance(img);
    
      console.log("Testing timestamping configuration.");
      const config_result = await tst_config.testConfiguration(opts);
      if (await config_result.getStatus()) {
        console.log(
          "Success: timestamping configuration usable. Attempting to timestamp."
        );
      } else {
        // Print details of timestamping failure.
        console.log(await config_result.getString());
        if (await config_result.hasResponseVerificationResult()) {
          const tst_result = await config_result.getResponseVerificationResult();
          console.log(
            "CMS digest status: " + (await tst_result.getCMSDigestStatusAsString())
          );
          console.log(
            "Message digest status: " +
              (await tst_result.getMessageImprintDigestStatusAsString())
          );
          console.log(
            "Trust status: " + (await tst_result.getTrustStatusAsString())
          );
        }
        // return false; throw error instead
      }
    
      await doctimestamp_signature_field.timestampOnNextSave(tst_config, opts);
    
      // Save/signing throws if timestamping fails.
      const res = await doc.saveMemoryBuffer(
        PDFNet.SDFDoc.SaveOptions.e_incremental
      );
    
      return res.buffer;
    };