def replaceText(text, code): if text is None or text is u'': logger.warn(".. empty content for elem [%s]", code) text = ' ' l = scribus.getTextLength(code) scribus.selectText(0, l - 1, code) scribus.deleteText(code) scribus.insertText(text, 0, code) l = scribus.getTextLength(code) scribus.selectText(l - 1, 1, code) scribus.deleteText(code)
def createPlaceTimePrice(box, string, font, style): startLength = scribus.getTextLength(box) scribus.insertText(string, startLength, box) endLength = scribus.getTextLength(box) - startLength if style != "": scribus.selectText(startLength, endLength, box) scribus.setStyle(style, box) if font != "": scribus.selectText(startLength, endLength, box) scribus.setFont(font, box) return endLength
def getColorsFromCsv(filename, idxPro): csvreader=csv.reader(file(filename)) csvcolors=[] for row in csvreader: if len(row)>1 and idxPro==1: name=row[0].strip() if len(row)>4 and name[0:7]=='couleur': c=int(row[1] )* 2.55 c=int(c) m=int(row[2] )* 2.55 m=int(m) y=int(row[3] )* 2.55 y=int(y) k=int(row[4] )* 2.55 k=int(k) if checkValue(c, m, y, k) ==False: scribus.messageBox("importerPros", "At least one CMYK value in your csv file is not correct \n(must be between 0 and 100)\nAborting script - nothing imported.", icon=scribus.ICON_WARNING) sys.exit() color=(name, c, m, y, k) csvcolors.append(color) elif name[0:3]=='txt': if scribus.objectExists(name): scribus.setText(row[1].replace("\\n","\n"), name) nbContent=scribus.getTextLength(name) scribus.selectText(0, nbContent, name) scribus.setStyle("style"+name[3:], name) else: scribus.messageBox("Objet non trouvé","Aucun objet correspondant au paramètre %s n'a été trouvé dans le document vierge"%name) readGlobalParameter(row) return csvcolors
def change_text(text, item): l = scribus.getTextLength(item) scribus.selectText(0, l, item) fs = scribus.getFontSize(item) f = scribus.getFont(item) scribus.insertText(text, 0, item) l2 = scribus.getTextLength(item) scribus.selectText(0, l2, item) scribus.setFontSize(fs, item) scribus.setFont(f, item) scribus.selectText(l2-l, l, item) scribus.deleteText(item) scribus.deselectAll()
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 insertTextWithStyle(txt,style,frame): start = scribus.getTextLength(frame) scribus.insertText(txt, -1, frame) scribus.selectText(start, len(txt), frame) try: scribus.setStyle(style, frame) except scribus.NotFoundError: scribus.createParagraphStyle(style) scribus.setStyle(style, frame) scribus.insertText("\n", -1, frame)
def insertTextWithStyle(txt, style, frame): start = scribus.getTextLength(frame) scribus.insertText(txt, -1, frame) scribus.selectText(start, len(txt), frame) try: scribus.setStyle(style, frame) except scribus.NotFoundError: scribus.createParagraphStyle(style) scribus.setStyle(style, frame) scribus.insertText("\n", -1, frame)
def evalTocEvents(self, runs, firstPageNr): toc = [] pagenum = scribus.pageCount() foundEvents = 0 for page in range(1, pagenum + 1): scribus.gotoPage(page) self.pageNr = firstPageNr + page - 1 pageitems = scribus.getPageItems() for item in pageitems: if item[1] != 4: continue tbox = item[0] tlen = scribus.getTextLength(tbox) logger.debug("tbox %s length %d", tbox, tlen) if tlen == 0: continue scribus.selectText(0, tlen, tbox) allText = scribus.getText( tbox) # getAllText returns text of complete link chain! z = 0 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] logger.debug("eventid %s, titel %s on page %d", evtId, titel, self.pageNr) event = self.gui.eventServer.getEventById(evtId, titel) toc.append((self.pageNr, event)) foundEvents += 1 logger.debug("sorting") toc.sort(key=lambda t: t[1].getDatumRaw()) # sortieren nach Datum for (pageNr, event) in toc: self.eventMsg = event.getTitel() + " vom " + event.getDatum()[0] logger.debug("event %s on page %d", self.eventMsg, self.pageNr) self.pageNr = pageNr for run in runs: self.run = run self.evalRun(event) self.insertText("\n", self.run) self.pageNr = None if foundEvents == 0: print("Noch keine Events gefunden") else: # remove template pos1, pos2, tbox = self.toBeDelPosToc scribus.selectText(pos1, pos2 - pos1, tbox) scribus.deleteText(tbox) scribus.redrawAll()
def characters(self, content): """place text, apply style""" start = scribus.getTextLength(self.name) go_ahead = self.shouldSetStyle() scribus.insertText (content, -1, self.name) scribus.selectText(start, len(content), self.name) if self.styles[-1] != None and go_ahead: try: scribus.setStyle(self.styles[-1], self.name) except scribus.NotFoundError: scribus.createParagraphStyle(self.styles[-1]) scribus.setStyle(self.styles[-1], self.name) if self.overrides[-1] != None: try: scribus.setFont(self.overrides[-1], self.name) except ValueError: pass self.first = False
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 simpleGradient(my_parameters): '''Applies a simple (character by character) gradient to a TextFrame object''' try: TextFrame_object = my_parameters[0] CMYKstart = my_parameters[1] CMYKend = my_parameters[2] object_length = scribus.getTextLength(TextFrame_object) for i in range(0, object_length): scribus.selectText(i, 1, TextFrame_object) color = CMYKgradientPoint(CMYKstart, CMYKend, object_length, i) try: getColor(str(color)) except: scribus.defineColor(str(color), color[0], color[1], color[2], color[3]) scribus.setTextColor(str(color), TextFrame_object) except: print error_message_gradient_simple scribus.messageBox(TITLE, error_message_gradient_simple, scribus.ICON_WARNING)
def slotDoIt(self): nfs = self.val.value() obj = scribus.getSelectedObject(0) t = scribus.getText(obj) scribus.deselectAll() t0 = scribus.getText(obj) fs = scribus.getFontSize(obj) tl = scribus.getTextLength(obj) idx = t0.find(t) + (len(t) / 2) base = fs #print t0 #print t #print "FS %i NFS %i IDX %i START %i" % (fs,nfs,idx,idx - int((nfs - fs) / 0.1)) for i in xrange(max(idx - int((nfs - fs) * 10), 0), idx): scribus.selectText(i, 1, obj) base += 0.1 scribus.setFontSize(base,obj) for i in xrange(idx, min(idx + int((nfs - fs) * 10), tl - 1)): scribus.selectText(i, 1, obj) base -= 0.1 scribus.setFontSize(base,obj) scribus.setRedraw(True) scribus.selectObject(obj)
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()
"There is no object selected.\nPlease select a text frame and try again.", scribus.ICON_WARNING, scribus.BUTTON_OK) sys.exit(2) if scribus.selectionCount() > 1: scribus.messageBox('Scribus - Usage Error', "You have more than one object selected.\nPlease select one text frame and try again.", 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) while c <= (contents -1): if ((c + 1) > contents - 1): nextchar = ' ' else: scribus.selectText(c+1, 1, textbox) nextchar = scribus.getText(textbox) scribus.selectText(c, 1, textbox) char = scribus.getText(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):
def generateContent(string, window): #generates all the elements/only one element start = 0 end = 0 if string == "all": #dont include the first line to make the data sort work [1:] #sort the the elements by date data = sorted(getCSVdata()[1:], key=lambda row: dateFun(str.strip(row[5])), reverse=True) end = len(data) print(str(end) + " " + str(start)) print("generating elements from all lines") window.destroy() elif RepresentsInt(string): start = int(string) - 1 #index shifting end = int(string) print("only generating line " + string) data = getCSVdata() window.destroy() else: print(string + " is not a valid value") print("exiting") window.destroy() sys.exit() if not scribus.haveDoc() > 0: #do we have a doc? scribus.messageBox("importcvs2table", "No opened document.\nPlease open one first.") sys.exit() userdim = scribus.getUnit() #get unit and change it to mm scribus.setUnit(scribus.UNIT_MILLIMETERS) lineWidth = 3.92 #aka 1.383mm, kp warum rowDate = "" for i in range(start, end): rowName = str.strip(data[i][0]) rowCategory = str.strip(data[i][1]) rowDescription = str.strip(data[i][2]) rowPrice = str.strip(data[i][3]) rowPlace = str.strip(data[i][4]) rowDate = str.strip(data[i][5]) rowTime = str.strip(data[i][6]) if rowName == "": #skip empty csv lines continue print("add element: " + rowName) #random values hpos = 120.0 vpos = 200.0 hposition = 120.0 vposition = 200.0 objectlist = [] #list for all boxes x = 0 #sets the progress #create the blue box print("create the blue line") blueBox = scribus.createLine(hposition + 1, vposition, hposition + 1, vposition + 5.863) scribus.setLineColor("Cyan", blueBox) scribus.setLineWidth(lineWidth, blueBox) objectlist.append(blueBox) scribus.progressSet(x) x = 1 #create the data character box #these are the width values for the numbers zero = 4.608 one = 2.839 two = 4.724 three = 4.393 four = 4.625 five = 4.261 six = 4.278 seven = 4.261 eight = 4.625 nine = 4.708 lenArray = [zero, one, two, three, four, five, six, seven, eight, nine] marginleft = 1.3 margintop = 0.519 #substract, cause the box is heigher that the blue line cellwidthright = 10.951 cellHeight = 8.282 hposition = hposition + marginleft + 1 textbox = scribus.createText(hposition, vposition - margintop, cellwidthright, cellHeight) scribus.setFont("Quicksand Regular", textbox) scribus.setFontSize(20.0, textbox) finalDate = "" rowDateLength = 0 #checks if the rowDate is from 01-09, in that case remove the zero if rowDate[0] == '0': finalDate = rowDate[1] rowDateLength = lenArray[int(rowDate[1])] else: finalDate = rowDate[:2] rowDateLength = lenArray[int(rowDate[0])] + lenArray[int( rowDate[1])] scribus.insertText(finalDate, 0, textbox) print("day: " + finalDate) objectlist.append(textbox) scribus.progressSet(x) x = 2 #create the month/day box print("create the box with the day and month") width = 19.447 height = 8.025 marginleft = rowDateLength #gain that from the calculations above, depends on the width of the rowDate characters monthBox = scribus.createText(hposition + marginleft + 0.7, vposition, width, height) scribus.setFont("Quicksand Regular", monthBox) scribus.setFontSize(8.5, monthBox) month = "" m = rowDate[3:5] if m == '01': month = "Januar" elif m == '02': month = "Februar" elif m == '03': month = "März" elif m == '04': month = "April" elif m == '05': month = "Mai" elif m == '06': month = "Juni" elif m == '07': month = "Juli" elif m == '08': month = "August" elif m == '09': month = "September" elif m == '10': month = "Oktober" elif m == '11': month = "November" elif m == '12': month = "Dezember" else: print("cant determine month!") day = datetime.date(int(rowDate[6:]), int(m), int(rowDate[:2])).weekday() dayName = "" if day == 0: dayName = "Montag" elif day == 1: dayName = "Dienstag" elif day == 2: dayName = "Mittwoch" elif day == 3: dayName = "Donnerstag" elif day == 4: dayName = "Freitag" elif day == 5: dayName = "Samstag" elif day == 6: dayName = "Sonntag" else: print("cant determine day!") text = month + "\n" + dayName scribus.setStyle("Kalender_neu_Monat und Tag", monthBox) scribus.insertText(text, 0, monthBox) print("month: " + month + " day: " + dayName) objectlist.append(monthBox) scribus.progressSet(x) x = 3 #create the main text box print("create the main text box") margintop = 5.5 hpos = hpos - 0.383 #i dont know why but scribus always places the element 0.383 right than it should be :/ mainTextBox = scribus.createText( hpos, vposition + margintop, 43.0, 45.0) #minus eins weil der blaue balken seinen kasten overflowed #insert category print("insert the category: " + rowCategory) scribus.insertText(rowCategory, 0, mainTextBox) endCategory = scribus.getTextLength(mainTextBox) scribus.selectText(0, endCategory, mainTextBox) scribus.setFontSize(10.5, mainTextBox) scribus.selectText(0, endCategory, mainTextBox) scribus.setStyle("Kalender_Eventname", mainTextBox) #insert main text print("insert the main text") scribus.insertText("\n" + rowDescription, endCategory, mainTextBox) endMainText = scribus.getTextLength(mainTextBox) - endCategory scribus.selectText(endCategory, endMainText, mainTextBox) scribus.setStyle("Kalender_Eventbeschreibung", mainTextBox) #get start length to color everything black and set font size startAll = scribus.getTextLength(mainTextBox) createPlaceTimePrice(mainTextBox, "\n| Ort: ", "", "Kalender_Eventname") #insert value for place createPlaceTimePrice(mainTextBox, rowPlace, "Heuristica Regular", "") #insert time letters createPlaceTimePrice(mainTextBox, " | Zeit: ", "Quicksand Regular", "") #insert time value createPlaceTimePrice(mainTextBox, rowTime, "Heuristica Regular", "") #insert price letters createPlaceTimePrice(mainTextBox, " | Eintritt: ", "Quicksand Regular", "") #insert price value createPlaceTimePrice(mainTextBox, rowPrice, "Heuristica Regular", "") #setFontSize and black color for the whole detail box endAll = scribus.getTextLength(mainTextBox) - startAll scribus.selectText(startAll, endAll, mainTextBox) scribus.setFontSize(8.5, mainTextBox) scribus.selectText(startAll, endAll, mainTextBox) scribus.setTextColor("Black", mainTextBox) objectlist.append(mainTextBox) scribus.progressSet(x) #do some generell stuff scribus.groupObjects(objectlist) scribus.progressReset() scribus.setUnit(userdim) # reset unit to previous value scribus.docChanged(True) scribus.statusMessage("Done") scribus.setRedraw(True) print("done") return 0
import sys try: import scribus except ImportError: print "This script only works from within Scribus" sys.exit(1) obj = scribus.getSelectedObject(0) sdir = 1 # options fs = 8 fsmax = 14 fsmin = 8 inc = 0.0005 ### tl = scribus.getTextLength() for c in range(tl - 1): scribus.selectText(c, 1, obj) if(sdir == 1): fs += inc if(fs > fsmax): sdir = 0 else: fs -= inc if(fs < fsmin): sdir = 1 scribus.setFontSize(fs,obj)
def importSocietes(filename, fileCat, iPro): arrLines=[]#liste de lignes du fichier csv, chaque ligne est une liste de champs mapCol={}#table de correspondance entre les champs à importer et les numéros de colonne du fichier csv mapCat={}#table de correspondance entre numéro de catégorie et nom de catégorie nbCat=readSocietes(filename, fileCat, mapCat, arrLines, mapCol) (nbChg, nbPro)=(0,0) numPro=1 while scribus.getTextLength("txtPros%d" % numPro)>0 and numPro<=NB_TXT: numPro+=1 if iPro==1 and scribus.objectExists("txtBureauxChange"): scribus.deleteText("txtBureauxChange") scribus.progressTotal(len(arrLines)) strPro="txtPros%d"%numPro scribus.statusMessage("Remplissage du cadre de texte %s..."%strPro) bFirstPro=True strCat="#" for record in arrLines:#Pour chaque pro # log("nbPro=%d\n"%nbPro) if strCat != record[mapCol["cat"]]:#nouvelle categorie strCat=record[mapCol["cat"]] bNewCat=True else: bNewCat=False nbPro+=1 if nbPro<iPro:#déjà importé à l'exécution précédente continue try: scribus.progressSet(nbPro) if record[mapCol["chg"]]=="True" and scribus.objectExists("txtBureauxChange"): try: nbCarBureau=scribus.getTextLength("txtBureauxChange") appendText(u"● "+toUnicode(record[mapCol["nom"]])+"\n","styleChangeTitre","txtBureauxChange") appendText(toUnicode(record[mapCol["adr"]].replace("\\n"," - "))+"\n","styleChangeAdresse","txtBureauxChange") appendText(record[mapCol["post"]]+" "+toUnicode(record[mapCol["ville"]].upper()+"\n"),"styleChangeAdresse","txtBureauxChange") nbChg+=1 except Exception as ex: scribus.messageBox( "Erreur","Une erreur est survenue sur ce bureau de change: \n%s\n\n%s" %(record, str(ex))) sys.exit() else : nbCarBureau=0 nbCar=scribus.getTextLength(strPro) if bNewCat or bFirstPro: if bFirstPro and not bNewCat: appendText(toUnicode(strCat+" (suite)")+"\n","styleProCatSuite",strPro) else: appendText(toUnicode(strCat)+"\n","styleProCat",strPro) bFirstPro=False appendText(u"● "+toUnicode(record[mapCol["nom"]])+"\n","styleProTitre",strPro) if record[mapCol["chg"]]=="True" : appendText(u"\n","styleProBureau",strPro) #icone du bureau de change en police FontAwesome appendText(processDesc(toUnicode(record[mapCol["desc"]]))+"\n","styleProDesc",strPro) if bLivret: strAdr=toUnicode(record[mapCol["adr"]].replace("\\n"," - "))+" - " + toUnicode(record[mapCol["post"]])+" " strAdr+=processDesc(toUnicode(record[mapCol["ville"]].upper())) if record[mapCol["tel"]].strip(): strAdr+=" ("+toUnicode(record[mapCol["tel"]].strip().replace(" ","\xC2\xA0"))+")\n" #numéro de téléphone insécable else: strAdr+="\n" appendText(strAdr, "styleProAdresse", strPro) else: appendText(toUnicode(record[mapCol["adr"]].replace("\\n"," - "))+"\n","styleProAdresse",strPro) appendText(toUnicode(record[mapCol["post"]])+" "+processDesc(toUnicode(record[mapCol["ville"]]).upper())+"\n","styleProAdresse",strPro) if record[mapCol["tel"]].strip(): appendText(processTelephone(record[mapCol["tel"]])+"\n","styleProAdresse",strPro) if scribus.textOverflows(strPro, nolinks=1): #effacement du paragraphe de pro tronqué et du bureau de change en double scribus.selectText(nbCar, scribus.getTextLength(strPro)-nbCar, strPro) scribus.deleteText(strPro) if nbCarBureau: scribus.selectText(nbCarBureau, scribus.getTextLength("txtBureauxChange")-nbCarBureau, "txtBureauxChange") scribus.deleteText("txtBureauxChange") #log("Cadre rempli : le cadre de texte %s est plein à la ligne %d\n" % (strPro, nbPro)) break except Exception as exc: scribus.messageBox( "Erreur","Une erreur est survenue sur ce professionnel: \n%s\n\n%s" %(record, str(exc))) sys.exit() return (nbChg, nbPro, nbCat)
if not scribus.haveDoc(): scribus.messageBox('Usage Error', 'You need a Document open') sys.exit(2) if scribus.selectionCount() == 0: scribus.messageBox('Usage Error', 'You need to select a frame') sys.exit(2) item = scribus.getSelectedObject() if (scribus.getObjectType(item) != 'TextFrame'): scribus.messageBox('Usage Error', 'You need to select a text frame') sys.exit(2) print(scribus.getTextLength(item)) if scribus.getTextLength(item) > 0: scribus.messageBox('Usage Error', 'The text frame should be empty') sys.exit(2) answer = scribus.valueDialog('Numbered lines', 'Start number, step', '1,1') start, step = answer.split(',') start = int(start) step = int(step) i = start print(scribus.textOverflows(item)) while scribus.textOverflows(item) == 0: if i == start or i % step == 0: scribus.insertText(str(i) + "\n", -1, item) else:
# check opened document if not scribus.haveDoc(): scribus.messageBox('Scribus - Script Error', "No document open", scribus.ICON_WARNING, scribus.BUTTON_OK) sys.exit(1) scribus.setRedraw(False) selectionCount = scribus.selectionCount() # str('Selected: ' + str(selectionCount)) selected = [] # remember all selected objects for index in range(0, selectionCount): # str(index) selectedObject = scribus.getSelectedObject(index) # str(selectedObject) selected.append(selectedObject) scribus.deselectAll() # change style for each selected object for obj in selected: # str(obj) scribus.selectObject(obj) scribus.selectText(0, scribus.getTextLength(obj), obj) scribus.setStyle(style, obj) scribus.deselectAll() scribus.setRedraw(True) scribus.docChanged(True)
textbox = scribus.getSelectedObject() boxcount = 1 for item in scribus.getPageItems(): if (item[0] == textbox): if (item[1] != 4): if (lang == 'fr'): scribus.messageBox('Scribus - Erreur', "L'objet sélectionné n'est pas un cadre de texte.\nVeuillez sélectionner un cadre de texte, puis recommencez.", scribus.ICON_WARNING, scribus.BUTTON_OK) else: scribus.messageBox('Scribus - Usage Error', "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK) sys.exit(2) textlen = scribus.getTextLength(textbox) c = 0 nbchange = 0 lastchange = 'close' prevchar = '' while c <= (textlen -1): # si on est à la fin, il faut tricher pour le dernier caractère if ((c + 1) > textlen - 1): alafin = 1 nextchar = ' ' else: alafin = 0 scribus.selectText(c+1, 1, textbox) nextchar = scribus.getText(textbox)
for item in scribus.getPageItems(): if (item[0] == textbox): if (item[1] != 4): if (lang == 'fr'): scribus.messageBox( 'Scribus - Erreur', "L'objet sélectionné n'est pas un cadre de texte.\nVeuillez sélectionner un cadre de texte, puis recommencez.", scribus.ICON_WARNING, scribus.BUTTON_OK) else: scribus.messageBox('Scribus - Usage Error', "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK) sys.exit(2) textlen = scribus.getTextLength(textbox) c = 0 nbchange = 0 lastchange = 'close' prevchar = ' ' while c <= (textlen - 1): # si on est à la fin, il faut tricher pour le dernier caractère if ((c + 1) > textlen - 1): alafin = 1 nextchar = ' ' else: alafin = 0 scribus.selectText(c + 1, 1, textbox) nextchar = scribus.getText(textbox)
item = scribus.getSelectedObject(i) selectedFrame.append(item) if scribus.getObjectType(item) == "TextFrame": textFrame.append(item) if scribus.getObjectType(item) == "ImageFrame": imageFrame.append(item[0]) # print textFrame # print imageFrame scribus.deselectAll() chars = [] for item in textFrame: scribus.deselectAll() scribus.selectObject(item) n = scribus.getTextLength() for i in range(n): scribus.selectText(i, 1) char = scribus.getText() if (char not in charsIgnore and len(char) > 0): chars.append(char.lower()) random.shuffle(chars) for item in textFrame: scribus.messagebarText("Processing text frame " + item) scribus.redrawAll() print item scribus.deselectAll() scribus.selectObject(item) n = scribus.getTextLength()
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]]
warnresult = scribus.valueDialog( 'Warning!', 'This script is going to irreveribly alter the text in your document.\nChange this default value to abort', 'Ok!') if (warnresult != 'Ok!'): sys.exit(2) pageitems = scribus.getPageItems() for item in pageitems: if (item[1] == 4): c = 0 textbox = item[0] scribus.selectObject(textbox) contents = scribus.getTextLength(textbox) while 1: if ((c == contents) or (c > contents)): break if ((c + 1) > contents - 1): nextchar = ' ' else: scribus.selectText(c + 1, 1, textbox) nextchar = scribus.getText(textbox) scribus.selectText(c, 1, textbox) char = scribus.getText(textbox) if (len(char) != 1): c += 1 continue alpha = random.randint(1, 26) letter = chr(alpha + 96)
except ImportError: print("This script only works from within Scribus") sys.exit(1) # check that the selection is one text frame and get that frame frame_n = scribus.selectionCount() if frame_n == 0 : scribus.messageBox('Error:', 'No frame selected'); sys.exit(1) elif frame_n > 1 : scribus.messageBox('Error:', 'You may select only one frame'); sys.exit(1) frame = scribus.getSelectedObject(0) try: char_n = scribus.getTextLength(frame) except scribus.WrongFrameTypeError: scribus.messageBox('Error:', 'You may only adjust text frames'); sys.exit(1) if char_n == 0 : scribus.messageBox('Error:', 'You can\'t adjust an empty frame'); sys.exit(1) if (scribus.textOverflows(frame) == 1) : scribus.messageBox('Error:', 'You can\' center a text which is overflowing'); sys.exit(1) # get some page and frame measure (x, y) = scribus.getPosition(frame)