// 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 table to 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 output_path = "../output_files/";

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)}`;
}

// 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 GetTableTextStyle(index) {
  let style = new FSDK.RichTextStyle();
  style.font = new FSDK.Font(FSDK.Font.e_StdIDHelvetica);
  style.text_size = 10;
  style.text_alignment = FSDK.e_AlignmentLeft;
  style.text_color = 0x000000;
  style.is_bold = false;
  style.is_italic = false;
  style.is_underline = false;
  style.is_strikethrough = false;
  style.mark_style = FSDK.RichTextStyle.e_CornerMarkNone;

  switch (index) {
  case 1:
    style.text_alignment = FSDK.e_AlignmentCenter;
    break;
  case 2: {
    style.text_alignment = FSDK.e_AlignmentRight;
    style.text_color = 0x00FF00;
    break;
  }
  case 3:
    style.text_size = 15;
    break;
  case 4: {
    if (os.platform() === 'linux') {
      style.font = new FSDK.Font("FreeSerif", 0, FSDK.Font.e_CharsetANSI, 0);
    } else {
      style.font = new FSDK.Font("Times New Roman", 0, FSDK.Font.e_CharsetANSI, 0);
    }
    style.text_color = 0xFF0000;
    style.text_alignment = FSDK.e_AlignmentRight;
    break;
  }
  case 5: {    
    if (os.platform() === 'linux') {
      style.font = new FSDK.Font("FreeSerif", 0, FSDK.Font.e_CharsetANSI, 0);
    } else {
      style.font = new FSDK.Font("Times New Roman", 0, FSDK.Font.e_CharsetANSI, 0);
    }
    style.is_bold = true;
    style.text_alignment = FSDK.e_AlignmentRight;
    break;
  }
  case 6: {
    style.is_bold = true;
    style.is_italic = true;
    break;
  }
  case 7: {
    style.is_bold = true;
    style.is_italic = true;
    style.text_alignment = FSDK.e_AlignmentCenter;
    break;
  }
  case 8: {
    style.is_underline = true;
    style.text_alignment = FSDK.e_AlignmentRight;
    break;
  }
  case 9:
    style.is_strikethrough = true;
    break;
  case 10:
    style.mark_style = FSDK.RichTextStyle.e_CornerMarkSubscript;
    break;
  case 11:
    style.mark_style = FSDK.RichTextStyle.e_CornerMarkSuperscript;
    break;
  default:
    break;
  }
  return style;
}

function GetTableCellText(index) {
  let cell_text = "";
  switch (index) {
  case 0:
    cell_text = "Reference style";
    break;
  case 1:
    cell_text = "Alignment center";
    break;
  case 2:
    cell_text = "Green text color and alignment right";
    break;
  case 3:
    cell_text = "Text font size 15";
    break;
  case 4: {
    if (os.platform() === 'linux') {
      cell_text = "Red text color, FreeSerif font and alignment right";
    } else {
      cell_text = "Red text color, Times New Roman font and alignment right";
    }
    break;
  }
  case 5: {
    if (os.platform() === 'linux') {
      cell_text = "Bold, FreeSerif font and alignment right";
    } else {
      cell_text = "Bold, Times New Roman font and alignment right";
    }
    break;
  }
  case 6:
    cell_text = "Bold and italic";
    break;
  case 7:
    cell_text = "Bold, italic and alignment center";
    break;
  case 8:
    cell_text = "Underline and alignment right";
    break;
  case 9:
    cell_text = "Strikethrough";
    break;
  case 10:
    cell_text = "CornerMarkSubscript";
    break;
  case 11:
    cell_text = "CornerMarkSuperscript";
    break;
  default:
    cell_text = " ";
    break;
  }

  return cell_text;
}

function AddElectronicTable(page) {

  // Add a spreadsheet with 4 rows and 3 columns
  {
    let index = 0;
    let cell_array = new FSDK.TableCellDataArray();
    
    for (let row = 0; row < 4; row++) {
      let col_array = new FSDK.TableCellDataColArray();
      for (let col = 0; col < 3; col++) {
        style = GetTableTextStyle(index);
        let cell_text = GetTableCellText(index++);
        let cell_data = new FSDK.TableCellData(style, 0xFFFFFFFF, cell_text, new FSDK.Image(), new FSDK.RectF());
        col_array.Add(cell_data);
      }
      cell_array.Add(col_array);
    }
    let page_width = page.GetWidth();
    let page_height = page.GetHeight();
 
    let outside_border_left = new FSDK.TableBorderInfo();
    outside_border_left.line_width = 1;
    let outside_border_right = new FSDK.TableBorderInfo();
    outside_border_right.line_width = 1;
    let outside_border_top = new FSDK.TableBorderInfo();
    outside_border_top.line_width = 1;
    let outside_border_bottom = new FSDK.TableBorderInfo();
    outside_border_bottom.line_width = 1;
    let inside_border_row = new FSDK.TableBorderInfo();
    inside_border_row.line_width = 1;
    let inside_border_col = new FSDK.TableBorderInfo();
    inside_border_col.line_width = 1;
    let data = new FSDK.TableData(new FSDK.RectF(100, 550, page_width - 100, page_height - 100), 4, 3, outside_border_left, outside_border_right, outside_border_top, outside_border_bottom, inside_border_row, inside_border_col, new FSDK.TableCellIndexArray(), new FSDK.FloatArray(), new FSDK.FloatArray());
    FSDK.TableGenerator.AddTableToPage(page, data, cell_array);
  }

  //Add a spreadsheet with 5 rows and 6 columns
  {
    let cell_array = new FSDK.TableCellDataArray();
    let cell_text = " ";
    for (let row = 0; row < 5; row++) {
      let col_array = new FSDK.TableCellDataColArray();
      for (let col = 0; col < 6; col++) {
        let style = GetTableTextStyle(row);
        switch (col) {
        case 0:
          cell_text = "First column";
          break;
        case 1:
          cell_text = "Second column";
          break;
        case 2:
          cell_text = "Third column";
          break;
        case 3:
          cell_text = "Fourth column";
          break;
        case 4:
          cell_text = "Fifth column";
          break;
        case 5:
          cell_text = DateTimeToString(GetLocalDateTime());
          break;
        default:
          cell_text = " ";
          break;
        }
        let cell_data = new FSDK.TableCellData(style, 0xFFFFFFFF, cell_text, new FSDK.Image(), new FSDK.RectF());
        col_array.Add(cell_data);
      }
      cell_array.Add(col_array);
    }

    let page_width = page.GetWidth();
    let page_height = page.GetHeight();
    let outside_border_left = new FSDK.TableBorderInfo();
    outside_border_left.line_width = 2;
    let outside_border_right = new FSDK.TableBorderInfo();
    outside_border_right.line_width = 2;
    let outside_border_top = new FSDK.TableBorderInfo();
    outside_border_top.line_width = 2;
    let outside_border_bottom = new FSDK.TableBorderInfo();
    outside_border_bottom.line_width = 2;

    let inside_border_row = new FSDK.TableBorderInfo();
    inside_border_row.line_width = 2;
    let inside_border_col = new FSDK.TableBorderInfo();
    inside_border_col.line_width = 2;
    let data = new FSDK.TableData(new FSDK.RectF(10, 200, page_width - 10, page_height - 350), 5, 6, outside_border_left, outside_border_right, outside_border_top, outside_border_bottom, inside_border_row, inside_border_col, new FSDK.TableCellIndexArray(), new FSDK.FloatArray(), new FSDK.FloatArray());
    FSDK.TableGenerator.AddTableToPage(page, data, cell_array);
  }
}

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;
}

let output_directory = output_path + "electronictable/";

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

try {
  let doc = new FSDK.PDFDoc();
  let page = doc.InsertPage(0, FSDK.PDFPage.e_SizeLetter);
  AddElectronicTable(page);
  // Save PDF file
  let new_pdf = output_directory + "electronictable_result.pdf";
  doc.SaveAs(new_pdf, FSDK.PDFDoc.e_SaveFlagNoOriginal);
  console.log("electronictable demo.");
}
catch (e) {
  console.log(e);
}
FSDK.Library.Release();