//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------
// The following sample illustrates how to convert to PDF with virtual printer on Windows.
// It supports several input formats like docx, xlsx, rtf, txt, html, pub, emf, etc. For more details, visit 
// https://docs.apryse.com/documentation/windows/guides/features/conversion/convert-other/
//
// To check if ToPDF (or ToXPS) require that PDFNet printer is installed use Convert::RequiresPrinter(filename). 
// The installing application must be run as administrator. The manifest for this sample 
// specifies appropriate the UAC elevation.
//
// Note: the PDFNet printer is a virtual XPS printer supported on Vista SP1 and Windows 7.
// For Windows XP SP2 or higher, or Vista SP0 you need to install the XPS Essentials Pack (or 
// equivalent redistributables). You can download the XPS Essentials Pack from:
//		http://www.microsoft.com/downloads/details.aspx?FamilyId=B8DCFFDD-E3A5-44CC-8021-7649FD37FFEE&displaylang=en
// Windows XP Sp2 will also need the Microsoft Core XML Services (MSXML) 6.0:
// 		http://www.microsoft.com/downloads/details.aspx?familyid=993C0BCF-3BCF-4009-BE21-27E85E1857B1&displaylang=en
//
// Note: Convert.fromEmf and Convert.toEmf will only work on Windows and require GDI+.
//
// Please contact us if you have any questions.	
//---------------------------------------------------------------------------------------

const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
  'use strict';

  let Testfile = function (inputFile, outputFile) {
    this.inputFile = inputFile;
    this.outputFile = outputFile;
  }

  const testfiles = [
    new Testfile('simple-word_2007.docx', 'docx2pdf.pdf'),
    new Testfile('simple-powerpoint_2007.pptx', 'pptx2pdf.pdf'),
    new Testfile('simple-excel_2007.xlsx', 'xlsx2pdf.pdf'),
    new Testfile('simple-publisher.pub', 'pub2pdf.pdf'),
    new Testfile('simple-text.txt', 'txt2pdf.pdf'),
    new Testfile('simple-rtf.rtf', 'rtf2pdf.pdf'),
    new Testfile('simple-emf.emf', 'emf2pdf.pdf'),
    new Testfile('simple-webpage.mht','mht2pdf.pdf'),
    new Testfile('simple-webpage.html', 'html2pdf.pdf'),
  ]



  const inputPath = '../TestFiles/';
  const outputPath = '../TestFiles/Output/';

  exports.runConvertPrintTest = () => {

    const main = async () => {
    if (process.platform === 'win32') {	
      try {
        await convertToPdfFromFile();
        console.log('ConvertFile succeeded');
      } catch (err) {
        console.log('ConvertFile failed');
        console.log(err);
      }

      try {
        await convertSpecificFormats();
        console.log('ConvertSpecificFormats succeeded');
      } catch (err) {
        console.log('ConvertSpecificFormats failed');
        console.log(err);
      }
      if (await PDFNet.Convert.printerIsInstalled()) {
        try {
          console.log('Uninstalling printer (requires Windows platform and administrator)');
          await PDFNet.Convert.printerUninstall();
          console.log('Uninstalled printer ' + await PDFNet.Convert.printerGetPrinterName());
        } catch (err) {
          console.log('Unable to uninstall printer');
        }
      }
      console.log('Done.');
    }
    else {
        console.log('ConvertPrintTest only available on Windows');	  
    }
    };

    const convertToPdfFromFile = async () => {
        if (await PDFNet.Convert.printerIsInstalled('PDFTron PDFNet')) {
          await PDFNet.Convert.printerSetPrinterName('PDFTron PDFNet');
        } else if (!(await PDFNet.Convert.printerIsInstalled())) {
          try {
            // This will fail if not run as administrator. Harmless if PDFNet 
            // printer already installed
            console.log('Installing printer (requires Windows platform and administrator)');
            await PDFNet.Convert.printerInstall();
            console.log('Installed printer ' + await PDFNet.Convert.printerGetPrinterName());
          } catch (err) {
            console.log('Unable to install printer');
          }
        }
      for (const testfile of testfiles) {

        try {
          const pdfdoc = await PDFNet.PDFDoc.create();
          await pdfdoc.initSecurityHandler();
          const inputFile = inputPath + testfile.inputFile;
          const outputFile = outputPath + testfile.outputFile;
          if (await PDFNet.Convert.requiresPrinter(inputFile)) {
            console.log('Using PDFNet printer to convert file ' + testfile.inputFile);
          }
          await PDFNet.Convert.toPdf(pdfdoc, inputFile);
          await pdfdoc.save(outputFile, PDFNet.SDFDoc.SaveOptions.e_linearized);
          console.log('Converted file: ' + testfile.inputFile + '\nto: ' + testfile.outputFile);
        } catch (err) {
          console.log('Unable to convert file ' + testfile.inputFile);
          console.log(err);
        }
      }
    };

    const convertSpecificFormats = async () => {

        try {
          // Convert MSWord document to XPS
          console.log('Converting DOCX to XPS');
          await PDFNet.Convert.fileToXps(inputPath + 'simple-word_2007.docx', outputPath + 'simple-word_2007.xps');
          console.log('Saved simple-word_2007.xps');
        } catch (err) {
          console.log(err);
        }
        try {
          const pdfdoc = await PDFNet.PDFDoc.create();
          await pdfdoc.initSecurityHandler();

          console.log('Converting from EMF');
          await PDFNet.Convert.fromEmf(pdfdoc, inputPath + 'simple-emf.emf');
          await pdfdoc.save(outputPath + 'emf2pdf v2.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);
          console.log('Saved emf2pdf v2.pdf');
        } catch (err) {
          console.log(err);
        }
    };
    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
      console.log('Error: ' + JSON.stringify(error));
    }).then(function(){ return PDFNet.shutdown(); });
  };
  exports.runConvertPrintTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=ConvertPrintTest.js
