sarbjit2k

Import Multiple Pages from PDF

Sep 13th, 2018
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. File: Import Multiple Pages from PDF.js
  3. Description: The script reads a PDF at a user given location and creates necessary pages in the document
  4. All pdf pages are then imported as images in the document
  5. */
  6.  
  7. (function () {
  8.     //************* Default Values - Changes made here are safe
  9.     const defaultPDFPath = ""; //e.g. "C:\\SomeFolder\\SomeFile.pdf" OR "/Volumes/SomeFolder/SomeFile.pdf"
  10.  
  11.     //************* Do NOT make changes beyond this point if you don't know JavaScript
  12.     const dependencies = ["qx_constants", "qx_validations", "qx_inputs"]; //File Names of Dependencies to Load From QuarkXPress App (skip .js extension)
  13.     let startTime, endTime;
  14.  
  15.     //Import Dependency Scripts
  16.     importDependencies(dependencies);
  17.  
  18.     if (qxValidations.isLayoutOpen()) {
  19.         let validFileExtns = [{ types: ['pdf'], typesName: "PDF Files" }];
  20.         let pdfPath = getFilePath("Please select the pdf file: ", defaultPDFPath, validFileExtns);
  21.         if (pdfPath != null) {
  22.             pdfPath = qxFileIO.convertURIToFilePath(pdfPath);
  23.             console.log("Entered pdf path : " + pdfPath);
  24.             let maxPages = app.components.pdf.getPDFNumPages(pdfPath);
  25.  
  26.             if (qxConstants.debugMode) console.log("Number of pages in PDF: " + maxPages);
  27.             let pdfStartPage, pdfEndPage;
  28.             let pdfPages;
  29.  
  30.             if (maxPages <= 0) {
  31.                 showResult("Invalid file. Unable to get number of pages.");
  32.             }
  33.             else if (maxPages == 1) {
  34.                 pdfStartPage = 1;
  35.                 pdfEndPage = 1;
  36.             }
  37.             else {
  38.                 let inputStr = "Please enter the range of pages of PDF to import:";
  39.                 let defVal = "1 - " + maxPages;
  40.                 pdfPages = qxInputs.getValidNumericRangeInput(inputStr, defVal, 1, maxPages);
  41.                 if (pdfPages != null) {
  42.                     pdfStartPage = pdfPages.start;
  43.                     pdfEndPage = pdfPages.end;
  44.                 }
  45.                 else {//user cancelled
  46.                     pdfStartPage = -1;
  47.                     pdfEndPage = -1;
  48.                 }
  49.             }
  50.             if (pdfStartPage > 0 && pdfEndPage > 0) {
  51.                 let numPages = (pdfEndPage - pdfStartPage) + 1;
  52.                 console.log("Importing " + numPages + " page(s) from the PDF");
  53.  
  54.                 //Start the Timer
  55.                 startTime = performance.now();
  56.                 app.dialogs.openProgressDialog("Please wait");
  57.  
  58.                 if (numPages > 1)
  59.                     createPages(numPages)
  60.                         .then(() => importPDF(pdfPath, numPages, pdfStartPage))
  61.                         .then(() => logTimeTaken())
  62.                         .then(() => showResult("Imported PDF successfully."));
  63.                 else
  64.                     importPDF(pdfPath, numPages, pdfStartPage)
  65.                         .then(() => logTimeTaken())
  66.                         .then(() => showResult("Imported PDF successfully."));;
  67.             }
  68.         }
  69.     }
  70.  
  71.     //*****************====================================Functions used in the JavaScript===============================****************//
  72.     //creates the necessary number of pages
  73.     function createPages(numPages) {
  74.         console.log("Creating " + numPages + " pages in the layout.");
  75.         let promise = new Promise(function (resolve, reject)//promise is used to ensure this task completes and return a promise followed by further execution
  76.         {
  77.             //console.log("Creating pages");
  78.             let layoutNode = app.activeLayoutDOM();
  79.             let pages = layoutNode.getElementsByTagName('qx-page');
  80.             let existingPageCount = pages.length;
  81.             //create numPages-existingPageCount pages (since existingPageCount pages are already present)
  82.             for (let i = existingPageCount + 1; i <= numPages; i++) {
  83.                 let qxPage = document.createElement("qx-page");
  84.                 qxPage.setAttribute("page-index", i);
  85.                 let qxSpread = document.createElement("qx-spread");
  86.                 qxSpread.setAttribute("spread-index", i);
  87.                 qxSpread.appendChild(qxPage);
  88.                 layoutNode.appendChild(qxSpread);
  89.                 if (qxConstants.debugMode) console.log("Creating page number " + i);
  90.             }
  91.             Promise.resolve().then(resolve({}));
  92.         });
  93.         return promise;
  94.     }
  95.  
  96.     //imports the pdf into image boxes on pages
  97.     function importPDF(pdfPath, numPages, pdfStartPage) {
  98.         console.log("Importing '" + pdfPath + "', " + numPages + " pages starting from page " + pdfStartPage + ".");
  99.         let promise = new Promise(function (resolve, reject)//promise is used to ensure this task completes and return a promise followed by further execution
  100.         {
  101.             let itemStyleConf, itemStyleToBeApplied, itemStyleClass, qxBox, imgTag;
  102.             //Get DOM of active Layout
  103.             let layoutNode = app.activeLayoutDOM();//get the layout DOM
  104.             let layout = app.activeLayout();
  105.             //get existing pages
  106.             let pages = layoutNode.getElementsByTagName('qx-page');//get all pages on the layout
  107.  
  108.             //get the active project
  109.             let assetType = app.constants.assetTypes.kAssetItemStyle;
  110.             let itemStyleName = qxInputs.getAssetNamesAsArray(assetType);
  111.             if (!(itemStyleName.length == 1 && itemStyleName[0] == "No Style")) {
  112.                 //confirm if the user wants to apply item style
  113.                 itemStyleConf = confirm("Do you want to apply some item style to the picture boxes of pdf?");
  114.                 if (itemStyleConf) {
  115.                     //get valid item style to be applied
  116.                     itemStyleToBeApplied = qxInputs.getValidAssetNameInput(assetType, "Please Enter the item style to be applied:", "");
  117.                     if (itemStyleToBeApplied != null) {
  118.                         //get the class name for this item style
  119.                         itemStyleClass = app.components.qxml.getClassNameFromAssetName(itemStyleToBeApplied, assetType);
  120.                     }
  121.                 }
  122.             }
  123.             //create image boxes on all pages
  124.             for (let j = 0; j < numPages; j++) {
  125.                 qxBox = document.createElement("qx-box");//create box
  126.                 //specify offsets for boxes[i]
  127.                 qxBox.setAttribute("box-content-type", "picture");
  128.                 qxBox.style.qxTop = '0in';
  129.                 qxBox.style.qxLeft = '0in';
  130.                 if (layout.getPrintLayoutOptions() == null)//digital layout
  131.                 {
  132.                     qxBox.style.qxBottom = '1024px';//Assume default height
  133.                     qxBox.style.qxRight = '768px';//Assume default width
  134.                 }
  135.                 else {
  136.                     qxBox.style.qxBottom = layout.getPrintLayoutOptions().pageHeight.replace("\"", "in");
  137.                     qxBox.style.qxRight = layout.getPrintLayoutOptions().pageWidth.replace("\"", "in");
  138.                 }
  139.                 //apply item style to box
  140.                 qxBox.classList.add(itemStyleClass);
  141.                 qxBox.style.qxPage = j + 1;
  142.                 let srcPath = pdfPath + '#page=' + pdfStartPage;
  143.                 pdfStartPage++;
  144.  
  145.                 //create the image element
  146.                 //console.log("Creating image tag");
  147.                 imgTag = document.createElement('qx-img');
  148.                 //console.log("Setting image path to tag");
  149.                 imgTag.setAttribute("src", srcPath);
  150.                 //console.log("Adding image to box");
  151.                 qxBox.appendChild(imgTag);
  152.                 //console.log("Added image to box");
  153.                 //add the new box
  154.                 //console.log("Adding box to layout");
  155.                 pages[j].parentNode.appendChild(qxBox);
  156.                 //console.log("Added box to layout");
  157.  
  158.             }
  159.             Promise.resolve().then(resolve({}));
  160.         });
  161.         return promise;
  162.     }
  163.  
  164.     /*Function to Import Required Libraries
  165.     */
  166.     function importDependencies(list) {
  167.         for (i = 0, max = list.length; i < max; i++) {
  168.             let dependency = list[i];
  169.             let isDefined = null;
  170.  
  171.             switch (dependency) {
  172.                 case "qx_constants":
  173.                     isDefined = typeof (qxConstants);
  174.                     break;
  175.                 case "qx_create_box":
  176.                     isDefined = typeof (qxCreateBox);
  177.                     break;
  178.                 case "qx_file_io":
  179.                     isDefined = typeof (qxFileIO);
  180.                     break;
  181.                 case "qx_get_boxes":
  182.                     isDefined = typeof (qxGetBoxes);
  183.                     break;
  184.                 case "qx_inputs":
  185.                     isDefined = typeof (qxInputs);
  186.                     break;
  187.                 case "qx_measurements":
  188.                     isDefined = typeof (qxMeasurements);
  189.                     break;
  190.                 case "qx_validations":
  191.                     isDefined = typeof (qxValidations);
  192.                     break;
  193.                 default:
  194.                     isDefined = "undefined";
  195.                     console.log("Dependency " + dependency + ".js will be imported without checking if it is loaded already."); //Other Libraries are importing without checking if they are already loaded
  196.             }
  197.  
  198.             if (isDefined == "undefined") {
  199.                 //import library
  200.                 app.importScript(app.getAppScriptsFolder() + "/Dependencies/" + dependency + ".js");
  201.                 console.log("Imported Dependency " + dependency + ".js.");
  202.             }
  203.             else {
  204.                 if (qxConstants.debugMode) console.log("Dependency " + dependency + ".js already loaded.");
  205.             }
  206.         }
  207.     }
  208.  
  209.     /* Function to get File Path
  210.     */
  211.     function getFilePath(defTitle = "Select File", defPath = "", defFileExtensions = "") {
  212.         let splitPath, defFolder;
  213.         //Get Folder Path from File Path
  214.         if (defPath != "") {
  215.             splitPath = qxFileIO.splitFilePath(defPath);
  216.             defFolder = splitPath.folder;
  217.         }
  218.         return app.dialogs.openFileDialog(defTitle, defFolder, defFileExtensions);;
  219.     }
  220.  
  221.     /*Function to log Execution Time
  222.     */
  223.     function logTimeTaken() {
  224.         endTime = performance.now();
  225.         let timeTaken = Math.round((endTime - startTime) / 1000);
  226.         console.log("Time Taken: ", timeTaken, " seconds");
  227.     }
  228.  
  229.     /* Function to show Alert and Log
  230.     */
  231.     function showResult(msgString) {
  232.         app.dialogs.closeDialog();
  233.         console.log(msgString);
  234.         if (!qxConstants.testMode) alert(msgString); //Don't show alerts in TestMode
  235.     }
  236. })();
Add Comment
Please, Sign In to add comment