// 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 associate files with PDF.

const FSDK = require("@foxitsoftware/foxit-pdf-sdk-node");
const fs = require('fs');
const os = require('os');
const path = require('path');

var sn = "bPxThFlBAYifO3yiW0C51bKbjPap1zHaf5aG5sX378TjFvB7Q0802A==";
var key = "8f3g1sGNtR8NAgfSNv+BvaJWy2fnrw36NZvzh8GUxYXvs+/YczAk4e34yqlOnmL4asgxGMO7+rlOcSHUSSKagx5g4G7VEXfkYLXnDDx77FOOedZPrFFcOCu1vT4+wOKzy1zkORq9cKtiFf44byH5sfRqf+OvELjep2teT9eF9yPCsSw2vRKljXlPy40DMP9XX1O5OTe+mSG3RvwKUMb0+RpG3YobM87j+/ynTDlJMMXw4vgwuTb1ZuAtlvkTdFz7HDLV81C6TYnn73ddHeGD3qYWBVsD4uJkDwyyH/SWr7QX0HSgVg8HSZqnab1VGdAUYxKY2vGWeOTJdu6qDGb5ZEb9O3kZZg+9LYAmUKzDfCYwfIsYZ8Y9LPC4wMx70kIq7JpNnzPvigrdshV8/ew1F0+qP/P5Z1EB53vDVrp2LVSuL873Wv4g3PzjZlNH+1qgT87hC+Buto4qsSUfP5Y2z0uApu+c/TfttCXbeMLSsw9TY1HQD3mkrZExMaQqRrAuXAcZWdvBnVuG3DCZmm8q0DLxJiCfYfViAU/AkbeKMIGaTJdrvIXBcssfde4nmU6qr0M4x4+Hs2ESddtY2QRtLAUBq/7h7GJlJHkEZr8ueaUy/6D/2vvAWz6wMLgmjlPbDTLqzfnCJylHCPtcJmu1SPPT9v1VreBX3+zNWcIT8HueyHEiUniqzwWkRKaotrnNb/zhnHLPpgaBSwKjyi8rOzzVwu/nY84G9ye4jsVjmkIRItKDrW7z22iS+QQuTwfqLVuMB0OD4jMkPCC2slzPfEeZnuh4+Rewln2qLRJVgI72zJ20OBWAelGSpO1Ii2Y3gOvojdmtUwx6R3Z1qFNWTTB25o9ytcux8BLOtTCkA8T8xaT4N339OTCsu/TmfahIDixKvr8cDa6F2WkBT8SOfv64W9PgiNv5B/BMOD2VWYaAl0N7yD0NkYYg/cDWRC4dfpdeip1jrr0k3mND0oSpIkxC+FicZbaYYwRdtJ9OSVWJ5OE0voLv8HgLze8mw6s4TrN3z+a2NQCveMa2VRN7YcEF7agPrvb/qU+otMwHae/wM7+f+HFAaOW+WTfzfxIVFB8/A1DN0NiEX+em4G7nO5F5ZcvfYPpaaioe8Nn33BbVLtMjXqsOBeM8AXiVfpD6YO75j7BqnBUPnivvD8BxJaaIQZvVSuQmvGm0ynt03IYwE8Rq+jYsunvsZ86jh5BiUR+Nm7sK0Qe9BdZn/7jdqohMv9czfMGUAscX+xBMunFbDpcRbWVpUADcm209L8Ndek2XY7YlCMxPgPVNvfWRF2jxehib9Tpd7zB5ZIDfAEH9zrpLfp29DLvCh2Yx8mH7xxdKG1O9Q0GdHphYHhej6smAcPm68R0GUQaTOLfXqNpueGJC1GAOI3Y4swjyt7jMTWcibnKLzwukWE5rnEDhn5n64JnyUM0ZFkRmtOiV";

const input_path = "../input_files/";
const output_path = "../output_files/";

let error_code = FSDK.Library.Initialize(sn, key);
if (FSDK.e_ErrSuccess != error_code) {
  if (FSDK.e_ErrInvalidLicense == error_code)
    console.log("[Failed] Current used Foxit PDF SDK key information is invalid.");
  else
    console.log("Library Initialize Error: %d", FSDK.e_ErrSuccess);
  return;
}

let output_directory = output_path + "associated_files/";
if (!fs.existsSync(output_directory)) {
  fs.mkdirSync(output_directory);
}

let input_file = input_path + "AF_Catalog_Page_Annot.pdf";
try {
  let doc = new FSDK.PDFDoc(input_file);
  let error_code = doc.Load("");
  if (error_code != FSDK.e_ErrSuccess) {
    console.log("The Doc [%s] Error: %d", input_file, error_code);
    return 1;
  }

  let associated_files = new FSDK.AssociatedFiles(doc)  
  let doc_catalog_dict = doc.GetCatalog();
  let count = associated_files.GetAssociatedFilesCount(doc_catalog_dict);
  console.log("The catalog dictionary of \"AF_Catalog_Page_Annot.pdf\" has %d associated files.", count);
  let filespec = associated_files.GetAssociatedFile(doc_catalog_dict, 0);
  console.log("The file name is \"%s\".\n", filespec.GetFileName());
  filespec.ExportToFile(output_directory + "af_1.txt");

  let page = doc.GetPage(0);
  let page_dict = page.GetDict();
  count = associated_files.GetAssociatedFilesCount(page_dict);
  console.log("The page dictionary of \"AF_Catalog_Page_Annot.pdf\" has %d associated files.n", count);
  filespec = associated_files.GetAssociatedFile(page_dict, 0);
  console.log("The file name is \"%s\".\n", filespec.GetFileName());
  filespec.ExportToFile(output_directory + "af_2.txt");

  let annot = page.GetAnnot(0);
  let annot_dict = annot.GetDict();
  count = associated_files.GetAssociatedFilesCount(annot_dict);
  console.log("The annot dictionary of \"AF_Catalog_Page_Annot.pdf\" has %d associated files.", count);
  filespec = associated_files.GetAssociatedFile(annot_dict, 0);
  console.log("The file name is \"%s\".\n",filespec.GetFileName());
  filespec.ExportToFile(output_directory + "af_4.txt");
} catch (e) {
  console.log(e); 
}

input_file = input_path + "AF_ImageXObject_FormXObject.pdf";
try {
  let doc = new FSDK.PDFDoc(input_file);
  let error_code = doc.Load("");
  if (error_code != FSDK.e_ErrSuccess) {
    console.log("The Doc [%s] Error: %d", input_file, error_code);
    return 1;
  }

  let associated_files = new FSDK.AssociatedFiles(doc);
  let page = doc.GetPage(0);
  page.StartParse(FSDK.PDFPage.e_ParsePageNormal, null, false);
  let pos = page.GetFirstGraphicsObjectPosition(FSDK.GraphicsObject.e_TypeImage);
  let image_x_object = page.GetGraphicsObject(pos);
  
  let image_x_object_dict = image_x_object.GetImageObject().GetStream().GetDictionary();
  let count = associated_files.GetAssociatedFilesCount(image_x_object_dict);
  console.log("The image x object of \"AF_ImageXObject_FormXObject.pdf\" has %d associated files.", count);
  let filespec = associated_files.GetAssociatedFile(image_x_object_dict, 0);
  console.log("The file name is \"%s\".\n", filespec.GetFileName());
  filespec.ExportToFile(output_directory + "2.jpg");

  pos = page.GetFirstGraphicsObjectPosition(FSDK.GraphicsObject.e_TypeFormXObject);
  let form_x_object = page.GetGraphicsObject(pos);
  let form_x_object_dict = form_x_object.GetFormXObject().GetStream().GetDictionary();
  count = associated_files.GetAssociatedFilesCount(form_x_object_dict);
  console.log("The form x object of \"AF_ImageXObject_FormXObject.pdf\" has %d associated files.", count);
  filespec = associated_files.GetAssociatedFile(form_x_object_dict, 0);
  console.log("The file name is \"%s\".\n", filespec.GetFileName());
  filespec.ExportToFile(output_directory + "af_6.txt");
} catch (e) {
  console.log(e); 
}

input_file = input_path + "AF_MarkedContent.pdf";
try {
  let doc = new FSDK.PDFDoc(input_file);
  let error_code = doc.Load("");
  if (error_code != FSDK.e_ErrSuccess) {
    console.log("The Doc [%s] Error: %d", input_file, error_code);
    return 1;
  }

  let associated_files = new FSDK.AssociatedFiles(doc);

  let page = doc.GetPage(0);
  page.StartParse(FSDK.PDFPage.e_ParsePageNormal, null, false);

  let pos = page.GetFirstGraphicsObjectPosition(FSDK.GraphicsObject.e_TypeText);
  let text_object = page.GetGraphicsObject(pos);
  let count = associated_files.GetAssociatedFilesCount(text_object);
  console.log("The text object of \"AF_MarkedContent.pdf\" has %d associated files.", count);
  let filespec = associated_files.GetAssociatedFile(text_object, 0);
  console.log("The first file name is \"%s\".", filespec.GetFileName());
  filespec.ExportToFile(output_directory + "bitmap.bmp");

  filespec = associated_files.GetAssociatedFile(text_object, 1);
  console.log("The second file name is \"%s\".\n", filespec.GetFileName());
  filespec.ExportToFile(output_directory + "text.txt");
} catch (e) {
  console.log(e); 
}


// Associate files with objects in PDF document.
input_file = input_path + "AssociateTestFile.pdf";
try{
  let doc = new FSDK.PDFDoc(input_file);
  let error_code = doc.Load("");
  if (error_code != FSDK.e_ErrSuccess) {
    console.log("The Doc [%s] Error: %d", input_file, error_code);
    return 1;
  }

  let associated_files = new FSDK.AssociatedFiles(doc);

  //Create filespec with 1.txt
  let filespec_txt = new FSDK.FileSpec(doc);
  filespec_txt.SetAssociteFileRelationship(FSDK.AssociatedFiles.e_RelationshipSource);
  filespec_txt.SetFileName("1.txt");
  let dateTime = new FSDK.DateTime(2017, 9, 15, 17, 20, 20, 0, 8, 0);
  filespec_txt.SetDescription("text");
  filespec_txt.Embed(input_path +  "1.txt");
  filespec_txt.SetCreationDateTime(dateTime);
  filespec_txt.SetModifiedDateTime(dateTime);
  filespec_txt.SetSubtype("application/octet-stream");

  //Associate 1.txt with catalog dictionary.
  {
    let catalog_dict = doc.GetCatalog();
    associated_files.AssociateFile(catalog_dict, filespec_txt);
    console.log("Associate a text file with catalog dictionary.");
    let filespec_catalog = associated_files.GetAssociatedFile(catalog_dict, 0);
    filespec_catalog.ExportToFile(output_directory + "catalog.txt");
  }

  var page = doc.GetPage(0);  
  page.StartParse(FSDK.PDFPage.e_ParsePageNormal, null, false);
  
  //Associate 1.txt with page dictionary.
  {
    associated_files.AssociateFile(page, filespec_txt);
    console.log("Associate a text file with page.");

    let filespec_page = associated_files.GetAssociatedFile(page.GetDict(), 0);
    filespec_page.ExportToFile(output_directory + "page.txt");
  }

  //Associate 1.txt with annotation dictionary.
  {
    let rect = new FSDK.RectF(100, 50, 220, 100);
    let annot = page.AddAnnot(FSDK.Annot.e_Note, rect);
    annot.ResetAppearanceStream();
    associated_files.AssociateFile(annot, filespec_txt);
    console.log("Associate a text file with annotation.");
    let filespec_annot = associated_files.GetAssociatedFile(annot.GetDict(), 0);
    filespec_annot.ExportToFile(output_directory + "annotation.txt");
  }

  //Create filespec with 2.jpg image.
  let filespec_jpg = new FSDK.FileSpec(doc);
  filespec_jpg.SetAssociteFileRelationship(FSDK.AssociatedFiles.e_RelationshipSource);
  filespec_jpg.SetFileName("2.jpg");
  filespec_jpg.SetDescription("jpeg");
  filespec_jpg.Embed(input_path +  "2.jpg");
  filespec_jpg.SetCreationDateTime(dateTime);
  filespec_jpg.SetModifiedDateTime(dateTime);
  filespec_jpg.SetSubtype("application/octet-stream");

  //Associate 2.jpg with marked content.
  {
    let page_dict = page.GetDict();
    let resource_dict = page_dict.GetElement("Resources");
    if (!resource_dict) return 1;

    let position = page.GetFirstGraphicsObjectPosition(FSDK.GraphicsObject.e_TypeText);
    let text_object = page.GetGraphicsObject(position);
    if (text_object) {
      let markcontent = text_object.GetMarkedContent();
      if (!markcontent) return 1;

      if (markcontent.GetItemCount() == 0) {
        markcontent.AddItem("Associated", null);
      }
      associated_files.AssociateFile(text_object, 0, resource_dict, "textobject", filespec_jpg);
      page.GenerateContent();

      console.log("Associate a jpeg file with markcontent.");

      let filespec_text_object = associated_files.GetAssociatedFile(text_object, 0);
      filespec_text_object.ExportToFile(output_directory + "textobject.jpg");
    }
  }

  //Associate 2.jpg with image object.
  {
    let position = page.GetFirstGraphicsObjectPosition(FSDK.GraphicsObject.e_TypeImage);
    let image_oject = page.GetGraphicsObject(position).GetImageObject();
    if (image_oject) {
      associated_files.AssociateFile(image_oject, filespec_jpg);
      console.log("Associate a jpeg file with image xobject.");

      let filespec_image_oject = associated_files.GetAssociatedFile(image_oject.GetStream().GetDictionary(), 0);
      filespec_image_oject.ExportToFile(output_directory + "image_x_object.jpg");
    }
  }

  //Associate 2.jpg with form XObject.
  {
    let position = page.GetFirstGraphicsObjectPosition(FSDK.GraphicsObject.e_TypeFormXObject);
    let form_x_object = page.GetGraphicsObject(position).GetFormXObject();
    if (form_x_object) {
      associated_files.AssociateFile(form_x_object, filespec_jpg);
      console.log("Associate a jpeg file with form xobject.");

      let filespec_form_x_object = associated_files.GetAssociatedFile(form_x_object.GetStream().GetDictionary(), 0);
      filespec_form_x_object.ExportToFile(output_directory + "form_x_object.jpg");
    }
  }

  // Save PDF file
  let newPdf = output_directory + "associated_files.pdf";
  doc.SaveAs(newPdf, FSDK.PDFDoc.e_SaveFlagNoOriginal);
} catch (e) {
  console.log(e); 
}

FSDK.Library.Release();