// 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 Conversion 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 Conversion SDK to convert Office(Word, Excel or PowerPoint) format files to PDF files.

var {
  ErrorCode,
  Library,
  Office2PDF,
  Word2PDFSettingData,
  Excel2PDFSettingData,
  Office2PDFSettingData,
  ReaderCallback,
  StreamCallback } = require("@foxitsoftware/foxit-pdf-conversion-sdk-node");
var fs = require('fs');


class CustomReaderCallback extends ReaderCallback {
  LoadFile(file_path) {
    this.file_path = file_path;
    this.fd = fs.openSync(file_path, 'r');
  }

  GetSize() {
    var states = fs.statSync(this.file_path);
    return states.size;
  }

  ReadBlock(offset, size) {
	var buf = Buffer.alloc(size);
    var read_size = fs.readSync(this.fd, buf, 0, size, offset);
    if (read_size == 0) {
      return "";
    }
    return buf.toString('binary');
  }
}

class CustomStreamCallback extends StreamCallback{
  LoadFile(file_path) {
    this.file_path = file_path;
    this.fd = fs.openSync(file_path, 'w+')
    this.curpos = 0;
    this.offset = 0;
    this.ref_ = 1;
  }

  Retain() {
    this.ref_ ++;
    return this;
  }

  Release() {
    this.ref_ -= 1;
    if(this.ref_ == 0)
      fs.closeSync(this.fd);
  }

  GetSize() {
    var states = fs.statSync(this.file_path);
    return states.size;
  }

  IsEOF() {
    var states = fs.statSync(this.file_path);
    return this.curpos - this.offset >= states.size;
  }

  GetPosition() {
    return this.curpos;
  }

  ReadBlock0(offset, size) {
    var buf = Buffer.alloc(size);
    this.offset = offset;
    var read_size = fs.readSync(this.fd, buf, 0, size, offset);
    if (read_size == 0) {
      return false;
    }
    this.curpos = offset + size;
    return buf.toString('binary');
  }

  ReadBlock1(buffer, size) {
    var states = fs.statSync(this.file_path);
    return ReadBlock0(buffer, states.size(), size);
  }

  WriteBlock(buffer, offset, size) {
    this.offset = offset;
    var buf = Buffer.from(buffer,'binary');
    var write_size = fs.writeSync(this.fd, buf,0,size,offset);
    if (write_size == size) {
      this.curpos = offset + size;
      return true;
    }
    return false;
  }

  Flush(user_data) {
  }
}

var sn = "P3UzPXKJGf7OHTSbhZ6tlBV431IfR0JhCBZo/XUOrENG7KfnzSYbZQ==";
var key = "LTceEOhprTpgi0mLVrxVJm5hqR99zNi1ZCtecxHwMXEuEdHxIQbDJonAF2d37PmvGSN6/PbNarMuKcHQThgXJNojhT75ZAjj166X09vSA51spwLdwH0ykA+v+q+AsQSod/Ib4LZ0i9BkazwVDe0Odn8crtBo7/+0yc5a/mWzNrFdoDMs17PpYQ0LBc6SKD+CAjTzv5oPSaJPU/IGgA2mJTHqNrgacs6IDVJs8rXuDSKVyRZKni//QpBOMCvxkYg9QhIluwBHkbJYtzCJO7ClQrwXq7CJTK46jB6ZNyGX1UFLX+Jt9U6MbBeNPrNvqMaCxkySz92mp+hIxWaVKfWUMT0o7teeScZif9fA58wixmblBm8FuZ1L1+OP9dfwp73vgd3srp28KBt6xZK+MhltDT6QQZlFcLJulFIPaU3+ZvyvOWrEI8ffd3TGHg7/VA8F2uJpz1inLxBF2+NwK+4uD0zVyvBrLS3Z1VgCh22l1XleaUbpBzjcKt0YMxa4tKJpBKUx9FZwwLCKvEb8DJuZ4PMLRSbLv6MVGzR4EZce0opAPxSHdiaxYMONX1K5HOR4uMH6RuncTAXGjEnNB2El3pk5Gw7+a1SlR2rIEKyTLzV4EXnC3eDSPAIufLlrNA8zUOAPvBaMCjCyMlDospzAf0FJwWVhn12zC3PRzq+kiFijLX+XvenWaAlR26NKMXjqySFXQQMxFtN7+Q9ppdxh05h3C7vXcLnD+eXU/vNOWwV0ymMsomQobDnkR8qrcNJkM3/IysaxaszU+4w2EAtYadZ542+LaSpW8YlvM0HqXdtBG7tx/a0qSBFZxSsr+MQZZzpJFZj3VrEakiwuVRztFGLqudrPYWC0HecrcQLO+SGF0kEcpaNZ+ydmveXlpsaIgwro/mzeZHqxFQ8n3W8xHO2bL5CE6KGLwCMZECgnXbLI7SWfuuWOxlkkbxRW1nFA4/VbLWgR7mC2Ax7R5qZd/q3Pzp8s4L0S2Hym2g/3OdjC4RF7SrXhDRWyAwICE/vKaa1nHDLv8XOiKnzz7jDeFBH2ScbfqovUiArVQyzTXxvQ7qhIxg4LatrBNv4k17p2DIRSP/hZBoFmpUEFGnqm6zC6fbkfkJ/ljbjuoTGziFwNHZ2iX//w1TJOGqDQE3Hd3rHJXWqmzpshXCrn1nn1FhbhePiIirnO12XFR2852ltgN/pQXzrZkjhzcoTTZAd6lSsj10q/8wDvOKG0ITbO34f9iO9XAm/WopOpSP2S2HoyxRJJQqbD/94ZR0Uw";

var error_code = Library.Initialize(sn, key);
if (ErrorCode.e_ErrSuccess != error_code) {
  if (ErrorCode.e_ErrInvalidLicense == error_code)
    console.log("[Failed] Current used Foxit PDF Conversion SDK key information is invalid.");
  else
    console.log("Library Initialize Error: %d", error_code);
  return;
}

var input_dir = "../input_files/";
var output_dir = "../output_files/office2pdf/";
if (!fs.existsSync(output_dir)) {
  fs.mkdirSync(output_dir);
}


var word_setting_data = new Word2PDFSettingData(false);
var excel_setting_data = new Excel2PDFSettingData(false, false, null);
var setting_data = new Office2PDFSettingData("../../../res/office2pdf", false, word_setting_data, excel_setting_data);
var src_word_path = input_dir + "word.docx";
var saved_pdf_file_path = output_dir + "word2pdf_withpath_result.pdf";
try {
  Office2PDF.ConvertFromWordWithPath(src_word_path, "", saved_pdf_file_path, setting_data);
  console.log("Convert Word format file to PDF file with path.");
} catch (e) {
  console.log(e);
}

try {
  var custom_readercallback_word = new CustomReaderCallback();
  var custom_streamcallback_word = new CustomStreamCallback();
  var src_pdf_path = input_dir + "word.docx";
  var saved_pdf_file_path = output_dir + "word2pdf_withstream_result.pdf";
  custom_readercallback_word.LoadFile(src_pdf_path);
  custom_streamcallback_word.LoadFile(saved_pdf_file_path);
  Office2PDF.ConvertFromWordWithStream(custom_readercallback_word, "", custom_streamcallback_word, setting_data);
  console.log("Convert Word format file to PDF file with stream.");
  delete custom_readercallback_word;
  delete custom_streamcallback_word;
} catch (e) {
  console.log(e);
}

try {
  var src_excel_path = input_dir + "excel.xlsx";
  var saved_pdf_file_path = output_dir + "excel2pdf_withpath_result.pdf";
  Office2PDF.ConvertFromExcelWithPath(src_excel_path, "", saved_pdf_file_path, setting_data);
  console.log("Convert Excel format file to PDF file with path.");
} catch (e) {
  console.log(e); 
}

try {
	var custom_readercallback_excel = new CustomReaderCallback();
	var custom_streamcallback_excel = new CustomStreamCallback();
	var src_excel_path = input_dir + "excel.xlsx";
	var saved_pdf_file_path = output_dir + "excel2pdf_withstream_result.pdf";
	custom_readercallback_excel.LoadFile(src_excel_path);
	custom_streamcallback_excel.LoadFile(saved_pdf_file_path);
	Office2PDF.ConvertFromExcelWithStream(custom_readercallback_excel, "", custom_streamcallback_excel, setting_data);

	console.log("Conver Excel format filet to PDF file with stream.");
	delete custom_readercallback_excel;
	delete custom_streamcallback_excel;
} catch (e) {
  console.log(e); 
}

try {
  var src_powerpoint_path = input_dir + "powerpoint.pptx";
  var saved_pdf_file_path = output_dir + "ppt2pdf_withpath_result.pdf";
  Office2PDF.ConvertFromPowerPointWithPath(src_powerpoint_path, "", saved_pdf_file_path, setting_data);

  console.log("Convert PowerPoint format file to PDF file  with path.");
} catch (e) {
  console.error(e);
}

try {
	var custom_readercallback_ppt = new CustomReaderCallback();
	var custom_streamcallback_ppt = new CustomStreamCallback();
	var src_powerpoint_path = input_dir + "powerpoint.pptx";
	var saved_pdf_file_path = output_dir + "ppt2pdf_withstream_result.pdf";
	custom_readercallback_ppt.LoadFile(src_powerpoint_path);
	custom_streamcallback_ppt.LoadFile(saved_pdf_file_path);
	Office2PDF.ConvertFromPowerPointWithStream(custom_readercallback_ppt, "", custom_streamcallback_ppt, setting_data);
	console.log("Convert PowerPoint format file to PDF file with stream.");
	delete custom_readercallback_ppt;
	delete custom_streamcallback_ppt;
} catch (e) {
  console.log(e); 
}
