// 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 convert url web pages or html files to PDF document.
// If using a stream to load the html file, set variable isfilestreamload to true.


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

function AnalysisParameter(argc, argv, pdf_setting_data_, url_or_html_, engine_path_, cookies_path_, output_path_, timeout_) {
  let pdf_setting_data = pdf_setting_data_;
  let engine_path = engine_path_;
  let cookies_path = cookies_path_;
  let output_path = output_path_;
  let url_or_html = url_or_html_;
  let timeout = timeout_;
  for (let i = 2; i < argc; i = i + 2) {
    let argv_key = String(argv[i]);
    let argv_value;
    if (argc < i + 2) {
      console.log("Please make sure the key %s is valid and it has value.\n", argv_key);
      console.log("Usage: html2pdf_xxx <-html <The url or html path>> <-o <output pdf path>> ...\nPlease try 'html2pdf_xxx --help' for more information.\n");
      return [false];
    }
    argv_value = argv[i + 1];
    if (argv_key == "-w") pdf_setting_data.page_width = parseFloat(argv_value);
    else if (argv_key == "-h")  pdf_setting_data.page_height = parseFloat(argv_value);
    else if (argv_key == "-r")  pdf_setting_data.rotate_degrees = parseInt(argv_value);
    else if (argv_key == "-ml")  pdf_setting_data.page_margin.left = parseFloat(argv_value);
    else if (argv_key == "-mr")  pdf_setting_data.page_margin.right = parseFloat(argv_value);
    else if (argv_key == "-mt")  pdf_setting_data.page_margin.top = parseFloat(argv_value);
    else if (argv_key == "-mb")  pdf_setting_data.page_margin.bottom = parseFloat(argv_value);
    else if (argv_key == "-scale")  pdf_setting_data.scaling_mode = parseInt(argv_value);
    else if (argv_key == "-link")  pdf_setting_data.is_convert_link = argv_value.toLowerCase() == "yes" ? true : false;
    else if (argv_key == "-tag")  pdf_setting_data.is_generate_tag = argv_value.toLowerCase() == "yes" ? true : false;
    else if (argv_key == "-mode")  pdf_setting_data.page_mode = parseInt(argv_value);
    else if (argv_key == "-bookmarks")  pdf_setting_data.to_generate_bookmarks = argv_value.toLowerCase() = "yes" ? true : false;
    else if (argv_key == "-encoding")  pdf_setting_data.encoding_format = parseInt(argv_value);
    else if (argv_key == "-render_images")  pdf_setting_data.to_render_images = argv_value.toLowerCase() = "yes" ? true : false;
    else if (argv_key == "-remove_underline_for_link")  pdf_setting_data.to_remove_underline_for_link = argv_value.toLowerCase() = "yes" ? true : false;
    else if (argv_key == "-headerfooter")  pdf_setting_data.to_set_headerfooter = argv_value.toLowerCase() = "yes" ? true : false;
    else if (argv_key == "-headerfooter_title")  pdf_setting_data.headerfooter_title = argv_value;
    else if (argv_key == "-headerfooter_url")  pdf_setting_data.headerfooter_url = argv_value;
    else if (argv_key == "-bookmark_root_name")  pdf_setting_data.bookmark_root_name = argv_value;
    else if (argv_key == "-resize_objects")  pdf_setting_data.to_resize_objects = argv_value.toLowerCase() = "yes" ? true : false;
    else if (argv_key == "-print_background")  pdf_setting_data.to_print_background = argv_value.toLowerCase() = "yes" ? true : false;
    else if (argv_key == "-optimize_tag")  pdf_setting_data.to_optimize_tag_tree = argv_value.toLowerCase() = "yes" ? true : false;
    else if (argv_key == "-media")  pdf_setting_data.media_style = parseInt(argv_value);
    else if (argv_key == "-engine")  engine_path = rgv_value;
    else if (argv_key == "-cookies")  cookies_path = argv_value;
    else if (argv_key == "-o")  output_path = argv_value;
    else if (argv_key == "-html")  url_or_html = argv_value;
    else if (argv_key == "-timeout")  timeout = parseInt(argv_value);
    else {
      console.log("Please make sure the key %s is valid and it has value.\n", argv_key);
      console.log("Usage: html2pdf_xxx <-html <The url or html path>> <-o <output pdf path>> ...\nPlease try 'html2pdf_xxx --help' for more information.\n");
      return [false];
    }
  }

  return [true, pdf_setting_data, url_or_html, engine_path, cookies_path, output_path, timeout];
}

class FileWriter {
  constructor() {
    this.m_fileFP = null;
    this.file_path_ = "";
  }

  LoadFile(file_path) {
    try {
      this.file_path_ = file_path;
      this.m_fileFP = fs.openSync(file_path, 'w');
      if (!this.m_fileFP) {
        return false;
      }
      return true;
    } catch (err) {
      console.error(err);
      return false;
    }
  }

  GetSize() {
    try {
      let stats = fs.statSync(this.file_path_);
      return stats.size;
    } catch (err) {
      console.error(err);
      return 0;
    }
  }

  Flush() {
    return true;  
  }

  WriteBlock(buffer, offset, size) { 
    try {
      const write_size = fs.writeSync(this.m_fileFP, buffer, 0, size, offset);
      if (write_size == size) {
        return true;
      } else {
        return false;
      }
    } catch (err) {
      console.error(err);
      return false;
    }
  }

  Release() {
    try {
      fs.closeSync(this.m_fileFP);
      this.m_fileFP = null;
    } catch (err) {
      console.error(err);

    }
  }
}

class FileRead {
  constructor() {
    this.file_ = null;
    this.file_path_ = "";
    this.hint_data_record_ = [];
  }

  LoadFile(file_path) {
    try {
      this.file_path_ = file_path;
      this.file_ = fs.openSync(file_path, 'r');
      return true;
    } catch (err) {
      console.error(err);
      return false;
    }
  }

  CloseFile() {
    fs.closeSync(this.file_);
  }

  GetSize() {
    try {
      let stats = fs.statSync(this.file_path_);
      return stats.size;
    } catch (err) {
      console.error(err);
      return 0;
    }
  }

  ReadBlock(offset, size_t) {
    try {
      let buffer = Buffer.alloc(size_t);
      fs.readSync(this.file_, buffer, 0, size_t, offset);
      return [true, buffer]
    } catch (err) {
      return [false, null];
    }
  }

  Release() {  }
}


if (process.argv.length > 2 && process.argv[2] == "--help") {
  console.log("Usage:" + "\n" + "html2pdf_xxx <-html <The url or html path>> <-o <output pdf path>> <-engine <htmltopdf engine path>>" + "\n" +
      " [-w <page width>] [-h <page height>] [-ml <margin left>] [-mr <margin right>] [-mt <margin top>] [-mb <margin bottom>] [-r <page rotate degree>] [-mode <page mode>] [-scale <whether scale page>]" + "\n" +
      " [-link <whether convert link>] [-tag <whether generate tag>] [-bookmarks <whether to generate bookmarks>] [-cookies <cookies file path>] [-timeout <timeout>]" + "\n" + "\n" +
      "-html The url or html file path. for examples '-html www.foxitsoftware.com'" + "\n" +
      "-o The output pdf path." + "\n" +
      "-engine The html to pdf engine path." + "\n" +
      "-w The page width." + "\n" +
      "-h The page height." + "\n" +
      "-r The page roate degree. '0' means 0 degree, '1' means 90 degree, '2' means 180 degree, '3' means 270 degree." + "\n" +
      "-ml The page margin distance of left." + "\n" +
      "-mr The page margin distance of right." + "\n" +
      "-mt The page margin distance of top." + "\n" +
      "-mb The page margin distance of bottom." + "\n" +
      "-mode The page mode. 0 means single page mode and 1 means multiple mode" + "\n" +
      "-scale The scaling mode. '0' means no scale, '1' means scale, '2' means enlarge page." + "\n" +
      "-link Whether to covert link. 'yes' means to convert link, 'no' means no need to covert." + "\n" +
      "-tag Whether to generate tag. 'yes' means to generate tag, 'no' means no need to generate." + "\n" +
      "-bookmarks  Whether to generate bookmarks.'yes' means to generate bookmarks, 'no' means no need to generate." + "\n" +
      "-encoding The HTML encoding format. '0' means auto encoding and '1'-'73' means other encodings" + "\n" +
      "-render_images Whether to render images or not.'yes' means to render images, 'no' means no need to render." + "\n" +
      "-remove_underline_for_link Whether to remove underline for link. 'yes' means to remove underline for link, 'no' means no need to remove." + "\n" +
      "-headerfooter Whether to generate headerfooter. 'yes' means to generate headerfooter, 'no' means no need to generate." + "\n" +
      "-headerfooter_title The headerfooter title." + "\n" +
      "-headerfooter_url The headerfooter url." + "\n" +
      "-bookmark_root_name The bookmark root name." + "\n" +
      "-print_background Whether to print background. 'yes' means to print background, 'no' means no need to print background." + "\n" +
      "-optimize_tag Whether to optimize tag tree. 'yes' means to optimize tag tree, 'no' means no need to optimize tag tree." + "\n" +
      "-media The media style. '0' means screen media style, '1' means print media style." + "\n" +
      "-cookies The cookies file path." + "\n" +
      "-timeout The timeout of loading webpages.");
      return;
}

//If using a stream to load the html file, set isfilestreamload to true
let isfilestreamload = false;

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 + "html2pdf/";
if (!fs.existsSync(output_directory))  {
  fs.mkdirSync(output_directory);
}

let url_or_html = input_path + "AboutFoxit.html";

// "engine_path" is the path of the engine file "fxhtml2pdf" which is used to convert html to pdf. Please refer to Developer Guide for more details.
let engine_path = "";

// "cookies_path" is the path of the cookies file exported from the web pages that you want to convert. Please refer to Developer Guide for more details.
let cookies_path = "";

output_file_path = output_directory + "html2pdf_result.pdf";

let time_out = 15;

try {
  let pdf_setting_data = new FSDK.HTML2PDFSettingData();
  pdf_setting_data.is_convert_link = true;
  pdf_setting_data.is_generate_tag = true;
  pdf_setting_data.to_generate_bookmarks = true;
  pdf_setting_data.rotate_degrees = FSDK.e_Rotation0;
  pdf_setting_data.page_height = 640;
  pdf_setting_data.page_width = 900;
  pdf_setting_data.page_mode = FSDK.HTML2PDFSettingData.e_PageModeSinglePage;
  pdf_setting_data.scaling_mode = FSDK.HTML2PDFSettingData.e_ScalingModeScale;
  pdf_setting_data.to_print_background = true;
  pdf_setting_data.to_optimize_tag_tree = false;
  pdf_setting_data.media_style = FSDK.HTML2PDFSettingData.e_MediaStyleScreen;

  let parameter = AnalysisParameter(process.argv.length, process.argv, pdf_setting_data, url_or_html, engine_path, cookies_path, output_file_path, time_out);
  if (!parameter[0]) return;
  pdf_setting_data = parameter[1];
  url_or_html = parameter[2];
  engine_path = parameter[3];
  cookies_path = parameter[4];
  output_file_path = parameter[5];
  time_out = parameter[6]; 
  FSDK.Convert.FromHTML(url_or_html, engine_path, cookies_path, pdf_setting_data, output_file_path, time_out);
  console.log("Convert HTML to PDF successfully.");
} catch (e) {
  console.log(e);
}

 //get HTML data from stream
 if (isfilestreamload) {
  try {
    let pdf_setting_data = new FSDK.HTML2PDFSettingData();
    pdf_setting_data.page_height = 650;
    pdf_setting_data.page_width = 950;
    pdf_setting_data.is_to_page_scale = false;
    pdf_setting_data.page_margin = new FSDK.RectF(18, 18, 18, 18);
    pdf_setting_data.is_convert_link = true;
    pdf_setting_data.rotate_degrees = FSDK.e_Rotation0;
    pdf_setting_data.is_generate_tag = true;

    let mode = FSDK.HTML2PDFSettingData.e_PageModeSinglePage;
    pdf_setting_data.to_generate_bookmarks = true;
    let scale = FSDK.HTML2PDFSettingData.e_ScalingModeNone;
    pdf_setting_data.encoding_format = FSDK.HTML2PDFSettingData.e_EncodingFormatDefault;
    pdf_setting_data.to_render_images = true;
    pdf_setting_data.to_remove_underline_for_link = false;
    pdf_setting_data.to_set_headerfooter = false;
    pdf_setting_data.headerfooter_title = "";
    pdf_setting_data.headerfooter_url = "";
    pdf_setting_data.bookmark_root_name = "abcde";
    pdf_setting_data.to_resize_objects = true;
    pdf_setting_data.to_print_background = false;
    pdf_setting_data.to_optimize_tag_tree = false;
    pdf_setting_data.media_style = FSDK.HTML2PDFSettingData.e_MediaStyleScreen;
    pdf_setting_data.to_load_active_content = false;
    let output_path = output_directory + "html2pdf_filestream_result.pdf";
    filewrite = new FileWriter();
    let write_callback = new FSDK.FileWriterCallback(filewrite);
    filewrite.LoadFile(output_path);
    // "htmlfile" is the path of the html file to be loaded. For example: "C:/aaa.html". The method of "FromHTML" will load this file as a stream.
    let htmlfile = "";
    filereader = new FileRead();
    filereader.LoadFile(htmlfile);
    let read_callback = new FSDK.FileReaderCallback(filereader);


    let html2PDFRelatedResourceArray = new FSDK.HTML2PDFRelatedResourceArray ;
    let html2PDFRelatedResource = new FSDK.HTML2PDFRelatedResource;

    //"htmlfilepng" is the path of the png resource file to be loaded. For example: "C:/aaa.png". set "htmlfilepng" in the related_resource_file of HTML2PDFRelatedResource.
    let htmlfilepng = "";
    let filereader1 = new FileRead();
    filereader1.LoadFile(htmlfilepng);
    let read_callback1 = new FSDK.FileReaderCallback(filereader1);
    html2PDFRelatedResource.related_resource_file = read_callback1;
    //"relativefilepath" is  the resource file's relative path. For example: "./aaa.png".
    let relativefilepath = "";
    html2PDFRelatedResource.resource_file_relative_path = relativefilepath;
    html2PDFRelatedResourceArray.Add(html2PDFRelatedResource);

    FSDK.Convert.FromHTML(read_callback, html2PDFRelatedResourceArray, engine_path, null,
                                                pdf_setting_data, write_callback, 30);
    console.log("Convert HTML to PDF successfully by filestream.");
  } catch (e) {
    console.log(e);
  }
 }
 FSDK.Library.Release();