def exportText(textfile): page = 1 pagenum = scribus.pageCount() T = [] content = [] while (page <= pagenum): scribus.gotoPage(page) d = scribus.getPageItems() strpage = str(page) T.append('Page '+ strpage + '\n\n') for item in d: if (item[1] == 4): contents = scribus.getAllText(item[0]) if (contents in content): contents = 'Duplication, perhaps linked-to frame' T.append(item[0]+': '+ contents + '\n\n') content.append(contents) elif (item[1] == 2): imgname = scribus.getImageFile(item[0]) T.append(item[0]+': ' + imgname + '\n') page += 1 T.append('\n') output_file = open(textfile,'w') output_file.writelines(T) output_file.close() endmessage = textfile + ' was created' scribus.messageBox("Finished", endmessage,icon=0,button1=1)
def run(self): selCount = scribus.selectionCount() if selCount == 0: scribus.messageBox('Scribus Data Merger- Usage Error', "There is no objects selected.\nPlease try again.", scribus.ICON_WARNING, scribus.BUTTON_OK) sys.exit(2) csvData = self.loadCsvData() # Create a list with the names of the selected objects: selectedObjects = [] # Loop through the selected objects and put their names into the list selectedObjects o = 0 while (o < selCount): selectedObjects.append(scribus.getSelectedObject(o)) o = o + 1 startingPage = scribus.currentPage() lastRow = len(csvData) if(self.__dataObject.getNumberOfLinesToMerge() != 'All'): lastRow = int(self.__dataObject.getNumberOfLinesToMerge()) lastRow = min(lastRow, len(csvData)) # This will prevent the script from trying to merge data from non-existing rows in the data file currentPage = scribus.currentPage() rowNumber = 0 insertPageBeforeThis = -1 while (rowNumber < lastRow): if(scribus.pageCount() > currentPage): insertPageBeforeThis = currentPage + 1 scribus.newPage(insertPageBeforeThis) # Inserts a page before the page given as an argument currentPage = currentPage + 1 for selectedObject in selectedObjects: # Loop through the names of all the selected objects scribus.gotoPage(startingPage) # Set the working page to the one we want to copy objects from scribus.copyObject(selectedObject) scribus.gotoPage(currentPage) scribus.pasteObject() # Paste the copied object on the new page scribus.docChanged(1) scribus.gotoPage(currentPage) # Make sure ware are on the current page before we call getAllObjects() newPageObejcts = scribus.getAllObjects() for pastedObject in newPageObejcts: # Loop through all the items on the current page objType = scribus.getObjectType(pastedObject) text = CONST.EMPTY if(objType == 'TextFrame'): text = scribus.getAllText(pastedObject) # This should have used getText but getText does not return the text values of just pasted objects text = self.replaceText(csvData[rowNumber], text) scribus.setText(text, pastedObject) if(objType == 'ImageFrame'): text = scribus.getImageFile(pastedObject) # self.info("Image text", text) # Todo: Find out if it is possible to replace text in the ImageFile property rowNumber = rowNumber + 1 scribus.setRedraw(1) scribus.docChanged(1) scribus.messageBox("Merge Completed", "Merge Completed", icon=scribus.ICON_INFORMATION, button1=scribus.BUTTON_OK)
def exportText(textfile): page = 1 pagenum = scribus.pageCount() T = [] content = [] while (page <= pagenum): scribus.gotoPage(page) d = scribus.getPageItems() strpage = str(page) T.append('Page ' + strpage + '\n\n') for item in d: if (item[1] == 4): contents = scribus.getAllText(item[0]) if (contents in content): contents = 'Duplication, perhaps linked-to frame' T.append(item[0] + ': ' + contents + '\n\n') content.append(contents) elif (item[1] == 2): imgname = scribus.getImageFile(item[0]) T.append(item[0] + ': ' + imgname + '\n') page += 1 T.append('\n') output_file = open(textfile, 'w') output_file.writelines(T) output_file.close() endmessage = textfile + ' was created' scribus.messageBox("Finished", endmessage, scribus.ICON_NONE, scribus.BUTTON_OK)
def exportText(root_folder): page = 1 pagenum = scribus.pageCount() T = [] content = [] while (page <= pagenum): scribus.gotoPage(page) d = scribus.getPageItems() page_folder = root_folder+"/p"+str(page) if not os.path.isdir(page_folder): os.mkdir(page_folder) for item in d: if (item[1] == 4): # the item is a text textfile = folder+"/p"+str(page)+"/"+item[0]+".txt" output_file = open(textfile,'w') output_file.writelines(scribus.getAllText(item[0])) output_file.close() page += 1 endmessage = "Text files successfully saved in "+root_folder scribus.messageBox("Finished", endmessage,icon=0,button1=1)
def evalTemplate(self): pos2 = 0 while True: textlen = scribus.getTextLength(self.textbox) if textlen == 0: return scribus.selectText(0, textlen, self.textbox) alltext = scribus.getAllText(self.textbox) # logger.debug("alltext: %s %s", type(alltext), alltext) pos1 = alltext.find("/template", pos2) logger.debug("pos /template=%d", pos1) if pos1 < 0: return pos2 = alltext.find("/endtemplate", pos1) if pos2 < 0: raise Exception("kein /endtemplate nach /template") pos2 += 12 # len("/endtemplate") lines = alltext[pos1:pos2].split('\r') logger.debug("lines:%s %s", type(lines), str(lines)) line0 = lines[0] lineN = lines[-1] # logger.debug("lineN: %s %s", type(lineN), lineN) if lineN != "/endtemplate": raise ValueError( "Die letzte Zeile des templates darf nur /endtemplate enthalten" ) words = line0.split() typ = words[1] if typ != "/tour" and typ != "/termin" and typ != "/toc": raise ValueError( "Zweites Wort nach /template muß /tour, /termin oder /toc sein" ) typ = typ[1:] if typ == "toc": continue sel = words[2] if not sel.startswith("/selektion="): raise ValueError( "Drittes Wort nach /template muß mit /selektion= beginnen") sel = sel[11:].lower() sels = self.tourselections if typ == "tour" else self.terminselections if not sel in sels: raise ValueError("Selektion " + sel + " nicht in " + typ + "selektion") sel = sels[sel] events = self.touren if typ == "tour" else self.termine self.insertPos = pos1 runs = self.makeRuns(pos1, pos2) logger.debug("runs:%s", str(runs)) # can now remove template scribus.selectText(pos1, pos2 - pos1, self.textbox) scribus.deleteText(self.textbox) pos2 = pos1 self.insertPos = pos1 self.evalEvents(sel, events, runs)
def main(argv): """This is a documentation string. Write a description of what your code does here. You should generally put documentation strings ("docstrings") on all your Python functions.""" ######################### # YOUR CODE GOES HERE # ######################### #copyPlayer("__player__","PLAYER 1") #copyPlayer("__player__","PLAYER 2") #copyPlayer("__player__","PLAYER 3") csv = scribus.fileDialog('Open input', 'CSV files (*.csv)') stuff = { 'NAME': 'Mike Hingley', 'ADDRESS': '22 Trinity Street, Cradley Heath, West Midlands', 'PHOTO': '128.jpg' } print(os.path.dirname(os.path.realpath(sys.argv[0]))) print os.getcwd() print(sys.path[0]) print(os.path.abspath('')) sourceName = "__player__" if scribus.objectExists(sourceName): scribus.selectObject(sourceName) scribus.unGroupObject() childObjectCount = scribus.selectionCount() for x in range(0, childObjectCount): element = scribus.getSelectedObject(x) if scribus.getObjectType(str(element)) == 'TextFrame': current = scribus.getAllText(element) if current in stuff: fontsize = scribus.getFontSize(element) font = scribus.getFont(element) scribus.setText(stuff[current], element) scribus.setFont(font) scribus.setFontSize(fontsize) if scribus.getObjectType(str(element)) == 'ImageFrame': current = scribus.getImageFile(element) currentName = os.path.basename(os.path.normpath(current)) print current print currentName if currentName in stuff: ExistingFolder = os.path.split(current) print ExistingFolder[0] newFile = os.path.join(ExistingFolder[0], stuff[currentName]) print newFile scribus.loadImage(newFile, element) print scribus.getObjectType(str(element)) print str(scribus.getSelectedObject(x)) scribus.groupObjects() print "name = " + scribus.getSelectedObject() scribus.setNewName("__player__", scribus.getSelectedObject())
def evalTocTemplate(self, firstPageNr): textlen = scribus.getTextLength(self.textbox) if textlen == 0: return scribus.selectText(0, textlen, self.textbox) alltext = scribus.getAllText(self.textbox) # logger.debug("alltext: %s %s", type(alltext), alltext) pos2 = 0 while True: pos1 = alltext.find("/template", pos2) logger.debug("pos /template=%d", pos1) if pos1 < 0: return pos2 = alltext.find("/endtemplate", pos1) if pos2 < 0: raise Exception("kein /endtemplate nach /template") pos2 += 12 # len("/endtemplate") lines = alltext[pos1:pos2].split('\r') logger.debug("lines:%s %s", type(lines), str(lines)) line0 = lines[0] lineN = lines[-1] # logger.debug("lineN: %s %s", type(lineN), lineN) if lineN != "/endtemplate": raise ValueError( "Die letzte Zeile des templates darf nur /endtemplate enthalten" ) words = line0.split() typ = words[1] if typ != "/tour" and typ != "/termin" and typ != "/toc": raise ValueError( "Zweites Wort nach /template muß /tour, /termin oder /toc sein" ) typ = typ[1:] if typ != "toc": continue self.insertPos = pos1 runs = self.makeRuns(pos1, pos2) logger.debug("runs:%s", str(runs)) # remember template self.toBeDelPosToc = (pos1, pos2, self.textbox) self.insertPos = pos2 self.evalTocEvents(runs, firstPageNr)
def makeRuns(self, pos1, pos2): runs = [] scribus.selectText(pos1, pos2 - pos1, self.textbox) txtAll = scribus.getAllText(self.textbox) scribus.selectText(pos1, 1, self.textbox) last_pstyle = scribus.getStyle(self.textbox) last_cstyle = scribus.getCharacterStyle(self.textbox) text = "" changed = False for c in range(pos1, pos2): scribus.selectText(c, 1, self.textbox) # does not work for text in overflown area, see https://bugs.scribus.net/view.php?id=15911 # char = scribus.getText(self.textbox) char = txtAll[c - pos1] pstyle = scribus.getStyle(self.textbox) if pstyle != last_pstyle: changed = True cstyle = scribus.getCharacterStyle(self.textbox) if cstyle != last_cstyle: changed = True # ff = scribus.getFontFeatures(self.textbox) # if ff != last_ff: # # ff mostly "", for Wingdins chars ="-clig,-liga" !?!? # logger.debug("fontfeature %s", ff) # last_ff = ff if changed: runs.append(ScrbRun(text, last_pstyle, last_cstyle)) last_pstyle = pstyle last_cstyle = cstyle text = "" changed = False text = text + char if text != "": runs.append(ScrbRun(text, last_pstyle, last_cstyle)) return runs
def processTemplate(xlat): if xlat is None: return logger.info(r'! process template') page = 1 pagenum = scribus.pageCount() while page <= pagenum: logger.info(r'.process page ' + str(page)) scribus.gotoPage(page) pitems = scribus.getPageItems() for item in [p for p in pitems if p[1] == 4]: logger.info(r'..process item: [%s] ', item) buf = scribus.getAllText(item[0]) logger.info(r'...cur text: [%s]', buf) phc = None # try to figure placeholder mbuf = re.search(r'[{]+(\w+)[}]+', buf) if mbuf is not None: # placeholder text phc = mbuf.group(1) Automator3.codes[item[0]] = phc else: # have we been here before? if item[0] in Automator3.codes: phc = Automator3.codes[item[0]] # ok. do we have a xlat for this? if phc is not None and phc in xlat: nstr = xlat[phc] else: nstr = buf try: scribus.replaceText(nstr, item[0]) logger.info('...new text: ' + str(nstr)) except scribus.ScribusException: logger.error('.. scribus setText failed') page += 1 logger.info('! done processing template')
def exportText(filename): file_content = [] content = [] for page in range(1, scribus.pageCount() + 1): scribus.gotoPage(page) file_content.append('Page ' + str(page) + '\n\n') for item in scribus.getPageItems(): if item[1] == 4: contents = scribus.getAllText(item[0]) if contents in content: contents = 'Duplication, perhaps linked-to frame' file_content.append(item[0] + ': ' + contents + '\n\n') content.append(contents) elif item[1] == 2: imgname = scribus.getImageFile(item[0]) file_content.append(item[0] + ': ' + imgname + '\n') file_content.append('\n') output_file = open(filename, 'w') output_file.writelines(file_content) output_file.close()
def rmEventIdMarkers(self): pagenum = scribus.pageCount() for page in range(1, pagenum + 1): scribus.gotoPage(page) pageitems = scribus.getPageItems() for item in pageitems: if item[1] != 4: continue tbox = item[0] # frameLinks nonempty only if starten called from same gui if self.frameLinks.get( tbox ) is not None: # i.e. if tbox is not the root of a link chain continue # TODO find out if tbox is a linked frame tlen = scribus.getTextLength(tbox) if tlen == 0: continue scribus.selectText(0, tlen, tbox) allText = scribus.getAllText( tbox) # getAllText returns text of complete link chain! z = 0 xl = [] while True: x = allText.find("_evtid_:", z) if x < 0: break y = allText.find(STX, x) evtId = allText[x + 8:y] z = allText.find(ETX, y) titel = allText[y + 1:z] xl.append((x, z + 1 - x)) for (x, l) in reversed(xl): # the reversed is important! scribus.selectText(x, l, tbox) scribus.deleteText(tbox) scribus.redrawAll()
style_name, *[int(color[i:i + 2], 16) for i in range(0, 6, 2)]) arguments['fillcolor'] = style_name # TODO: add other style elements (underline, italic, bold) # (bold and italic won't be easy) # TODO: add the parent_style to the API scribus.createCharStyle(style_name, **arguments) return style_name # TODO: read the text from the frame print('=====') code = scribus.getAllText() # TODO: read the item's attributes attribute = '' for a in scribus.getObjectAttributes(): if a['Name'] == 'syntax-highlight': attribute = a['Value'] print('>>>> ' + attribute) if attribute != '': try: from pygments.lexers import get_lexer_by_name lexer = get_lexer_by_name(attribute) except pygments_classNotFound: pass
scribus.ICON_WARNING, scribus.BUTTON_OK) sys.exit(2) textbox = scribus.getSelectedObject() pageitems = scribus.getPageItems() boxcount = 1 for item in pageitems: if (item[0] == textbox): if (item[1] != 4): scribus.messageBox('Scribus - Usage Error', "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK) sys.exit(2) contents = scribus.getTextLength(textbox) probably_url = scribus.getAllText(textbox) button = scribus.messageBox('url is', probably_url, scribus.ICON_NONE, scribus.BUTTON_OK, scribus.BUTTON_CANCEL) if button == scribus.BUTTON_CANCEL: sys.exit(2) r = requests.get(probably_url) scribus.setText(r.text, textbox) scribus.setRedraw(1) scribus.docChanged(1) # TODO: save in a new doc # TODO: Check for a valid url # TODO: make it possible to do all text boxes in a document # TODO: Format the text, make it possible to use basic markdown, basic wiki formatting scribus.messageBox("Finished", "That should do it!", scribus.ICON_NONE,
## contribution from jvr14115, https://github.com/berteh/ScribusGenerator/issues/116 ## run from within Scribus > Script > run Script import os import re import scribus Edoc = scribus.getDocName() Edoc = Edoc.replace('.sla', '') file_name = Edoc + 'Elements.csv' Edoc = Edoc.replace('Elements.csv', '') Edoc = re.search(r'(.*)/(.*)', Edoc).group(2) f = open(file_name, 'w+') f.write('Template,Element,ElementType') f.write('\n') objL = scribus.getAllObjects() for obj in objL: objT = scribus.getObjectType(obj) Evar = '' if objT == 'ImageFrame': Etype = 'image' Evar = scribus.getImageFile(obj) if objT == 'TextFrame': Etype = 'text' Evar = scribus.getAllText(obj) if '%VAR_' in Evar: Evar = re.sub('^[^%VAR_]*%VAR_', '', Evar) Evar = Evar[:-1] f.write(Edoc + ';"' + Evar + '";' + Etype + '\n') f.close
def shouldSetStyle (self): if self.first: return True else: return scribus.getAllText(self.name)[-1] == "\n"
if color: scribus.defineColorRGB(style_name, *[int(color[i:i+2], 16) for i in range(0, 6, 2)]); arguments['fillcolor'] = style_name # TODO: add other style elements (underline, italic, bold) # (bold and italic won't be easy) # TODO: add the parent_style to the API scribus.createCharStyle(style_name, **arguments) return style_name # TODO: read the text from the frame print('=====') code = scribus.getAllText() # TODO: read the item's attributes attribute = '' for a in scribus.getObjectAttributes(): if a['Name'] == 'syntax-highlight': attribute = a['Value'] print('>>>> '+attribute) if attribute != '': try: from pygments.lexers import get_lexer_by_name lexer = get_lexer_by_name(attribute) except pygments_classNotFound: pass
#!/usr/bin/env python import scribus from oblique_text import make_oblique_4 scribus.setText(make_oblique_4(scribus.getAllText()))
import scribus n = scribus.selectionCount() list = [] for i in range(0,n): list.append(scribus.getSelectedObject(i)) print(list) #deselectAll() for selected in list: size = len(scribus.getAllText(selected)) scribus.selectText(0, size , selected) scribus.setStyle("WASTE dialog", selected)
textbox = scribus.getSelectedObject() pageitems = scribus.getPageItems() boxcount = 1 for item in pageitems: if (item[0] == textbox): if (item[1] != 4): scribus.messageBox('Scribus - Usage Error', "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK) sys.exit(2) contents = scribus.getTextLength(textbox) while c <= (contents -1): if ((c + 1) > contents - 1): nextchar = ' ' else: scribus.selectText(c+1, 1, textbox) nextchar = scribus.getAllText(textbox) scribus.selectText(c, 1, textbox) char = scribus.getAllText(textbox) if (len(char) != 1): c += 1 continue if ((ord(char) == 34) and (c == 0)): scribus.deleteText(textbox) scribus.insertText(lead_double, c, textbox) elif (ord(char) == 34): if ((prevchar == '.') or (prevchar == ',') or (prevchar == '?') or (prevchar == '!')): scribus.deleteText(textbox) scribus.insertText(follow_double, c, textbox) elif ((ord(prevchar) == 39) and ((nextchar != ' ') and (nextchar != ',') and (nextchar != '.'))): scribus.deleteText(textbox) scribus.insertText(lead_double, c, textbox)
def parseParams(self): pagenum = scribus.pageCount() lines = [] for page in range(1, pagenum + 1): scribus.gotoPage(page) pageitems = scribus.getPageItems() for item in pageitems: if item[1] != 4: continue self.textbox = item[0] textlen = scribus.getTextLength(self.textbox) if textlen == 0: continue scribus.selectText(0, textlen, self.textbox) alltext = scribus.getAllText(self.textbox) pos1 = alltext.find("/parameter") if pos1 < 0: continue pos2 = alltext.find("/endparameter") if pos2 < 0: raise ValueError("kein /endparameter nach /parameter") pos2 += 13 # len("/endparameter") lines = alltext[pos1:pos2].split('\r')[1:-1] logger.debug("parsePar lines:%s %s", type(lines), str(lines)) self.toBeDelPosParam = (pos1, pos2, self.textbox) break if len(lines) != 0: break if len(lines) == 0: return self.includeSub = True lx = 0 selections = {} while lx < len(lines): line = lines[lx] words = line.split() if len(words) == 0: lx += 1 continue word0 = words[0].lower().replace(":", "") if len(words) > 1: if word0 == "linktyp": self.linkType = words[1].lower().capitalize() lx += 1 elif word0 == "ausgabedatei": self.ausgabedatei = words[1] lx += 1 else: raise ValueError("Unbekannter Parameter " + word0 + ", erwarte linktyp oder ausgabedatei") elif word0 not in [ "selektion", "terminselektion", "tourselektion" ]: raise ValueError( "Unbekannter Parameter " + word0 + ", erwarte selektion, terminselektion oder tourselektion") else: lx = self.parseSel(word0, lines, lx + 1, selections) selection = selections.get("selektion") self.gliederung = selection.get("gliederungen") self.includeSub = selection.get("mituntergliederungen") == "ja" self.start = selection.get("beginn") self.end = selection.get("ende") sels = selections.get("terminselektion") if sels is not None: for sel in sels.values(): self.terminselections[sel.get("name")] = sel for key in sel.keys(): if key != "name" and not isinstance(sel[key], list): sel[key] = [sel[key]] sels = selections.get("tourselektion") if sels is not None: for sel in sels.values(): self.tourselections[sel.get("name")] = sel for key in sel.keys(): if key != "name" and not isinstance(sel[key], list): sel[key] = [sel[key]]
if frame_n == 0: scribus.messageBox('Error:', 'No frame selected') sys.exit(1) elif frame_n > 1: scribus.messageBox('Error:', 'Please select one single frame') sys.exit(1) item = scribus.getSelectedObject(0) path_images = None filename_png = None path_png = None path_svg = None if (scribus.getObjectType(item) == 'TextFrame'): path = scribus.getAllText() if path != '': base_path = os.path.dirname(scribus.getDocName()) filename_png = os.path.join(base_path, path) elif (scribus.getObjectType(item) == 'ImageFrame'): filename_png = scribus.getImageFile() if path_png == '': filename_png = None if filename_png == None: scribus.messageBox( 'Error:', 'You need to select a text frame containing the path to the image or an image frame with an old version of the image' ) sys.exit(1)