// Copyright (C) 2003-2026, Foxit Software Inc..
// All Rights Reserved.
//
// http://www.foxitsoftware.com
//
// The following code is copyrighted and contains proprietary information and trade secrets of Foxit Software Inc..
// You cannot distribute any part of Foxit PDF SDK to any third party or general public,
// unless there is a separate license agreement with Foxit Software Inc. which explicitly grants you such rights.
//
// This file contains an example to demonstrate how to use Foxit PDF SDK to add, sign and verify paging seal signature
// in PDF document.

const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");
const fs = require('fs');
const os = require('os');
const path = require('path');
const util = require('util');


var sn = "bPxThFlBAYifO3yiW0C51bKbjPap1zHaf5aG5sX378TjFvB7Q0802A==";
var key = "8f3g1sGNtR8NAgfSNv+BvaJWy2fnrw36NZvzh8GUxYXvs+/YczAk4e34yqlOnmL4asgxGMO7+rlOcSHUSSKagx5g4G7VEXfkYLXnDDx77FOOedZPrFFcOCu1vT4+wOKzy1zkORq9cKtiFf44byH5sfRqf+OvELjep2teT9eF9yPCsSw2vRKljXlPy40DMP9XX1O5OTe+mSG3RvwKUMb0+RpG3YobM87j+/ynTDlJMMXw4vgwuTb1ZuAtlvkTdFz7HDLV81C6TYnn73ddHeGD3qYWBVsD4uJkDwyyH/SWr7QX0HSgVg8HSZqnab1VGdAUYxKY2vGWeOTJdu6qDGb5ZEb9O3kZZg+9LYAmUKzDfCYwfIsYZ8Y9LPC4wMx70kIq7JpNnzPvigrdshV8/ew1F0+qP/P5Z1EB53vDVrp2LVSuL873Wv4g3PzjZlNH+1qgT87hC+Buto4qsSUfP5Y2z0uApu+c/TfttCXbeMLSsw9TY1HQD3mkrZExMaQqRrAuXAcZWdvBnVuG3DCZmm8q0DLxJiCfYfViAU/AkbeKMIGaTJdrvIXBcssfde4nmU6qr0M4x4+Hs2ESddtY2QRtLAUBq/7h7GJlJHkEZr8ueaUy/6D/2vvAWz6wMLgmjlPbDTLqzfnCJylHCPtcJmu1SPPT9v1VreBX3+zNWcIT8HueyHEiUniqzwWkRKaotrnNb/zhnHLPpgaBSwKjyi8rOzzVwu/nY84G9ye4jsVjmkIRItKDrW7z22iS+QQuTwfqLVuMB0OD4jMkPCC2slzPfEeZnuh4+Rewln2qLRJVgI72zJ20OBWAelGSpO1Ii2Y3gOvojdmtUwx6R3Z1qFNWTTB25o9ytcux8BLOtTCkA8T8xaT4N339OTCsu/TmfahIDixKvr8cDa6F2WkBT8SOfv64W9PgiNv5B/BMOD2VWYaAl0N7yD0NkYYg/cDWRC4dfpdeip1jrr0k3mND0oSpIkxC+FicZbaYYwRdtJ9OSVWJ5OE0voLv8HgLze8mw6s4TrN3z+a2NQCveMa2VRN7YcEF7agPrvb/qU+otMwHae/wM7+f+HFAaOW+WTfzfxIVFB8/A1DN0NiEX+em4G7nO5F5ZcvfYPpaaioe8Nn33BbVLtMjXqsOBeM8AXiVfpD6YO75j7BqnBUPnivvD8BxJaaIQZvVSuQmvGm0ynt03IYwE8Rq+jYsunvsZ86jh5BiUR+Nm7sK0Qe9BdZn/7jdqohMv9czfMGUAscX+xBMunFbDpcRbWVpUADcm209L8Ndek2XY7YlCMxPgPVNvfWRF2jxehib9Tpd7zB5ZIDfAEH9zrpLfp29DLvCh2Yx8mH7xxdKG1O9Q0GdHphYHhej6smAcPm68R0GUQaTOLfXqNpueGJC1GAOI3Y4swjyt7jMTWcibnKLzwukWE5rnEDhn5n64JnyUM0ZFkRmtOiV";

const input_path = "../input_files/";
const output_path = "../output_files/";
const output_directory = output_path + "paging_seal_signature/";


// get current date time
function GetLocalDateTime() {
  const date = new Date();
  let timezone_hour = date.getTimezoneOffset() / 60 * -1;
  let timezone_minute = Math.abs(date.getTimezoneOffset() % 60);
  let datetime = new FSDK.DateTime(date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds(), timezone_hour, timezone_minute);
  return datetime;
}
  
function DateTimeToString(datetime) {
  const pad = number => (number < 10 ? '0' + number : String(number));
  const offsetSign = datetime.utc_hour_offset >= 0 ? '+' : '-'; 
  const hourOffset = Math.abs(datetime.utc_hour_offset);
  const minuteOffset = Math.abs(datetime.utc_minute_offset);
  return `${pad(datetime.year)}/${pad(datetime.month)}/${pad(datetime.day)}-${pad(datetime.hour)}:${pad(datetime.minute)}:${pad(datetime.second)} ${offsetSign}${pad(hourOffset)}:${pad(minuteOffset)}`;
}
  
function TransformSignatureStateToString(sig_state) {
  let state_str;
  if (sig_state & FSDK.Signature.e_TypeUnknown)
    state_str += "Unknown";
  if (sig_state & FSDK.Signature.e_StateNoSignData) {
    if (state_str != "") state_str += "|";
    state_str += "NoSignData";
  }
  if (sig_state & FSDK.Signature.e_StateUnsigned) {
    if (state_str != "") state_str += "|";
    state_str += "Unsigned";
  }
  if (sig_state & FSDK.Signature.e_StateSigned) {
    if (state_str != "") state_str += "|";
    state_str += "Signed";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyValid) {
    if (state_str != "") state_str += "|";
    state_str += "VerfiyValid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyInvalid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyInvalid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyErrorData) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyErrorData";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyNoSupportWay) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyNoSupportWay";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyErrorByteRange) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyErrorByteRange";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyChange) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyChange";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIncredible) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIncredible";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyNoChange) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyNoChange";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueValid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueValid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueUnknown) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueUnknown";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueRevoke) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueRevoke";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueExpire) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueExpire";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueUncheck) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueUncheck";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyIssueCurrent) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyIssueCurrent";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampNone) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampNone";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampDoc) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampDoc";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampValid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampValid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampInvalid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampInvalid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampExpire) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampExpire";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampIssueUnknown) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampIssueUnknown";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampIssueValid) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampIssueValid";
  }
  if (sig_state & FSDK.Signature.e_StateVerifyTimestampTimeBefore) {
    if (state_str != "") state_str += "|";
    state_str += "VerifyTimestampTimeBefore";
  }
  if (sig_state & FSDK.Signature.e_StateCertCannotGetVRI) {
    if (state_str != "") state_str += "|";
    state_str += "CertCannotGetVRI";
  }
  return state_str;
}

function AddPagingSealSiganture(pdf_doc, sub_filter, is_on_perforation) {
  let pdf_page = pdf_doc.GetPage(0);
  let page_width = pdf_page.GetWidth();
  let page_height = pdf_page.GetHeight();
  let sig_width =  page_width * 0.4;
  let sig_hegiht = page_height * 0.1;
  let range = new FSDK.Range(1, pdf_doc.GetPageCount(), FSDK.Range.e_All);
  let new_sig = pdf_doc.AddPagingSealSignature(range, sig_width, sig_hegiht, true);
  if (new_sig.IsEmpty()) return PagingSealSignature();
  
  let paging_seal_config = new FSDK.PagingSealConfig(FSDK.PagingSealConfig.e_PagingSealPositionLeft, page_width/2, 
      0.5, is_on_perforation, FSDK.PagingSealConfig.e_PagingSealStyleMultipleSignatures, false, 30);
  new_sig.SetPagingSealConfig(paging_seal_config);
    
  // Set values for the new signature.
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameSigner, "Foxit PDF SDK");
  let new_value = `As a sample for subfilter "${sub_filter}"`;
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameReason, new_value);
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameContactInfo, "support@foxitsoftware.com");
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameDN, "CN=CN,MAIL=MAIL@MAIL.COM");
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameLocation, "Fuzhou, China");
  new_value = `As a sample for subfilter "${sub_filter}"`;
  new_sig.SetKeyValue(FSDK.Signature.e_KeyNameText, new_value);
  let sign_time = GetLocalDateTime();
  new_sig.SetSignTime(sign_time);
  let image_file_path = input_path + "FoxitLogo.jpg";
  let image = new FSDK.Image(image_file_path);
  new_sig.SetImage(image, 0);
  // Set appearance flags to decide which content would be used in appearance.
  let ap_flags = FSDK.Signature.e_APFlagLabel | FSDK.Signature.e_APFlagSigner |
                      FSDK.Signature.e_APFlagReason | FSDK.Signature.e_APFlagDN |
                      FSDK.Signature.e_APFlagLocation | FSDK.Signature.e_APFlagText |
                      FSDK.Signature.e_APFlagSigningTime | FSDK.Signature.e_APFlagBitmap;
  new_sig.SetAppearanceFlags(ap_flags);
  let gaResult = new_sig.GenerateAppearance();
  return new_sig;
}

function AdobePPKLitePagingSealSignature(pdf_doc) {
  let filter = "Adobe.PPKLite";
  let sub_filter = "adbe.pkcs7.detached";

  console.log("Use signature callback object for filter \"%s\" and sub-filter \"%s\"",
    filter, sub_filter);
  // Add a new paging seal signature to the document.
  let is_on_perforation = false;
  let new_paging_seal_signature = AddPagingSealSiganture(pdf_doc, sub_filter, is_on_perforation);
  // Set filter and subfilter for the new  paging seal signature.
  new_paging_seal_signature.SetFilter(filter);
  new_paging_seal_signature.SetSubFilter(sub_filter);
  let is_signed = new_paging_seal_signature.IsSigned();
  let sig_state = new_paging_seal_signature.GetState();
  console.log("[Before signing] Signed?:%s\t State:%s",
          is_signed? "true" : "false",
          TransformSignatureStateToString(sig_state));

  // Sign the new signature.
  let signed_pdf_path = output_directory + "signed_left_paging_seal_signature_default_handler.pdf";
  let cert_file_path = input_path + "foxit_all.pfx";
  let cert_file_password = "123456";
  // Cert file path will be passed back to application through callback function FSSignatureCallback::Sign().
  // In this demo, the cert file path will be used for signing in callback function FSSignatureCallback::Sign().
  new_paging_seal_signature.StartSign(cert_file_path, cert_file_password,
                          FSDK.Signature.e_DigestSHA1, signed_pdf_path, null, null);
  console.log("[Sign] Finished!");
  is_signed = new_paging_seal_signature.IsSigned();
  sig_state = new_paging_seal_signature.GetState();
  console.log("[After signing] Signed?:%s\tState:%s",
          is_signed? "true" : "false",
          TransformSignatureStateToString(sig_state));

  // Open the signed document and verify the newly added paging seal signature (which is the last one).
  console.log("Signed PDF file: %s", signed_pdf_path);
  let signed_pdf_doc = new FSDK.PDFDoc(signed_pdf_path);
  let error_code = signed_pdf_doc.Load("");
  if (FSDK.e_ErrSuccess !=error_code ) {
    console.log("Fail to open the signed PDF file.");
    return;
  }
  // Get the last signature which is just added and signed.
  let sig_count = signed_pdf_doc.GetSignatureCount();
  let signed_signature = signed_pdf_doc.GetSignature(sig_count-1);
  // Verify the intergrity of signature.
  signed_signature.StartVerify(null, null);
  console.log("[Verify] Finished!");
  is_signed = signed_signature.IsSigned();
  sig_state = signed_signature.GetState();
  console.log("[After verifying] Signed?:%s\tState:%s",
          is_signed? "true" : "false",
          TransformSignatureStateToString(sig_state));
}

function CheckPagingSealSignatureInfo(pdf_doc) {
  let signature_count = pdf_doc.GetSignatureCount();
  if (signature_count<1) {
    console.log("No signature in current PDF file.");
    return;
  }
  for (let i = 0; i < signature_count; i++) {
    console.log("Signature index: %d", i);
    let signature = pdf_doc.GetSignature(i);
    if (signature.IsEmpty()) continue;
    let is_signed = signature.IsSigned();
    console.log("Signed?:%s", is_signed? "true":"false");
    let sig_state = signature.GetState();
    console.log("State:%s", TransformSignatureStateToString(sig_state));
  
    let widget_annot = signature.GetControl(0).GetWidget();
    console.log("Object number %d of related widget annotation's dictionary", widget_annot.GetDict().GetObjNum());
  
    let filter = signature.GetFilter();
    console.log("Filter:%s",filter);
    let sub_filter = signature.GetSubFilter();
    console.log("Sub-filter:%s", sub_filter);
    if (is_signed){
      let sign_time = signature.GetSignTime();
      let time_str = DateTimeToString(sign_time);
        console.log("Sign Time:%s", time_str);
    }
    let key_value;
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameSigner);
    console.log("Signer:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameLocation);
    console.log("Location:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameReason);
    console.log("Reason:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameContactInfo);
    console.log("Contact Info:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameDN);
    console.log("DN:%s", key_value);
    key_value = signature.GetKeyValue(FSDK.Signature.e_KeyNameText);
    console.log("Text:%s", key_value);
  }
}

let error_code = FSDK.Library.Initialize(sn, key);
if (FSDK.e_ErrSuccess != error_code) {
  if (FSDK.e_ErrInvalidLicense == error_code)
    console.log("[Failed] Current used Foxit PDF SDK key information is invalid.");
  else
    console.log("Library Initialize Error: %d", FSDK.e_ErrSuccess);
  return;
}

if (!fs.existsSync(output_directory)) {
  fs.mkdirSync(output_directory);
}

let input_file = input_path + "AboutFoxit.pdf";
console.log("Input file path: %s", input_file);
try {
  for (let i = 0; i < 1; i++) {
    let pdf_doc = new FSDK.PDFDoc(input_file);
    pdf_doc.StartLoad("", false, null);
    // Check information of existed signature(s) in PDF file if there's any signature in the PDF file.
    CheckPagingSealSignatureInfo(pdf_doc);
    // Add new signature, sign it and verify it with filter "Adobe.PPKLite" and different subfilter.
    let signed_pdf_path = output_directory + "signed_left_paging_seal_signature_default_handler.pdf";
    AdobePPKLitePagingSealSignature(pdf_doc);
    let pdf_doc1 = new FSDK.PDFDoc(signed_pdf_path);
    pdf_doc1.StartLoad("", false, null);
    CheckPagingSealSignatureInfo(pdf_doc1);
  }
} catch (e) {
  console.log(e);
}
FSDK.Library.Release();