# 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,Excelor PowerPoint) format files to PDF files.

import os
import sys
import site

if sys.version_info.major == 2:
    _PYTHON2_ = True
else:
    _PYTHON2_ = False

if _PYTHON2_:
    site.addsitedir('../../../')
    from FoxitPDFConversionSDKPython2 import *
else:
    from FoxitPDFConversionSDKPython3 import *

sn = "P3UzPXKJGf7OHTSbhZ6tlBV431IfR0JhCBZo/XUOrENG7KfnzSYbZQ=="
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"

output_path = "../output_files/"
input_path = "../input_files/"
output_directory = output_path + "office2pdf/"
resource_folder_path = "../../../res/office2pdf"


class SDKLibMgr:

    def __init__(self):
        self.is_initialize_ = False

    def Initialize(self):
        # Initialize library
        error_code = Library.Initialize(sn, key)
        if error_code != e_ErrSuccess:
            print("Library Initialize Error: {}".format(error_code))
            return False
        self.is_initialize_ = True
        return True

    def Release(self):
        if self.is_initialize_:
            Library.Release()


class FileReader(FileReaderCallback):

    def __init__(self, *args):
        if _PYTHON2_:
            super(FileReader, self).__init__()
        else:
            super().__init__()

        self.file_ = None

    def __del__(self):
        self.__disown__()

    def Release(self, *args):
        self.file_.close()

    def LoadFile(self, *args):
        self.file_ = open(args[0], "rb")
        if self.file_ is not None:
            return True
        else:
            return False

    def GetSize(self, *args):
        self.file_.seek(0, os.SEEK_END)
        file_size = self.file_.tell()
        return file_size

    def ReadBlock(self, *args):
        if self.file_ is None:
            return False, None

        size = 0
        if len(args) == 2:
            self.file_.seek(args[0], 0)
            size = args[1]
        elif len(args) == 1:
            size = args[0]
        else:
            return False, None

        buffer = self.file_.read(size)

        return True, buffer


class FileStream(StreamCallback):

    def __init__(self, *args):
        if _PYTHON2_:
            super(FileStream, self).__init__()
        else:
            super().__init__()

        self.file_ = None
        self.cur_pos_ = 0
        self.ref_ = 1

    def __del__(self):
        self.__disown__()

    def Retain(self, *args):
        self.ref_ += 1
        return self

    def IsEOF(self, *args):
        self.file_.seek(0, os.SEEK_END)
        file_size = self.file_.tell()
        if self.cur_pos_ < file_size:
            return False
        else:
            return True

    def GetPosition(self, *args):
        return self.cur_pos_

    def Release(self, *args):
        self.ref_ -= 1
        if self.ref_ > 0:
            return
        self.file_.close()

    def LoadFile(self, *args):
        self.file_ = open(args[0], "wb")
        if self.file_ is not None:
            return True
        else:
            return False

    def GetSize(self, *args):
        self.file_.seek(0, os.SEEK_END)
        file_size = self.file_.tell()
        return file_size

    def Flush(self, *args):
        self.file_.flush()
        return True

    def ReadBlock(self, *args):
        if self.file_ is None:
            return False, None

        size = 0
        if len(args) == 2:
            self.file_.seek(args[0], 0)
            size = args[1]
            self.cur_pos_ = args[0] + args[1]
        elif len(args) == 1:
            size = args[0]
        else:
            return False, None

        buffer = self.file_.read(size)

        return True, buffer

    def WriteBlock(self, *args):
        if self.file_ is None:
            return False
        if (args[0] is not None):
            self.file_.seek(args[0][1], os.SEEK_SET)
            self.file_.write(args[0][0])
            self.cur_pos_ = args[0][1] + args[0][2]
            return True
        else:
            return False

def main():
    err_ret = 0

    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    try:
        setting_data = Office2PDFSettingData();
        setting_data.resource_folder_path = resource_folder_path;
        # Conver Word file to PDF file.
        word_file_path = input_path + "word.docx"
        output_path = output_directory + "word2pdf_result.pdf"
        Office2PDF.ConvertFromWord(word_file_path, "", output_path,setting_data)
        print("Convert Word file to PDF file.")
        file_reader_word = FileReader()
        file_reader_word.LoadFile(word_file_path)
        file_stream_word = FileStream()
        file_stream_word.LoadFile(output_directory + "word2pdf_stream_result.pdf")        
        Office2PDF.ConvertFromWord(file_reader_word, "", file_stream_word,setting_data)
        print("Convert PDF file to Word format file with stream.")



        # Conver Excel file to PDF file.
        excel_file_path = input_path + "excel.xlsx"
        output_path = output_directory + "excel2pdf_result.pdf"
        Office2PDF.ConvertFromExcel(excel_file_path, "", output_path,setting_data)
        print("Convert Excel file to PDF file.")
        file_reader_excel = FileReader()
        file_reader_excel.LoadFile(excel_file_path)
        file_stream_excel = FileStream()
        file_stream_excel.LoadFile(output_directory + "excel2pdf_stream_result.pdf")      
        Office2PDF.ConvertFromExcel(file_reader_excel, "", file_stream_excel,setting_data)
        print("Convert PDF file to Excel format file with stream.")



        # Conver PowerPoint file to PDF file.
        ppt_file_path = input_path + "powerpoint.pptx"
        output_path = output_directory + "ppt2pdf_result.pdf"
        Office2PDF.ConvertFromPowerPoint(ppt_file_path, "", output_path,setting_data)
        print("Convert PowerPoint file to PDF file.")
        file_reader_ppt = FileReader()
        file_reader_ppt.LoadFile(ppt_file_path)
        file_stream_ppt = FileStream()
        file_stream_ppt.LoadFile(output_directory + "ppt2pdf_stream_result.pdf")
        Office2PDF.ConvertFromPowerPoint(file_reader_ppt, "", file_stream_ppt,setting_data)
        print("Convert PDF file to PowerPoint format file with stream.")
    except Exception as ex:
        print(ex.GetMessage())
        err_ret = 1

    return err_ret


if __name__ == '__main__':
    libmgr = SDKLibMgr()
    if libmgr.Initialize():
        main()

    libmgr.Release()