// 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 = "fpj42y0uOGt8cNp2iJUJdW5LNQGpJDawgJ5niOHYLl+0Emd0mMDhtA==";
static const char* key = "8f3gFsNtvW8N+Vea402IXXgHXIciB/Uw21sIKl1s0+MWvuGiCwz8VVTEwrNsIr1uDlREGorTmUmz7lEC6UcgWUsLrWhG6ezQc5PcgosYOpKsVTaOCyFdxIVCIj7QY9pjCyDgAV1S24QKmBz/ayQSbCepuRh2MBANca27kAN9Frb1qZXYI6Bmrr08YesEz5YKDHFyC04BbHhHiCKBeoQQXzf3O8KST9cFlArWUdIIz2/c3cMjj8uuxFiqVskJrKA1wxvsW4TzZEnDldm9Aye/mZIgHOhIlf8Hg1gIvnA0GCnWhUOs2UpRSFd8YuSnm0UPI7WR1K6vRdgeT/1sYh5bctEzdQh/0bMoN0LpciklqYPwpIFR8HU/zxfleXVwkxWKYkaPW7HxBAE6apzSd18nwRZ8fTsZjcYhTo64q4Jzukyr7m4ODp3tnWgrTgJKnTQYDEEEqK2cRA0ZIsKYTJoQ45gbVMpB7u7wLZ8kAIJbCmXrRPRh72fobCrlh67yJeH98JF8tB7pljmdGX7AD/0IDqtbcXcTUBxLskyaFPQHCuTzzMpLdoCxzGIsqVyobq7E3XKBC7kYcmdH79GwcsHl3BrYma1jTnRobtVOAWg9AgdI2yIhcZJSPrCn7SiQ4+73kbKHpQ2ekoZCF7Cwy6mQ3I+45yg1SLNB0K4YTtoz0t7FMDU1sLf0WsZ4GGlI67WdrOCrYKiXmHK/xjO5+20eR1nSYQlm3H/gyfCLHGdJtEzCB0K/ZwncTJ8ChQTdMHjtU5/rGK7BpDwbIewU2QItE935S9+BHfTQqcSlIvdiDlMtakKkfTCFkr5DUJPCD7XTxoaFN2s8fr9FvQPhhduKufiyl4Ds//jjiT0gRGSN6zDPfrEfJehqsSJgdqDOPlPHDCCj0BK34I8khlWiE8GVxb8qOWUXUfHY9eGLJgMkDiC6UtODXYCwEwNnrWpXGsQjuwtFmUBX7rtNrFr1uVqC1hmvo17a+cnvkRvKMuW9AxiFyak0WMVKT5zvzm9zBsBpAslZP17COOVYIhsDWnmVKt/i5AGFTCwlTlyqxi4RABXOhXHGRpTog+9wV6R2Z9VFjPSLDogFTcO5SkChkmQIKml+anIAnbLjll5Tgwgs7pqsAiCjetSJN0v3fLfcEeyonSnyN3s4VZrxYS1LE4S604EcW0O9gOXAVC6cmZDZkUvSfMh+UVj8pBhF7BSL6qUd5HEfObkL1SZkhh8EHFfe48elqVidbY3Lj9pq52rBnR03oWtUeMNkTYWncYTSzeTTP3jEnlbduUkKQOLVPdXAzPAfQ0FlB31RXm3a1y6VZcgNMsHF/WmPmd6Hwgc48+TUFY7XzLaBlEwcfolyAvFCfVOxO/m0b9pxEfCBYN7lhaMU9+Vjyujj15uCNDSpn4wcs32F2+wfY03pvsv+XMCrYZxvYYDHtw==";

#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;
}

