// 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.
// If using a stream to load the html file, set variable isfilestreamload to true.
//
// This file contains an example to demonstrate how to use Foxit PDF SDK to covert from html to pdf.

using System;

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using System.IO;
using System.Runtime.InteropServices;

namespace html2pdf
{
  public class FileRead : FileReaderCallback
  {
    private FileStream file_ = null;
    private bool is_large_file_;

    public FileRead()
    {
    }

    public bool loadFile(String file_path, bool is_large_file)
    {
      this.is_large_file_ = is_large_file;
      this.file_ = new FileStream(file_path, FileMode.Open);
      return true;

    }

    public override long GetSize()
    {
      file_.Seek(0, SeekOrigin.End);
      long len = file_.Length;
      file_.Seek(0, SeekOrigin.Begin);
      return len;
    }

    public override bool ReadBlock(IntPtr buffer, long offset, uint size)
    {
      int read_size = 0;
      file_.Seek(offset, SeekOrigin.Begin);
      byte[] array = new byte[size + 1];
      read_size = file_.Read(array, 0, (int)size);

      Marshal.Copy(array, 0, buffer, (int)size);
      return read_size == size ? true : false;

    }

    public override void Release()
    {
      try
      {
        file_.Close();
      }
      catch (IOException e)
      {
        Console.WriteLine(e.Message);
      }
    }
  }

  class FileWriter : FileWriterCallback
  {
    private FileStream file_ = null;

    public Boolean LoadFile(String file_path)
    {
      file_ = new FileStream(file_path, FileMode.Create);
      return true;
    }

    public override void Release()
    {
      this.file_.Close();
    }

    public override bool Flush()
    {
      return true;
    }

    public override long GetSize()
    {
      return this.file_.Length;
    }

    public override bool WriteBlock(IntPtr pData, long offset, uint size)
    {
      file_.Seek(offset, SeekOrigin.Begin);

      byte[] ys = new byte[size];
      Marshal.Copy(pData, ys, 0, (int)size);
      file_.Write(ys, (int)0, (int)size);
      return true;
    }
  }

  class html2pdf
    {
        static String output_directory = "../output_files/html2pdf/";
        static String url_or_html = "../input_files/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.
        static String 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.
        static String cookies_path = "";
        static String output_path = output_directory + "html2pdf_result.pdf";
        static int time_out = 15;
        static void Main(string[] args)
        {
            System.IO.Directory.CreateDirectory(output_directory);
            string sn = "Rew1vB0TqoMIxX444UcpScARWdhgJpsJfzmyMLR32a0+EgrCjp2NaQ==";
            string 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=";
            int length = args.Length;
            // Initialize library
            if (length > 0 && args[0].Equals("--help"))
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("html2pdf_xxx <-html <The url or html path>> <-o <output pdf path>> <-engine <htmltopdf engine path>>");
                Console.WriteLine(" [-w <page width>] [-h <page height>]  [-r <page rotate degree>] [-mode <page mode>] [-scale <whether scale page>]");
                Console.WriteLine(" [-ml <margin left>] [-mr <margin right>] [-mt <margin top>] [-mb <margin bottom>] [-link <whether convert link>]");
                Console.WriteLine(" [-tag <whether generate tag>] [-bookmarks <whether to generate bookmarks>] [-cookies <cookies file path>] [-timeout <timeout>]");
                Console.WriteLine("-html The url or html file path. for examples '-html www.foxitsoftware.com'");
                Console.WriteLine("-o The output pdf path.");
                Console.WriteLine("-engine The html to pdf engine path.");
                Console.WriteLine("-w The page width.");
                Console.WriteLine("-h The page height.");
                Console.WriteLine("-r The page roate degree.");
                Console.WriteLine("-ml The page margin distance of left.");
                Console.WriteLine("-mr The page margin distance of right.");
                Console.WriteLine("-mt The page margin distance of top.");
                Console.WriteLine("-mb The page margin distance of bottom.");
                Console.WriteLine("-mode The page mode. 0 means single page mode and 1 means multiple mode");
                Console.WriteLine("-encoding The HTML encoding format. '0' means auto encoding and '1'-'73' means other encodings");
                Console.WriteLine("-render_images Whether to render images or not.'yes' means to render images, 'no' means no need to render.");
                Console.WriteLine("-remove_underline_for_link Whether to remove underline for link. 'yes' means to remove underline for link, 'no' means no need to remove.");
                Console.WriteLine("-headerfooter Whether to generate headerfooter. 'yes' means to generate headerfooter, 'no' means no need to generate.");
                Console.WriteLine("-headerfooter_title The headerfooter title.");
                Console.WriteLine("-headerfooter_url The headerfooter url.");
                Console.WriteLine("-bookmark_root_name The bookmark root name.");
                Console.WriteLine("-resize_objects Whether to enable the Javascripts related resizing of the objects during rendering process. 'yes' means to enable, 'no' means to disable.");
                Console.WriteLine("-scale The scaling mode. '0' means no scale, '1' means scale page, '2' means enlarge page.");
                Console.WriteLine("-link Whether to covert link. 'yes' means to convert link, 'no' means no need to covert.");
                Console.WriteLine("-tag Whether generate tag. 'yes' means to generate tag, 'no' means no need to generate.");
                Console.WriteLine("-bookmarks Whether to generate bookmarks.'yes' means to generate bookmarks, 'no' means no need to generate.");
                Console.WriteLine("-print_background Whether to print background. 'yes' means to print background, 'no' means no need to print background.");
                Console.WriteLine("-optimize_tag Whether to optimize tag tree. 'yes' means to optimize tag tree, 'no' means no need to optimize tag tree.");
                Console.WriteLine("-media The media style. '0' means screen media style, '1' means print media style.");
                Console.WriteLine("-cookies The cookies file path.");
                Console.WriteLine("-timeout The timeout of loading webpages.'0' means 0 degree, '1' means 90 degree, '2' means 180 degree, '3' means 270 degree.");
                return;
            }
            //If using a stream to load the html file, set isfilestreamload to true
            bool isfilestreamload = false;

            ErrorCode error_code = Library.Initialize(sn, key);
            if (error_code != ErrorCode.e_ErrSuccess)
            {
                Console.WriteLine("Library Initialize Error: {0}\n", error_code);
                return;
            }

            try
            {
                foxit.addon.conversion.HTML2PDFSettingData pdf_setting_data = new foxit.addon.conversion.HTML2PDFSettingData();
                pdf_setting_data.scaling_mode = foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFScalingMode.e_ScalingModeScale;
                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 = 0;
                pdf_setting_data.page_height = 640;
                pdf_setting_data.page_width = 900;
                pdf_setting_data.page_mode = foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFPageMode.e_PageModeSinglePage;
                pdf_setting_data.to_print_background = true;
                pdf_setting_data.to_optimize_tag_tree = false;
                pdf_setting_data.media_style = foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFMediaStyle.e_MediaStyleScreen;
                if (!AnalysisParameter(length, args, pdf_setting_data)) return;
                foxit.addon.conversion.Convert.FromHTML(url_or_html, engine_path, cookies_path, pdf_setting_data, output_path, time_out);

                Console.WriteLine("Convert HTML to PDF successfully.");                      
            }
            catch (foxit.PDFException e)
            {
                Console.WriteLine(e.Message);
            }

            if (isfilestreamload)
            {
              try
              {
                  foxit.addon.conversion.HTML2PDFSettingData pdf_setting_data = new foxit.addon.conversion.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 RectF(18, 18, 18, 18);
                  pdf_setting_data.is_convert_link = true;
                  pdf_setting_data.rotate_degrees = 0;
                  pdf_setting_data.is_generate_tag = true;
                  pdf_setting_data.page_mode = foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFPageMode.e_PageModeSinglePage;
                  pdf_setting_data.scaling_mode = foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFScalingMode.e_ScalingModeScale;
                  pdf_setting_data.to_generate_bookmarks = true;
                  pdf_setting_data.encoding_format = 0;
                  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 = 0;
                  pdf_setting_data.to_load_active_content = false;

                  String output_path = output_directory + "html2pdf_filestream_result.pdf";
                  FileWriter filewrite = new FileWriter();
                  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.
                  String htmlfile = "";
                  FileRead filereader = new FileRead();
                  filereader.loadFile(htmlfile, false);
 
                  //"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.
                  String htmlfilepng = "";
                  FileRead filereader1 = new FileRead();
                  filereader1.loadFile(htmlfilepng, false);
                  //"relativefilepath" is  the resource file's relative path. For example: "./aaa.png".
                  String relativefilepng = "";
                  foxit.addon.conversion.HTML2PDFRelatedResourceArray html2PDFRelatedResourceArray = new foxit.addon.conversion.HTML2PDFRelatedResourceArray();
                  foxit.addon.conversion.HTML2PDFRelatedResource html2PDFRelatedResource = new foxit.addon.conversion.HTML2PDFRelatedResource(filereader1,relativefilepng);

                  html2PDFRelatedResourceArray.Add(html2PDFRelatedResource);
                  foxit.addon.conversion.Convert.FromHTML(filereader, html2PDFRelatedResourceArray, engine_path, null,
                                                              pdf_setting_data, filewrite, 30);
                  Console.WriteLine("Convert HTML to PDF successfully by filestream!");
              }
              catch (foxit.PDFException e)
              {
                Console.WriteLine(e.Message);
              }
            }

      Library.Release();
        }
        static bool AnalysisParameter(int length, String[] args, foxit.addon.conversion.HTML2PDFSettingData pdf_setting_data)
        {
            for (int i = 0; i < length; i = i + 2)
            {
                String args_key = args[i];
                if (length <= i + 1)
                {
                    Console.WriteLine("Please make sure the key {0} is valid and it has value!\n", args_key);
                    Console.WriteLine("Usage: html2pdf_xxx <-html <The url or html path>> <-o <output pdf path>> ...\nPlease try 'html2pdf_xxx --help' for more information.\n");
                    return false;
                }
                String args_value = (args[i + 1]);
                if (args_key.Equals("-w")) pdf_setting_data.page_width = Convert.ToSingle(args_value);
                else if (args_key.Equals("-h")) pdf_setting_data.page_height = Convert.ToSingle(args_value);
                else if (args_key.Equals("-r")) pdf_setting_data.rotate_degrees = (foxit.common.Rotation)Convert.ToInt16(args_value);
                else if (args_key.Equals("-ml")) pdf_setting_data.page_margin.left= Convert.ToSingle(args_value);
                else if (args_key.Equals("-mr")) pdf_setting_data.page_margin.right = Convert.ToSingle(args_value);
                else if (args_key.Equals("-mt")) pdf_setting_data.page_margin.top= Convert.ToSingle(args_value);
                else if (args_key.Equals("-mb")) pdf_setting_data.page_margin.bottom = Convert.ToSingle(args_value);
                else if (args_key.Equals("-scale")) pdf_setting_data.scaling_mode = (foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFScalingMode)Convert.ToInt32(args_value);
                else if (args_key.Equals("-link")) pdf_setting_data.is_convert_link = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-tag")) pdf_setting_data.is_generate_tag = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-bookmarks")) pdf_setting_data.to_generate_bookmarks = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-mode")) pdf_setting_data.page_mode = (foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFPageMode)Convert.ToInt32(args_value);
                else if (args_key.Equals("-encoding")) pdf_setting_data.encoding_format = (foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFEncodingFormat)Convert.ToInt32(args_value);
                else if (args_key.Equals("-render_images")) pdf_setting_data.to_render_images = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-remove_underline_for_link")) pdf_setting_data.to_remove_underline_for_link = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-headerfooter")) pdf_setting_data.to_set_headerfooter = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-headerfooter_title")) pdf_setting_data.headerfooter_title = args_value;
                else if (args_key.Equals("-headerfooter_url")) pdf_setting_data.headerfooter_url = args_value;
                else if (args_key.Equals("-bookmark_root_name")) pdf_setting_data.bookmark_root_name = args_value;
                else if (args_key.Equals("-resize_objects")) pdf_setting_data.to_resize_objects = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-engine")) engine_path = args_value;
                else if (args_key.Equals("-cookies")) cookies_path = args_value;
                else if (args_key.Equals("-o")) output_path = args_value;
                else if (args_key.Equals("-html")) url_or_html = args_value;
                else if (args_key.Equals("-timeout")) time_out = Convert.ToInt32(args_value);
                else if (args_key.Equals("-print_background")) pdf_setting_data.to_print_background = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-optimize_tag")) pdf_setting_data.to_optimize_tag_tree = (args_value.Equals("yes", StringComparison.OrdinalIgnoreCase) ? true : false);
                else if (args_key.Equals("-media")) pdf_setting_data.media_style = (foxit.addon.conversion.HTML2PDFSettingData.HTML2PDFMediaStyle)Convert.ToInt32(args_value);
                else
                {
                    Console.WriteLine("Please make sure the key " + args_key + " is valid and it has value!\n");
                    Console.WriteLine("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;
        }
    }
}
