// 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 get preflight keys and analyze or fixup PDF file.


import com.foxit.sdk.PDFException;
import com.foxit.sdk.common.Library;
import com.foxit.sdk.addon.compliance.*;
import com.foxit.sdk.common.WStringArray;
import com.foxit.sdk.addon.compliance.Preflight;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import static com.foxit.sdk.common.Constants.e_ErrSuccess;
import static com.foxit.sdk.common.Constants.e_ErrInvalidLicense;
import static com.foxit.sdk.addon.compliance.PreflightSettingData.*;
import static com.foxit.sdk.addon.compliance.PreflightReportSettingData.*;

public class preflight {


    static String key = "8f3g1sFttW8NAgfSNv+BvQJm2vDtTY+wGQ/1PcmGtqKTwvvI8mLE4KvuHocWH+XZnP3U+Vh1BnqpgQIjO0jwRz7evDdlijTdutpBEsozaXEvFpLbixmsSGvtznflVsuEmsu5ytLwVJiTap2VcCiiSbyuvQwQu88I8BxJ+XXv3LPXN5v/+00zDrZ+V5yLefi+bk7JX5FRE2jfSnOJIqEaVkHOpCIjwf9aszl01YoY7x0EAehg0ILal+v2QLLo7HnkAVt/TA31rddZexhq/2hwAwfy4OfvkJPnESppD7D+SAsX5CfXoU55P1vmyRe+lKBM6pOcarUbuaN4Vjj62SD0sTDbJZ2Ypyp+kcIxZ9wcD+Mg8aSimr5+hg8wZJT0u0mIAdZhTJ++A9sq9OmVAfL2QQ6bh2ISyKPGJPv29u738bAokRjqzZy9bi30mYfGLEwKChEd2R2NBDKZTDOVxFwpzD1IbF0/wN/DDbMO2gS0xUvgSbJyuXfA3ALtmoUH9I9iScaBVon5oYRRy6OTnFMgDgVM+nFTzWbaGKZfO+PMBnreaQ/Ezr9wH7YKJ+LrM4r6xVQjcHDUyx4dlVLe3zQlDRKGGChhyvymVDBuZR8B0/M9Y/DKr1sQAzp/W1Wsz+LZb+JUIxLBrJzgRLtOliuLF+JOTy036W0shWcXYYc2bwLdPWP/BXygmnopzUTCtuo/QLVTRNdENFqciYYvSHEZxgV1sUFpuBqIMUEigWR/2gMlMDiTVq0udEqn8g9bkw1SImVy50v2gwEbUHkEa243BP/3/Dae0YhH03NDUlTSVBKX6w1UVQK6/7aDL3A4EEg47YmKgh6NsABzRsgSvLBhBQNqzOoUvnKaf7YMlw0ns06BdFswP6DaY1KmuRR2Xn6MtDTshGNtT9+azHPqaAWaZs1rHz3fGYb5pfJHptJlx+r9609bY+ZhCERLYG+0lTNWCFnDxdI8Vj1BG4iGWaDBkIC5qdJI3qDLVDABdtIk43fMhgfr+TUqds+G6KBDapS9p32nKZc6lBqvlNN12Pv1AJCC1rwfECzmNQi3MXogQCxzi5pHAgd/BGyGwo4RWhFrKFN869H0whvDVC8NJM2upFrEEJET4fecQyMLWHuTCWvjRZclLC/GGOj9PAXHOcEdFkq4UkloMulXLGsQzkzHB3Elvd2NnxZ2+3FK2e0xNx+rBMru/i/HHLG6WZvz6Jz7mjmibNfBExydtEI5lWUZ1Wsy0r17kyvlME9Bot7XXPkx/+cKTcxfNWSb3kaPROYIgSpGjrXxfrphBnr1mioJPq3WrtP9E5lZBeMd8jxXT4NlX3T0frsci6Xy1ChB/BytU7pvn6bMfddTnEDd/QpkW+6WYOnHHrIYVk2ngKjUBl5nGOkp37wpgUpWp5tcICjpbjfNdY43VfTyHRf4dGRR"; 
    static String sn = "nkyvo37UxrKdu5Peq294Eb+g2ihRldgPQEP6MFtAM4LwtxXXJ+T7MQ==";
    static String output_directory = "../output_files/preflight/";
    static String input_path = "../input_files/";

    // You can also use System.load("filename") instead. The filename argument must be an absolute path name.
    static {
        String os = System.getProperty("os.name").toLowerCase();
        String lib = "fsdk_java_";
        if (os.startsWith("win")) {
            lib += "win";
        } else if (os.startsWith("mac")) {
            lib += "mac";
        } else {
            lib += "linux";
        }
        if (System.getProperty("sun.arch.data.model").equals("64")) {
            if(System.getProperty("os.arch").equals("aarch64")){
                lib += "arm";
            }
            else{
                lib += "64";
            }
        } else {
            lib += "32";
        }
        System.loadLibrary(lib);
    }

    private static void createResultFolder(String output_path) {
        File myPath = new File(output_path);
        if (!myPath.exists()) {
            myPath.mkdir();
        }
    }
   
    static void ListPreflightKeys(Preflight preflight, int library_type, int operate_type) {
        try{
        	ArrayList<String> group_arr = preflight.getGroupNamesArray(library_type, operate_type);
            for (int i = 0; i < group_arr.size(); i++) {
        	    System.out.println(String.format("Group name: %s", group_arr.get(i)));
        	    ArrayList<String> item_array = preflight.getItemKeysArray(group_arr.get(i));
                System.out.println(String.format("    Item count: %d", item_array.size()));
                for (int j = 0; j < item_array.size(); j++) {
                	System.out.println(String.format("    Item name: %s",item_array.get(j)));
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    static void AnalyzeAndFixup(Preflight preflight, int operate_type, String preflight_key, boolean is_fixed) {
      try {
          PreflightSettingData setting_data = new PreflightSettingData();
          setting_data.setOperate_type(operate_type);
          setting_data.setPreflight_key(preflight_key);
          setting_data.setFirst_page_index(0);
          setting_data.setSrc_pdf_path(input_path + "AboutFoxit.pdf");
          String fixpath = output_directory + "AboutFoxit_" + preflight_key + "_fixed.pdf";
          setting_data.setSaved_pdf_path(fixpath);
          MyComplianceProgressCallback progress_callback = new MyComplianceProgressCallback(output_directory + "AboutFoxit_" + preflight_key + "_progress.txt");
          if(is_fixed)
            preflight.analyzeAndFixup(setting_data, progress_callback);
          else
            preflight.analyze(setting_data, progress_callback);
      }catch (Exception e) {
          e.printStackTrace();
      }      
    }
    static void GenerateReport(Preflight preflight, int format_type, String preflight_key) {
      try {
    	  PreflightReportSettingData report_setting_data = new PreflightReportSettingData();
          report_setting_data.setReport_file_format_type(format_type);
          String path = output_directory + "AboutFoxit_" + preflight_key + "_report.pdf";
          report_setting_data.setReport_file_path(path);
          report_setting_data.setTo_generate_overview(true);
          report_setting_data.setTo_highlight_problems(true);
          report_setting_data.setProblems_highlight_method(e_ProblemsHighlightMethodTransparentMasks);
          preflight.generateReport(report_setting_data, null);
      }catch (Exception e) {
          e.printStackTrace();
      }    
    }
    public static void main(String[] args) throws PDFException, IOException {
        createResultFolder(output_directory);
        // Initialize library
        int error_code = Library.initialize(sn, key);
        if (error_code != e_ErrSuccess) {
            System.out.println(String.format("Library Initialize Error: %d\n", error_code));
            return;
        }

        String input_file = input_path + "AboutFoxit.pdf";

        try {
            // "compliance_resource_folder_path" is the path of compliance resource folder. Please refer to Developer Guide for more details.
            String compliance_resource_folder_path = "";
            // If you use an authorization key for Foxit PDF SDK, please set a valid unlock code string to compliance_engine_unlockcode for ComplianceEngine.
            // If you use an trial key for Foxit PDF SDK, just keep compliance_engine_unlockcode as an empty string.
            String compliance_engine_unlockcode = "";
            System.out.println(compliance_resource_folder_path);
            if (compliance_resource_folder_path.length()<1) {
                System.out.println("compliance_resource_folder_path is still empty. Please set it with a valid path to compliance resource folder path.");
                return ;
            }
            // Initialize compliance engine.
            error_code = ComplianceEngine.initialize(compliance_resource_folder_path, compliance_engine_unlockcode);
            if (error_code != e_ErrSuccess) {
              switch (error_code) {
              case e_ErrInvalidLicense:
                System.out.println("[Failed] Compliance module is not contained in current Foxit PDF SDK keys.\n");
                break;
              default:
                System.out.println(String.format("[Failed] Fail to initialize compliance engine. Error: %d\n", error_code));
                break;
              }
              return ;
            }
            System.out.println("ComplianceEngine is initialized.");
            
            // Set custom temp folder path for ComplianceEngine. 
            //ComplianceEngine.setTempFolderPath("");
            // Set languages. If not set language to ComplianceEngine, "English" will be used as default.
            //ComplianceEngine.setLanguage("Chinese-Simplified");

            Preflight preflight = new Preflight();
            // List all Foxit preflight keys.
            System.out.println("Library Type: Foxit, Operate Type: Profiles");
            ListPreflightKeys(preflight, e_LibraryTypeFoxit, e_OperateTypeProfiles);
            System.out.println("Library Type: Foxit, Operate Type: Checks");
            ListPreflightKeys(preflight, e_LibraryTypeFoxit, e_OperateTypeSingleChecks);
            System.out.println("Library Type: Foxit, Operate Type: Fixups");
            ListPreflightKeys(preflight, e_LibraryTypeFoxit, e_OperateTypeSingleFixups);

            boolean is_fixup = false;
            // Analyze and fixup a PDF file.
            System.out.println("== Profiles. ==");
            is_fixup = preflight.canFixup("pppp_ConverttoPDFA1a");
            AnalyzeAndFixup(preflight, e_OperateTypeProfiles, "pppp_ConverttoPDFA1a", is_fixup);
            GenerateReport(preflight, e_ReportFileFormatTypePdf, "pppp_ConverttoPDFA1a");

            // Analyze a PDF file.
            System.out.println("== Single Checks.==");
            AnalyzeAndFixup(preflight, e_OperateTypeSingleChecks, "R_6_Annotationinsidepagearea", false);
            GenerateReport(preflight, e_ReportFileFormatTypePdf, "R_6_Annotationinsidepagearea");

            //Fixup a PDF file.
            System.out.println("== Single Fixups. ==");
            AnalyzeAndFixup(preflight, e_OperateTypeSingleFixups, "F_9_RemoveXMPMetadataifnotcompliantwithPDFA1", true);
            GenerateReport(preflight, e_ReportFileFormatTypePdf, "F_9_RemoveXMPMetadataifnotcompliantwithPDFA1");

            // Release compliance engine.
            ComplianceEngine.release();
            
            System.out.println("== End: Preflight demo. ==");


        } catch (Exception e) {
            e.printStackTrace();

        }
        Library.release();
        return;
    }

}
