// 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 get/set attributes of viewer preference
// and values of metadata in a PDF file.

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/";

class TextDoc {
  constructor(file_name, file_mode) {
    this.file_name = file_name;
    this.file_mode = file_mode;
    this.file_stream = fs.openSync(file_name, file_mode);
    if (!this.file_stream) {
      throw new Error('Cannot open file');
    }
  }
  Write(format, ...args) {
    if(!this.file_stream) 
      throw new Error("File not opened");
    let formatted_string = util.format(format, ...args);
    let buffer = new Buffer.from(formatted_string, 'utf-8');
    fs.writeSync(this.file_stream, buffer, 0, buffer.length);
  }
  WriteWithPrefix(count, prefix, format, ...args){
    for (let i = 0; i < count; i++) {
      this.Write(prefix);
    }
    this.Write(format, ...args);
  }
  Close() {
    fs.closeSync(this.file_stream);
    this.file_stream = null;
  }
}

function DateTimeToString(datetime) {
  const pad = number => String(number).padStart(2, '0');
  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;
}

const kUIItems = [
  FSDK.DocViewerPrefs.e_HideToolbar, FSDK.DocViewerPrefs.e_HideMenubar,
  FSDK.DocViewerPrefs.e_HideWindowUI, FSDK.DocViewerPrefs.e_FitWindow,
  FSDK.DocViewerPrefs.e_CenterWindow, FSDK.DocViewerPrefs.e_DisplayDocTitle ];

const kDisplayModes = [ FSDK.PDFDoc.e_DisplayUseNone,   FSDK.PDFDoc.e_DisplayUseOutlines,
                        FSDK.PDFDoc.e_DisplayUseThumbs, FSDK.PDFDoc.e_DisplayFullScreen,
                        FSDK.PDFDoc.e_DisplayUseOC,     FSDK.PDFDoc.e_DisplayUseAttachment ];

const kDisplayModeStrings = ["UseNone", "UseOutlines", "UseThumbs", "FullScreen", "UseOC", "UseAttachment" ];

const kBoxItemStrings = ["ViewArea", "ViewClip", "PrintArea", "PrintClip"];
function GetPageBoxName(type){
  switch (type) {
  case FSDK.PDFPage.e_MediaBox:
    return "MediaBox";
  case FSDK.PDFPage.e_CropBox:
    return "CropBox";
  case FSDK.PDFPage.e_TrimBox:
    return "TrimBox";
  case FSDK.PDFPage.e_ArtBox:
    return "ArtBox";
  case FSDK.PDFPage.e_BleedBox:
    return "BleedBox";
  }
  return "";
}

function GetViewerPrefName(ui_item) {
  switch(ui_item){
  case FSDK.DocViewerPrefs.e_HideToolbar:
    return "HideToolbar";
  case FSDK.DocViewerPrefs.e_HideMenubar:
    return "HideMenubar";
  case FSDK.DocViewerPrefs.e_HideWindowUI:
    return "HideWindowUI";
  case FSDK.DocViewerPrefs.e_FitWindow:
    return "FitWindow";
  case FSDK.DocViewerPrefs.e_CenterWindow:
    return "CenterWindow";
  case FSDK.DocViewerPrefs.e_DisplayDocTitle:
    return "DisplayDocTitle";
  }
  return "";
}

function GetViewerPrefPrintScaleName(ui_item) {
  switch(ui_item) {
  case FSDK.DocViewerPrefs.e_PrintScaleNone:
    return "PrintScaleNone";
  case FSDK.DocViewerPrefs.e_PrintScaleAppDefault:
    return "PrintScaleAppDefault";
  }
  return "";
}

function ShowDocViewerPrefsInfo(doc, file_name) {
  file_info = output_directory + "DocViewerPrefsInfo_"+ file_name;
  let text_doc = new TextDoc(file_info, "w");

  let prefs = new FSDK.DocViewerPrefs(doc, null);
  text_doc.Write("Document viewer preferences information:\r\n");
  // Get UI visibility status.
  for (let i = 0; i < kUIItems.length; i++) {
      text_doc.Write("Visibility of %s:\t%s\r\n", GetViewerPrefName(kUIItems[i]), prefs.GetUIDisplayStatus(kUIItems[i]) ? "Yes" : "No");
  }
  // Get display mode for non full-screen mode.
  let mode = prefs.GetNonFullScreenPageMode();
  let display_mode;
  for (let i = 0; i < kDisplayModes.length; i++) {
    if (mode == kDisplayModes[i]) {
      display_mode = kDisplayModeStrings[i];
      break;
    }
  }
  text_doc.Write("None full screen page mode:\t%s\r\n", display_mode);
  // Get reading direction.
  text_doc.Write("Reading direction:\t%s\r\n", prefs.GetReadingDirection() ? "left to right" : "right to left");
  // Get the type of area item.
  type = prefs.GetPrintClip();
  text_doc.Write("The GetPrintClip returned:\t%s\r\n", GetPageBoxName(type));
  type = prefs.GetPrintArea();
  text_doc.Write("The GetPrintArea returned:\t%s\r\n", GetPageBoxName(type));
  type = prefs.GetViewArea();
  text_doc.Write("The GetViewArea returned:\t%s\r\n", GetPageBoxName(type));
  type = prefs.GetViewClip();
  text_doc.Write("The GetViewClip returned:\t%s\r\n", GetPageBoxName(type));

  // Get page scaling option.
  text_doc.Write("Page scaling option:\t%s\r\n", GetViewerPrefPrintScaleName(prefs.GetPrintScale()));
  // Get the number of copies to be printed.
  text_doc.Write("The number of copies to be printed:\t%d\r\n", prefs.GetPrintCopies());
  // Get page ranges which allowed to print
  text_doc.Write("Page ranges for printing:\r\n");
  print_ranges = prefs.GetPrintRange();
  if(!print_ranges.IsEmpty())
  {
    for (let i = 0; i < print_ranges.GetSegmentCount(); i=i+1)
      text_doc.Write("\tfirst:\t%d\tlast:\t%d\r\n", print_ranges.GetSegmentStart(i), print_ranges.GetSegmentEnd(i));

  }
}

function SetDocViewerPrefsInfo(doc) {
  doc.SetDisplayMode(FSDK.PDFDoc.e_DisplayFullScreen);
  let prefs = new FSDK.DocViewerPrefs(doc, null);
  // Set UI visibility status.
  for (let i = 0; i < kUIItems.length; i++) {
    prefs.SetUIDisplayStatus(kUIItems[i], true);
  }
  // Set display mode for non full-screen mode.
  prefs.SetNonFullScreenPageMode(FSDK.PDFDoc.e_DisplayUseOutlines);
  // Set reading direction.
  prefs.SetReadingDirection(false);
  // Set the type of area item.

  prefs.SetViewArea(FSDK.PDFPage.e_CropBox);
  prefs.SetViewClip(FSDK.PDFPage.e_CropBox);
  prefs.SetPrintArea(FSDK.PDFPage.e_CropBox);
  prefs.SetPrintClip(FSDK.PDFPage.e_CropBox);
  // Set page scaling option.
  prefs.SetPrintScale(FSDK.DocViewerPrefs.e_PrintScaleNone);
  // Set the number of copies to be printed.
  prefs.SetPrintCopies(4);
  let print_range = new FSDK.Range(0, doc.GetPageCount() / 2, FSDK.Range.e_All);
  prefs.SetPrintRange(print_range);
}

let kMetadataItems = [ "Title", "Author", "Subject", "Keywords",
    "Creator", "Producer", "CreationDate", "ModDate" ];

function ShowMetaDataInfo(doc, file_name) {
  let output_file = output_directory + "MetaDataInfo_"+file_name;
  text_doc = new TextDoc(output_file, "w");
  text_doc.Write("Metadata information:\r\n");
  metadata = new FSDK.Metadata(doc);
  for (let i = 0; i < kMetadataItems.length; i++) {
    let item = kMetadataItems[i];
    text_doc.Write("%s: ", item);
    let value = metadata.GetValues(item);
    for(let j=0;j<value.GetSize();j++)
    {
      text_doc.Write("%s", value.GetAt(j));
    }
    text_doc.Write("\r\n");
  }
}

function SetMetaDataInfo(doc) {
  let kMetadataValues = ["Title set by simple demo", "Simple demo",
    "Subject set by simple demo", "Keywords set by simple demo",
    "Foxit PDF SDK", "Foxit" ];
  let metadata = new FSDK.Metadata(doc);
  for (let i = 0; i < kMetadataValues.length; i++) {
    MetadataValues = new FSDK.WStringArray() ;
    MetadataValues.Add(kMetadataValues[i]);
    metadata.SetValues(kMetadataItems[i], MetadataValues);
  }
  metadata.SetCreationDateTime(GetLocalDateTime());
  metadata.SetModifiedDateTime(GetLocalDateTime());
}


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 + "docinfo/";

if (!fs.existsSync(output_directory)) {
  fs.mkdirSync(output_directory);
}
try {
  let input_file = input_path + "AboutFoxit.pdf";
  let doc = new FSDK.PDFDoc(input_file);
  let code = doc.Load("");
  if (code != FSDK.e_ErrSuccess) {
    console.log("[Failed] Cannot load PDF document %s.\r\nError Message: %d\r\n", input_file, code);
    return 1;
  }

  // Show original information.
  ShowDocViewerPrefsInfo(doc,"original.txt");
  ShowMetaDataInfo(doc,"original.txt");

  // Set information.
  SetDocViewerPrefsInfo(doc);
  SetMetaDataInfo(doc);

  // Show new information.
  ShowDocViewerPrefsInfo(doc,"new.txt");
  ShowMetaDataInfo(doc,"new.txt");
  output_file = output_directory + "AboutFoxit_docinfo.pdf";
  doc.SaveAs(output_file, FSDK.PDFDoc.e_SaveFlagNoOriginal);
} catch (e) {
  console.log(e)
}
FSDK.Library.Release();
