:tocdepth: 2 .. _Examples: Examples ******************************************************************************* This section provides some general examples on how to use the priint comet Python API. Toggle frame visibility =============================================================================== .. code-block:: python :caption: Toggle frame visibility #!py import comet def main(): visibleBefore = comet.gFrame.getVisible() comet.gFrame.setVisible(not visibleBefore) visibleNow = comet.gFrame.getVisible() comet.showMessage(f'Was visible: {visibleBefore}, is now visible: {visibleNow}') return 0 Toggle frame lock state =============================================================================== .. code-block:: python :caption: Toggle frame lock state #!py import comet def main(): lockedBefore = comet.gFrame.getLocked() comet.gFrame.setLocked(not lockedBefore) lockedNow = comet.gFrame.getLocked() comet.showMessage(f'Was locked: {lockedBefore}, is now locked: {lockedNow}') return 0 Show all script tags =============================================================================== .. code-block:: python :caption: Show all script tags of gFrame as a message box #!py import comet def main(): scriptTags = comet.gFrame.getScriptTags() comet.showMessage(str(scriptTags)) return 0 Reflection =============================================================================== .. code-block:: python :caption: Reflect all comet members and output them to the logfile #!py #pragma plain import inspect import sys import comet def reflect(obj, depth: int = 0): #reflect an object by inspecting all attributes and returning a summarizing string message = '' for name in dir(obj): if name.startswith('_'): continue attr = getattr(obj, name) for i in range(depth): message += '\t' message += '{} - {}\n'.format(name, attr) if inspect.isclass(attr) or inspect.ismodule(attr): message += reflect(attr, depth + 1) return message def reflectComet(): #do a full reflection of all comet members and produce a nice formatted output message = 'Comet reflection:\n' host = comet.host.getType() if host == 0: message += "Running in InDesign\n" if host == 1: message += "Running in InDesign Server\n" if host == 2: message += "Running in comet_pdf\n" if host == 3: message += "Running in Illustrator\n" message += reflect(comet) comet.wlog(message) def main(): reflectComet() return 0 Generate page previews =============================================================================== .. code-block:: python :caption: Generate a JPEG for each page of the front document and save it #!py #pragma plain import os import comet def main(): #Use the front document document = comet.CDocument.getFront() if not document: return 0 pages = document.getPages() #Select a target folder to place the previews into: #This opens a dialog which prompts the user to select a target folder #We suggest the Desktop as the initial folder for the user outFolder = comet.dialog.selectFolder(suggestion = '$DESKTOP') if not outFolder: #User cancelled - we stop the script return 0 #Export all page previews as JPEG since that is supported on each platform for page in pages: pageName = page.getName() fileName = pageName + '.jpg' filePath = os.path.join(outFolder, fileName) page.createSnapshot(filePath) return 0 Get publication info =============================================================================== .. code-block:: python :caption: Using a priint Pubserver connection, output available publication information #!py import comet def walkPublications(parentID: str = '', recursive: bool = True, depth: int = 0): """Recursively walk through all publications and output them to the logfile with proper indentation""" #Fetch all publications. When parentID is empty we get the root entries = comet.publication.getPublications(parentID) for entry in entries: name = entry.getValue(comet.kPublicationName) hasChildren = entry.getValue(comet.kPublicationHasChildren) #depth is only used for indentation in the logfile logPrefix = '' for i in range(depth): logPrefix += '\t' comet.wlog(f'{logPrefix}Publication "{name}":') #We simply use all available selectors to get all the information we need for selector, label in comet.kPublicationSelectors.items(): value = None #We use try/catch here since getValue throws when the selector is invalid try: value = entry.getValue(selector) except: continue comet.wlog(f'{logPrefix}\tSelector: {label} - Value: {value}') if hasChildren and recursive: #Recursively walk down parentID = entry.getValue(comet.kPublicationStringid) walkPublications(parentID, True, depth + 1) def main(): walkPublications() return 0 Disable all panels =============================================================================== .. code-block:: python :caption: Disable all panels #!py import comet def main(): for key, value in comet.kPanelIDs.items(): if key == comet.kPanelUndef: continue #We need to try/catch since not all panels are available for all hosts. #In this case the function throws. try: comet.prefs.setPanelEnabled(key, False, "I am locked!") except: pass return 0 Get all style names =============================================================================== .. code-block:: python :caption: Get all style names from every style type from the current document and show them as a message #!py import comet def main(): message = 'All document styles:' for styleType, styleTypeName in comet.kStyleTypes.items(): message += f'\n{styleTypeName}:' styles = comet.gDocument.getStyleNames(styleType) for style in styles: message += f'\n\t{style}' comet.showMessage(message) return 0 Read Excel file to HTML =============================================================================== .. code-block:: python :caption: Open an excel file and fetch all cell data as HTML #!py #pragma plain import comet import datetime import time def getCellStyle(book: comet.CExcelBook, sheet, column, row): #Get the cell style information as HTML by querying cell format #attributes and translating them to CSS tags openTag = ' 0: cellValue += f' / Format {formatID}' if formatStr: cellValue += f' {formatStr}' except: pass try: formula = ebook.getCellFormula(sheet, column, row) if formula: cellValue += f' {formula}' except: pass cellValue += closeTag completeData += cellValue completeData += '
\n' completeData += '
\n' comet.wlog(completeData) comet.gFrame.replace(completeData) ebook.close() return 0 Get CTextModel style runs =============================================================================== .. code-block:: python :caption: Write information about all paragraph(or character) style runs for the current CTextModel #!py #pragma plain import comet def echoStyleRuns(paraStyle: bool) -> None: tm = comet.gTextModel maxLength = tm.getLength() nextStart = 0 while True: data = None if paraStyle: data = tm.getParaStyle(nextStart, True) else: data = tm.getCharStyle(nextStart, True) #data contains name, start, length name, start, length = data if (length <= 0 or nextStart >= maxLength): break message = 'Name: {}\nStart: {}\nLength: {}'.format(name, start, length) comet.wlog('--------------------------------------------------------------------------------') comet.wlog(message) nextStart = start + length def main(): echoStyleRuns(True) #echo para style runs # echoStyleRuns(False) #uncomment this line to echo char style runs return 0 Get CLink information from document =============================================================================== .. code-block:: python :caption: Fetch information about all links in a document and output them to the logfile #!py #pragma plain import comet def main(): doc = comet.document.getFront() try: links = comet.link.collect(doc) comet.wlog("comet.link.collect results:") for link in links: linkMessage = '--------------------------------------------------\n' linkMessage += f'PlaceHolder ID: {link.getPlaceHolderID()}\n' linkMessage += f'RecordID ID: {link.getRecordID()}\n' linkType = link.getType() if linkType is comet.CLink.kTypeText: linkMessage += 'Type: Text\n' linkMessage += f'Position: {link.getPosition()}\n' linkMessage += f'Length: {link.getLength()}\n' elif linkType is comet.CLink.kTypeFrame: linkMessage += 'Type: Frame\n' linkMessage += f'Layer: {link.getLayer().getName()}\n' funcVarsLoad = link.getFuncVars(comet.kActionTypeLoad) linkMessage += 'FuncVars load:\n' for funcVar in funcVarsLoad: linkMessage += f'\tKey: {funcVar[0]} | Value: {funcVar[1]}\n' funcVarsStore = link.getFuncVars(comet.kActionTypeStore) linkMessage += 'FuncVars store:\n' for funcVar in funcVarsStore: linkMessage += f'\tKey: {funcVar[0]} | Value: {funcVar[1]}\n' funcVarsSync = link.getFuncVars(comet.kActionTypeSync) linkMessage += 'FuncVars sync:\n' for funcVar in funcVarsSync: linkMessage += f'\tKey: {funcVar[0]} | Value: {funcVar[1]}\n' funcVarsBuild = link.getFuncVars(comet.kActionTypeBuild) linkMessage += 'FuncVars build:\n' for funcVar in funcVarsBuild: linkMessage += f'\tKey: {funcVar[0]} | Value: {funcVar[1]}\n' comet.wlog(linkMessage) comet.wlog('--------------------------------------------------') comet.wlog("comet.link.collect results end") except Exception as e: comet.showMessage(str(e)) return 0 Get swatch information from document =============================================================================== .. code-block:: python :caption: Fetch information about all swatches in a document and output them to the logfile #!py #pragma plain import comet def main(): swatches = comet.color.getSwatches(None) for swatch in swatches: name = swatch.getName() space = swatch.getSpace() type = swatch.getType() tint = swatch.getTint() isSpot = swatch.getIsSpot() isReserved = swatch.getIsReserved() isLocked = swatch.getIsLocked() colors = swatch.getColors() comet.wlog(f"""Swatch: Name: {name} Type: {type} Space: {space} Colors: {colors} IsSpot: {isSpot} IsReserved: {isReserved} IsLocked: {isLocked} Tint: {tint}""") return 0 Output all sibling book documents to the logfile =============================================================================== .. code-block:: python :caption: Get the path of all sibling documents in the same book and output them to the logfile #!py import comet def main(): book = comet.gDocument.getBook() if book: gDocumentPath = comet.gDocument.getPath() documents = book.getDocuments() for docPath in documents: if docPath == gDocumentPath: continue comet.wlog(docPath) else: comet.wlog('No book found') return 0 Parse and traverse an XML tree =============================================================================== .. code-block:: python :caption: Parse a CXMLTree from an XML string and walk through all nodes in preorder fashion, outputting their names to the logfile #!py import comet data = """ 1 1 Orange juice Orangensaft Jus d‘orange <b>Ingredients:</b> Orange juice from concentrate. <b>Zutaten:</b> Orangensaft aus Konzentrat. <b>Ingrédients:</b> jus d‘orange à partir de concentré Energy Energie Énergie 1 Juice """ def main(): #Do a stack based iteration through all nodes in the tree tree = comet.xmltree.parse(data) stack = [(tree.getRoot(), 0)] #store node and depth as entries while stack: node, depth = stack.pop() name = node.getName() children = node.getChildren() while children: stack.append((children.pop(), depth + 1)) comet.wlog('\t' * depth + name) #use the depth to indent the log message return 0