// 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("@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 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();