Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- File: Import Multiple Pages from PDF.js
- Description: The script reads a PDF at a user given location and creates necessary pages in the document
- All pdf pages are then imported as images in the document
- */
- (function () {
- //************* Default Values - Changes made here are safe
- const defaultPDFPath = ""; //e.g. "C:\\SomeFolder\\SomeFile.pdf" OR "/Volumes/SomeFolder/SomeFile.pdf"
- //************* Do NOT make changes beyond this point if you don't know JavaScript
- const dependencies = ["qx_constants", "qx_validations", "qx_inputs"]; //File Names of Dependencies to Load From QuarkXPress App (skip .js extension)
- let startTime, endTime;
- //Import Dependency Scripts
- importDependencies(dependencies);
- if (qxValidations.isLayoutOpen()) {
- let validFileExtns = [{ types: ['pdf'], typesName: "PDF Files" }];
- let pdfPath = getFilePath("Please select the pdf file: ", defaultPDFPath, validFileExtns);
- if (pdfPath != null) {
- pdfPath = qxFileIO.convertURIToFilePath(pdfPath);
- console.log("Entered pdf path : " + pdfPath);
- let maxPages = app.components.pdf.getPDFNumPages(pdfPath);
- if (qxConstants.debugMode) console.log("Number of pages in PDF: " + maxPages);
- let pdfStartPage, pdfEndPage;
- let pdfPages;
- if (maxPages <= 0) {
- showResult("Invalid file. Unable to get number of pages.");
- }
- else if (maxPages == 1) {
- pdfStartPage = 1;
- pdfEndPage = 1;
- }
- else {
- let inputStr = "Please enter the range of pages of PDF to import:";
- let defVal = "1 - " + maxPages;
- pdfPages = qxInputs.getValidNumericRangeInput(inputStr, defVal, 1, maxPages);
- if (pdfPages != null) {
- pdfStartPage = pdfPages.start;
- pdfEndPage = pdfPages.end;
- }
- else {//user cancelled
- pdfStartPage = -1;
- pdfEndPage = -1;
- }
- }
- if (pdfStartPage > 0 && pdfEndPage > 0) {
- let numPages = (pdfEndPage - pdfStartPage) + 1;
- console.log("Importing " + numPages + " page(s) from the PDF");
- //Start the Timer
- startTime = performance.now();
- app.dialogs.openProgressDialog("Please wait");
- if (numPages > 1)
- createPages(numPages)
- .then(() => importPDF(pdfPath, numPages, pdfStartPage))
- .then(() => logTimeTaken())
- .then(() => showResult("Imported PDF successfully."));
- else
- importPDF(pdfPath, numPages, pdfStartPage)
- .then(() => logTimeTaken())
- .then(() => showResult("Imported PDF successfully."));;
- }
- }
- }
- //*****************====================================Functions used in the JavaScript===============================****************//
- //creates the necessary number of pages
- function createPages(numPages) {
- console.log("Creating " + numPages + " pages in the layout.");
- let promise = new Promise(function (resolve, reject)//promise is used to ensure this task completes and return a promise followed by further execution
- {
- //console.log("Creating pages");
- let layoutNode = app.activeLayoutDOM();
- let pages = layoutNode.getElementsByTagName('qx-page');
- let existingPageCount = pages.length;
- //create numPages-existingPageCount pages (since existingPageCount pages are already present)
- for (let i = existingPageCount + 1; i <= numPages; i++) {
- let qxPage = document.createElement("qx-page");
- qxPage.setAttribute("page-index", i);
- let qxSpread = document.createElement("qx-spread");
- qxSpread.setAttribute("spread-index", i);
- qxSpread.appendChild(qxPage);
- layoutNode.appendChild(qxSpread);
- if (qxConstants.debugMode) console.log("Creating page number " + i);
- }
- Promise.resolve().then(resolve({}));
- });
- return promise;
- }
- //imports the pdf into image boxes on pages
- function importPDF(pdfPath, numPages, pdfStartPage) {
- console.log("Importing '" + pdfPath + "', " + numPages + " pages starting from page " + pdfStartPage + ".");
- let promise = new Promise(function (resolve, reject)//promise is used to ensure this task completes and return a promise followed by further execution
- {
- let itemStyleConf, itemStyleToBeApplied, itemStyleClass, qxBox, imgTag;
- //Get DOM of active Layout
- let layoutNode = app.activeLayoutDOM();//get the layout DOM
- let layout = app.activeLayout();
- //get existing pages
- let pages = layoutNode.getElementsByTagName('qx-page');//get all pages on the layout
- //get the active project
- let assetType = app.constants.assetTypes.kAssetItemStyle;
- let itemStyleName = qxInputs.getAssetNamesAsArray(assetType);
- if (!(itemStyleName.length == 1 && itemStyleName[0] == "No Style")) {
- //confirm if the user wants to apply item style
- itemStyleConf = confirm("Do you want to apply some item style to the picture boxes of pdf?");
- if (itemStyleConf) {
- //get valid item style to be applied
- itemStyleToBeApplied = qxInputs.getValidAssetNameInput(assetType, "Please Enter the item style to be applied:", "");
- if (itemStyleToBeApplied != null) {
- //get the class name for this item style
- itemStyleClass = app.components.qxml.getClassNameFromAssetName(itemStyleToBeApplied, assetType);
- }
- }
- }
- //create image boxes on all pages
- for (let j = 0; j < numPages; j++) {
- qxBox = document.createElement("qx-box");//create box
- //specify offsets for boxes[i]
- qxBox.setAttribute("box-content-type", "picture");
- qxBox.style.qxTop = '0in';
- qxBox.style.qxLeft = '0in';
- if (layout.getPrintLayoutOptions() == null)//digital layout
- {
- qxBox.style.qxBottom = '1024px';//Assume default height
- qxBox.style.qxRight = '768px';//Assume default width
- }
- else {
- qxBox.style.qxBottom = layout.getPrintLayoutOptions().pageHeight.replace("\"", "in");
- qxBox.style.qxRight = layout.getPrintLayoutOptions().pageWidth.replace("\"", "in");
- }
- //apply item style to box
- qxBox.classList.add(itemStyleClass);
- qxBox.style.qxPage = j + 1;
- let srcPath = pdfPath + '#page=' + pdfStartPage;
- pdfStartPage++;
- //create the image element
- //console.log("Creating image tag");
- imgTag = document.createElement('qx-img');
- //console.log("Setting image path to tag");
- imgTag.setAttribute("src", srcPath);
- //console.log("Adding image to box");
- qxBox.appendChild(imgTag);
- //console.log("Added image to box");
- //add the new box
- //console.log("Adding box to layout");
- pages[j].parentNode.appendChild(qxBox);
- //console.log("Added box to layout");
- }
- Promise.resolve().then(resolve({}));
- });
- return promise;
- }
- /*Function to Import Required Libraries
- */
- function importDependencies(list) {
- for (i = 0, max = list.length; i < max; i++) {
- let dependency = list[i];
- let isDefined = null;
- switch (dependency) {
- case "qx_constants":
- isDefined = typeof (qxConstants);
- break;
- case "qx_create_box":
- isDefined = typeof (qxCreateBox);
- break;
- case "qx_file_io":
- isDefined = typeof (qxFileIO);
- break;
- case "qx_get_boxes":
- isDefined = typeof (qxGetBoxes);
- break;
- case "qx_inputs":
- isDefined = typeof (qxInputs);
- break;
- case "qx_measurements":
- isDefined = typeof (qxMeasurements);
- break;
- case "qx_validations":
- isDefined = typeof (qxValidations);
- break;
- default:
- isDefined = "undefined";
- 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
- }
- if (isDefined == "undefined") {
- //import library
- app.importScript(app.getAppScriptsFolder() + "/Dependencies/" + dependency + ".js");
- console.log("Imported Dependency " + dependency + ".js.");
- }
- else {
- if (qxConstants.debugMode) console.log("Dependency " + dependency + ".js already loaded.");
- }
- }
- }
- /* Function to get File Path
- */
- function getFilePath(defTitle = "Select File", defPath = "", defFileExtensions = "") {
- let splitPath, defFolder;
- //Get Folder Path from File Path
- if (defPath != "") {
- splitPath = qxFileIO.splitFilePath(defPath);
- defFolder = splitPath.folder;
- }
- return app.dialogs.openFileDialog(defTitle, defFolder, defFileExtensions);;
- }
- /*Function to log Execution Time
- */
- function logTimeTaken() {
- endTime = performance.now();
- let timeTaken = Math.round((endTime - startTime) / 1000);
- console.log("Time Taken: ", timeTaken, " seconds");
- }
- /* Function to show Alert and Log
- */
- function showResult(msgString) {
- app.dialogs.closeDialog();
- console.log(msgString);
- if (!qxConstants.testMode) alert(msgString); //Don't show alerts in TestMode
- }
- })();
Add Comment
Please, Sign In to add comment