// 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("@fuxinsoft/foxit-pdf-sdk-node");
const fs = require('fs');
const os = require('os');
const path = require('path');
const util = require('util');

var sn = "Rew1vB0TqoMIxX444UcpScARWdhgJpsJfzmyMLR32a0+EgrCjp2NaQ==";
var key = "8f3g1sFttW8NAgfSNv+BvaJWy4Pp8flcm7ncNDkdvCCO4JwUFbGLyZdujReMaiplbYJwwxam3lr7uHtQaEf0xTSu8j2ZBdrZ8FS4OQkEUjOI9UEGb3Ic0GqmlP9T9OnSItOYqoZZA/OnYg5EaVP+c/ha32nUquOk+5riEdhYgINAZDdgJkPc+YSWsrfixOIROf6t34j3eRcyFnOY0MS7tSXi1AEPE0VZdyu+5bfmBSGvLI+WR5lQ+oOQR5hRGwqf990WEdBelNO7dxhZELVhEZ+/L60PpDf5y9A8qmrY6PiEU8nhqIyLpks0BxeIsYyZ3Cr82jjfbItPGyEARsIVzluBSgVMD4oGjojz8T6wGDEXUbmZH/pra94XAs8wZ28mzbmIEppWnhBqX0c6Ov8iXCfFfUZr4KNuPxMEgk4VOYTMOd70GEjGnylivw18hbn7ZpkWh2Zql+uU2HejvOgn+WHvT0HF9NhK0Xb5vH8aFkgBP92PJx8obIbxBVeeExczxvsqWufuPdXS2sPNIgMYZ2TtvqVVsiUToeGB2FQo09fzZOSH5Vi18u/siyvC3FmjeMf4+OYWPuDPNCcrb21NgcHam7XI8AAoGLTGtLLWR+fxynbBBcg2d2ZPcZ5CMFIfOBHRWCkcA0sDT3cl9nsBppHNJze/jVxHy+lREeQEA/etSIgohTGAWW3ZlpibRXqMxlmVWEPifCubbWTzQ6U54mRMpW2UghH3gvCNFNgdday3Av7EtlIJOdUuiMq3zmmd5J4Jt4C82CKnVewA0DtZ4EEtwRG9IYuLrfpuZlnjBAtoeXRV1lqUZ6BcCe0E3m9jO28sGkALuIeJQ74XG7X8lMC7lMWWQYiYD7D6G9QT6X3qV4vXJwNKRKpYc/rI+amEawTSnDYAMEaYPwtZ0rb/7BL+atsZZaI+ncebdfVfjDJZbCZAc+JnkuNlUn2xrNRuObw8h/G0lm2pNOEJ10S8R4+yplo5B1QmC2dCDhaTaW67QJPqnJPKbVmjw7i6KGBi+CDP3JnAKlOX/YUu8uk56JfeQUuGcQg/KaBMGctnchH2n1i3+oGbibhurQj22+OO66Q6mijKoCRP/QJm5WTGcO4c0iVX0B8dIlai/uv/pGU8Wps9MxysH5ViVIj56LWKuNfy1FNO9+wx4iHYnUxfW0Iccq3YJYAlOBkMv8VZIJl9aTEEFJ626LJEw/UbEBdR9CdlwnylPf4RuNW/lcGYMgq3xNVpp/bzYKwZivvQOFgMdX1tv8D33SHvAm3zrRCU+v94BJXnBi9k25fnKsc705IMwv+I6bueXA+mDnagj1oTqsWXZ0WnPAYI3WUO7sBf7XUH230wfYXnTSVhujJxiEP/2oWqi2813gtQkKwz9N2p6yT8Vsh3+BaAwwDvtOZMJKUFcabTBSL6NoouzmzwItJ4mIboT6KXaef66rs8jCU=";


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();