// 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 images to PDF files.

// Include Foxit SDK header files.
#include <time.h>
#include <iostream>
#if defined(_WIN32) || defined(_WIN64)
#include<direct.h>
#else
#include <sys/stat.h>
#endif

#include "../../../include/common/fs_common.h"
#include "../../../include/common/fs_image.h"
#include "../../../include/pdf/fs_pdfdoc.h"
#include "../../../include/pdf/fs_pdfpage.h"
#include "../../../include/pdf/graphics/fs_pdfgraphicsobject.h"
#include "addon/conversion/fs_convert.h"

using namespace std;
using namespace foxit;
using namespace foxit::common;
using foxit::common::Library;
using namespace pdf;
using namespace pdf::graphics;
using namespace foxit::addon::conversion;
using namespace common::file;

static const char* sn = "Rew1vB0TqoMIxX444UcpScARWdhgJpsJfzmyMLR32a0+EgrCjp2NaQ==";
static const char* 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=";

#if defined(_WIN32) || defined(_WIN64)
static WString output_path = WString::FromLocal("../output_files/");
static WString input_path = WString::FromLocal("../input_files/");
#else
static WString output_path = WString::FromLocal("./output_files/");
static WString input_path = WString::FromLocal("./input_files/");
#endif

class SdkLibMgr {
public:
  SdkLibMgr() : is_initialize_(false){};
  ErrorCode Initialize() {
    ErrorCode error_code = Library::Initialize(sn, key);
    if (error_code != foxit::e_ErrSuccess) {
      printf("Library Initialize Error: %d\n", error_code);
    } else {
      is_initialize_ = true;
    }
    return error_code;

  }
  ~SdkLibMgr(){
    if(is_initialize_)
      Library::Release();
  }
private:
  bool is_initialize_;
};

class FileReader : public ReaderCallback {
public:
  FileReader()
    : m_fileFP(NULL)
    , m_bLargeFile(FALSE) {}

  ~FileReader() {}

  bool LoadFile(const wchar_t* wFilePath, bool bLargeFile = FALSE) {
    std::wstring strTemp(wFilePath);
    CFX_ByteString bytestring = CFX_ByteString::FromUnicode(wFilePath);
    string bstrFilepath = string(bytestring);
#if defined(_WIN32) || defined(_WIN64)
    fopen_s(&m_fileFP, bstrFilepath.c_str(), "rb");
#else
    m_fileFP = fopen(bstrFilepath.c_str(), "rb");
#endif
    if (!m_fileFP)
      return FALSE;
    m_bLargeFile = bLargeFile;
    return TRUE;
  }

  FILESIZE GetSize() {
    if (m_bLargeFile) {
#if defined(_WIN32) || defined(_WIN64)
      _fseeki64(m_fileFP, 0, SEEK_END);
      long long sizeL = _ftelli64(m_fileFP);
#elif defined(__linux__) || defined(__APPLE__)
      fseeko(m_fileFP, 0, SEEK_END);
      long long sizeL = ftello(m_fileFP);
#endif
      return sizeL;
    }
    else {
      fseek(m_fileFP, 0, SEEK_END);
      return (uint32)ftell(m_fileFP);
    }
  }

  FX_BOOL ReadBlock(void* buffer, FILESIZE offset, size_t size) {
    if (m_bLargeFile) {
#if defined(_WIN32) || defined(_WIN64)
      _fseeki64(m_fileFP, offset, SEEK_SET);
#elif defined(__linux__) || defined(__APPLE__)
      fseeko(m_fileFP, offset, SEEK_SET);
#endif
      long long readSize = fread(buffer, 1, size, m_fileFP);
      return (readSize == size);
    }
    else {
      if (!m_fileFP)
        return false;
      if (0 != fseek(m_fileFP, (long)offset, 0))
        return false;
      if (0 == fread(buffer, 1, size, m_fileFP))
        return false;
      return true;
    }
  }

  void Release() {
    if (m_fileFP)
      fclose(m_fileFP);
    m_fileFP = NULL;
    delete this;
  }

private:
  FILE* m_fileFP;
  bool m_bLargeFile;
};

class FileWriter : public WriterCallback {
public:
  FileWriter()
    : m_fileFP(NULL)
    , m_bLargeFile(FALSE) {}

  ~FileWriter() {}

  bool LoadFile(const char* filePath, bool bLargeFile = FALSE) {
#if defined(_WIN32) || defined(_WIN64)
    fopen_s(&m_fileFP, filePath, "wb");
#else
    m_fileFP = fopen(filePath, "wb");
#endif
    if (!m_fileFP)
      return FALSE;
    m_bLargeFile = bLargeFile;
    return TRUE;
  }

  FILESIZE GetSize() {
    if (!m_fileFP)
      return 0;
    if (m_bLargeFile) {
#if defined(_WIN32) || defined(_WIN64)
      _fseeki64(m_fileFP, 0, SEEK_END);
      long long sizeL = _ftelli64(m_fileFP);
#elif defined(__linux__) || defined(__APPLE__)
      fseeko(m_fileFP, 0, SEEK_END);
      long long sizeL = ftello(m_fileFP);
#endif
      return sizeL;
    }
    else {
      fseek(m_fileFP, 0, SEEK_END);
      return (uint32)ftell(m_fileFP);
    }
  }

  FX_BOOL Flush() {
    return fflush(m_fileFP) == 0;
  }

  FX_BOOL WriteBlock(const void* buffer, FILESIZE offset, size_t size) {
    if (!m_fileFP)
      return FALSE;
    if (m_bLargeFile) {
#if defined(_WIN32) || defined(_WIN64)
      _fseeki64(m_fileFP, offset, SEEK_SET);
#elif defined(__linux__) || defined(__APPLE__)
      fseeko(m_fileFP, offset, SEEK_SET);
#endif
      size_t readSize = fwrite(buffer, sizeof(char), size, m_fileFP);
      return (readSize == size);
    }
    else {
      if (!m_fileFP)
        return false;
      int ret1 = fseek(m_fileFP, (long)offset, SEEK_SET);
      uint64 write_size = fwrite(buffer, sizeof(char), size, m_fileFP);
      if (write_size == size) {
        return TRUE;
      }
    }
    return FALSE;
  }

  void Release() {
    if (m_fileFP)
      fclose(m_fileFP);
    m_fileFP = NULL;
    delete this;
  }

private:
  FILE* m_fileFP;
  bool m_bLargeFile;
};

void Image2PDF(WString input_file,WString output_file)
{
  Image image(input_file);
  int count = 1;
  if (image.GetType() != Image::e_JBIG2) {
    count = image.GetFrameCount();
  }  
  PDFDoc doc;
  for (int i = 0; i < count; i++) {
    PDFPage page = doc.InsertPage(i, image.GetWidth(), image.GetHeight());
    page.StartParse(foxit::pdf::PDFPage::e_ParsePageNormal, NULL, false);
    // Add image to page
    page.AddImage(image, i, PointF(0, 0), image.GetWidth(), image.GetHeight(), true);
  }
  doc.SaveAs(output_file, PDFDoc::e_SaveFlagNoOriginal);

}

void FromImage(WString input_file, WString output_file)
{
  try {
    Convert::FromImage(input_file, output_file);
  }
  catch (foxit::Exception& e) {
    cout << e.GetMessage() << endl;
  }
}

void FromImage(FileReader *reader, FileWriter *writer)
{
  try {
    Convert::FromImage(reader, writer);
  }
  catch (foxit::Exception& e) {
    cout << e.GetMessage() << endl;
  }
}

int main(int argc, char *argv[])
{
  WString output_directory = output_path + L"image2pdf/";
#if defined(_WIN32) || defined(_WIN64)
  _mkdir(String::FromUnicode(output_directory));
#else
  mkdir(String::FromUnicode(output_directory), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
#endif

  int err_ret = 0;
  SdkLibMgr sdk_lib_mgr;
  // Initialize library
  ErrorCode error_code = sdk_lib_mgr.Initialize();
  if (error_code != foxit::e_ErrSuccess) {
    return 1;
  }

  try {
    {
      // Convert .bmp file to PDF document.
      WString input_file = input_path + L"watermark.bmp";
      WString output_file = output_directory + L"watermark_bmp.pdf";
      Image2PDF(input_file,output_file);
      cout << "Convert BMP file to PDF file." << endl;
    }
    {
      // Convert .jpg file to PDF document.
      WString input_file = input_path + L"image_samples.jpg";
      WString output_file = output_directory + L"image_samples_jpg.pdf";
      Image2PDF(input_file,output_file);
      cout << "Convert JPG file to PDF file." << endl;
    }
    {
      // Convert .tif file to PDF document.
      WString input_file = input_path + L"TIF2Pages.tif";
      WString output_file = output_directory + L"TIF2Pages_tif.pdf";
      Image2PDF(input_file,output_file);
      cout << "Convert TIF file to PDF file." << endl;
    }
    {
      // Convert .gif file to PDF document.
      WString input_file = input_path + L"image005.gif";
      WString output_file = output_directory + L"image005_gif.pdf";
      Image2PDF(input_file,output_file);
      cout << "Convert GIF file to PDF file." << endl;
    }
    {
      // Convert .png file to PDF document.
      WString input_file = input_path + L"1.png";
      WString output_file = output_directory + L"1_png.pdf";
      Image2PDF(input_file, output_file);
      cout << "Convert PNG file to PDF file." << endl;
    }
    {
      // Convert .jb2 file to PDF document.
      WString input_file = input_path + L"STR_039.jb2";
      WString output_file = output_directory + L"STR_039_jb2.pdf";
      Image2PDF(input_file, output_file);
      cout << "Convert JB2 file to PDF file." << endl;
    }
    {
      // Convert .jp2 file to PDF document.
      WString input_file = input_path + L"1.jp2";
      WString output_file = output_directory + L"1_jp2.pdf";
      Image2PDF(input_file, output_file);
      cout << "Convert JP2 file to PDF file." << endl;
    }
    {
      // Convert .jpx file to PDF document.
      WString input_file = input_path + L"1.jpx";
      WString output_file = output_directory + L"1_jpx.pdf";
      Image2PDF(input_file, output_file);
      cout << "Convert JPX file to PDF file." << endl;
    }

  } catch (const Exception& e) {
    cout << e.GetMessage() << endl;
    err_ret = 1;
  }
  // Convert from filepath
  try {
    cout << "Start: convert file from file path." << endl;
    {
      // Convert .bmp file to PDF document.
      WString input_file = input_path + L"watermark.bmp";
      WString output_file = output_directory + L"watermark_bmp_frompath.pdf";
      FromImage(input_file, output_file);
      cout << "Convert BMP file to PDF file." << endl;
    }
    {
      // Convert .jpg file to PDF document.
      WString input_file = input_path + L"image_samples.jpg";
      WString output_file = output_directory + L"image_samples_jpg_frompath.pdf";
      FromImage(input_file, output_file);
      cout << "Convert JPG file to PDF file." << endl;
    }
    {
      // Convert .tif file to PDF document.
      WString input_file = input_path + L"TIF2Pages.tif";
      WString output_file = output_directory + L"TIF2Pages_tif_frompath.pdf";
      FromImage(input_file, output_file);
      cout << "Convert TIF file to PDF file." << endl;
    }
    {
      // Convert .gif file to PDF document.
      WString input_file = input_path + L"image005.gif";
      WString output_file = output_directory + L"image005_gif_frompath.pdf";
      FromImage(input_file, output_file);
      cout << "Convert GIF file to PDF file." << endl;
    }
    {
      // Convert .png file to PDF document.
      WString input_file = input_path + L"1.png";
      WString output_file = output_directory + L"1_png_frompath.pdf";
      FromImage(input_file, output_file);
      cout << "Convert PNG file to PDF file." << endl;
    }
    {
      // Convert .jb2 file to PDF document.
      WString input_file = input_path + L"STR_039.jb2";
      WString output_file = output_directory + L"STR_039_jb2_frompath.pdf";
      FromImage(input_file, output_file);
      cout << "Convert JB2 file to PDF file." << endl;
    }
    {
      // Convert .jp2 file to PDF document.
      WString input_file = input_path + L"1.jp2";
      WString output_file = output_directory + L"1_jp2_frompath.pdf";
      FromImage(input_file, output_file);
      cout << "Convert JP2 file to PDF file." << endl;
    }
    {
      // Convert .jpx file to PDF document.
      WString input_file = input_path + L"1.jpx";
      WString output_file = output_directory + L"1_jpx_frompath.pdf";
      FromImage(input_file, output_file);
      cout << "Convert JPX file to PDF file." << endl;
    }
    cout << "End: convert file from file path." << endl;
  }
  catch (const Exception& e) {
    cout << e.GetMessage() << endl;
    err_ret = 1;
  }

  // Convert from stream
  try {
    cout << "Start: convert file from stream." << endl;
    {
      // Convert .bmp file to PDF document.
      WString input_file = input_path + L"watermark.bmp";
      FileReader *filereader = new FileReader();
      filereader->LoadFile(input_file);
      WString output_file = output_directory + L"watermark_bmp_stream.pdf";
      FileWriter *filewriter = new FileWriter();
      filewriter->LoadFile(String::FromUnicode(output_file));
      FromImage(filereader, filewriter);
      cout << "Convert BMP file to PDF file." << endl;
    }
    {
      // Convert .jpg file to PDF document.
      WString input_file = input_path + L"image_samples.jpg";
      FileReader *filereader = new FileReader();
      filereader->LoadFile(input_file);
      WString output_file = output_directory + L"image_samples_jpg_stream.pdf";
      FileWriter *filewriter = new FileWriter();
      filewriter->LoadFile(String::FromUnicode(output_file));
      FromImage(filereader, filewriter);
      cout << "Convert JPG file to PDF file." << endl;
    }
    {
      // Convert .tif file to PDF document.
      WString input_file = input_path + L"TIF2Pages.tif";
      FileReader *filereader = new FileReader();
      filereader->LoadFile(input_file);
      WString output_file = output_directory + L"TIF2Pages_tif_stream.pdf";
      FileWriter *filewriter = new FileWriter();
      filewriter->LoadFile(String::FromUnicode(output_file));
      FromImage(filereader, filewriter);
      cout << "Convert TIF file to PDF file." << endl;
    }
    {
      // Convert .gif file to PDF document.
      WString input_file = input_path + L"image005.gif";
      FileReader *filereader = new FileReader();
      filereader->LoadFile(input_file);
      WString output_file = output_directory + L"image005_gif_stream.pdf";
      FileWriter *filewriter = new FileWriter();
      filewriter->LoadFile(String::FromUnicode(output_file));
      FromImage(filereader, filewriter);
      cout << "Convert GIF file to PDF file." << endl;
    }
    {
      // Convert .png file to PDF document.
      WString input_file = input_path + L"1.png";
      FileReader *filereader = new FileReader();
      filereader->LoadFile(input_file);
      WString output_file = output_directory + L"1_png_stream.pdf";
      FileWriter *filewriter = new FileWriter();
      filewriter->LoadFile(String::FromUnicode(output_file));
      FromImage(filereader, filewriter);
      cout << "Convert PNG file to PDF file." << endl;
    }

    {
      // Convert .jb2 file to PDF document.
      WString input_file = input_path + L"STR_039.jb2";
      FileReader *filereader = new FileReader();
      filereader->LoadFile(input_file);
      WString output_file = output_directory + L"STR_039_jb2_stream.pdf";
      FileWriter *filewriter = new FileWriter();
      filewriter->LoadFile(String::FromUnicode(output_file));
      FromImage(filereader, filewriter);
      cout << "Convert JB2 file to PDF file." << endl;
    }

    {
      // Convert .jp2 file to PDF document.
      WString input_file = input_path + L"1.jp2";
      FileReader *filereader = new FileReader();
      filereader->LoadFile(input_file);
      WString output_file = output_directory + L"1_jp2_stream.pdf";
      FileWriter *filewriter = new FileWriter();
      filewriter->LoadFile(String::FromUnicode(output_file));
      FromImage(filereader, filewriter);
      cout << "Convert JP2 file to PDF file." << endl;
    }
    {
      // Convert .jpx file to PDF document.
      WString input_file = input_path + L"1.jpx";
      FileReader *filereader = new FileReader();
      filereader->LoadFile(input_file);
      WString output_file = output_directory + L"1_jpx_stream.pdf";
      FileWriter *filewriter = new FileWriter();
      filewriter->LoadFile(String::FromUnicode(output_file));
      FromImage(filereader, filewriter);
      cout << "Convert JPX file to PDF file." << endl;
    }
    cout << "End: convert file from  stream." << endl;
  }
  catch (const Exception& e) {
    cout << e.GetMessage() << endl;
    err_ret = 1;
  }
  catch(...)
  {
    cout << "Unknown Exception" << endl;
    err_ret = 1;
  }

  return err_ret;
}

