Example #1
0
def error_msg(text):
    sc.messageBox(
        'Swap images', 
        f"Excact two image frames must be selected.\n{text}", 
        sc.ICON_CRITICAL
    )
    sys.exit(1)
Example #2
0
def getColorsFromCsv(filename):
    """get colors from csv file and return a list with name and cmyk 255 values"""
    csvreader = csv.reader(file(filename))

    csvcolors = []
    i = 0
    for row in csvreader:
        name = row[0]
        name = name.strip()
        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(
                "csv2color",
                "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()
        else:
            pass
        color = (name, c, m, y, k)
        csvcolors.append(color)
        i = i + 1
    return csvcolors
def main(argv):
    """A simple scripts to set baseline grid and matching guides."""

    CurrentUnit = scribus.getUnit()

    scribus.setUnit(0)
    H_Guides = []

    GuideHeight = float(
        scribus.valueDialog('Set BaseLine Grid & Guides',
                            'Enter value for Grid and Guide Height (pt).',
                            '14.40'))
    GuideOffset = float(
        scribus.valueDialog('Set Grid & Guide Offsets',
                            'Enter value for Grid and Guide Offset (pt).',
                            '0.0'))

    PageWidth, PageHeight = scribus.getPageSize()

    NumLoops = math.floor(1 + (PageHeight - GuideOffset) / GuideHeight)

    for i in range(int(NumLoops)):
        if i > 0:
            H_Guides.append(GuideOffset + i * GuideHeight)

    scribus.setBaseLine(GuideHeight, GuideOffset)
    scribus.setHGuides(scribus.getHGuides() + H_Guides)

    scribus.setUnit(CurrentUnit)

    scribus.messageBox(
        'Script',
        '<h3>Script by ugajin</h3><p>Thanks a bunch for using setBaselineGuides and Scribus!</p><p>[email protected]</p>',
        scribus.ICON_INFORMATION, scribus.BUTTON_OK, scribus.BUTTON_CANCEL)
def getColorsFromDoc():
    """returns a list ("name", c,y,m,k)
    get all the colors of that doc. """
    #get a list of al the colornames
    scribus.statusMessage("Reading Colors...")

    try:
        colorlist = scribus.getColorNames()
        scribus.progressTotal(len(colorlist))
        i = 0
        colordata = []
        for color in colorlist:
            colorvalues = scribus.getColor(color)
            c = int(colorvalues[0] / 2.55)  #convert values from 0-255 to 0-100
            m = int(colorvalues[1] / 2.55)
            y = int(colorvalues[2] / 2.55)
            k = int(colorvalues[3] / 2.55)
            name = color.strip()  #eliminate leading and tailing whitespace
            cd = [name, c, m, y, k]
            colordata.append(cd)
            i = i + 1
            scribus.progressSet(i)

        return colordata
    except:
        scribus.messageBox("color2csv",
                           "Can not retrieve colors - There is no Document",
                           icon=scribus.ICON_WARNING)
        sys.exit()
Example #5
0
def main(argv):
    """just invokes createChart() and displays a message after the chart is finished."""
    createChart()
    scribus.messageBox(
        "ColorChart Script by Sebastian Stetter",
        "Your chart has been created, but not saved, yet!\nThanks for using ColorChart and Scribus!"
    )
Example #6
0
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)
Example #7
0
def main(argv):
    """Main method - here we check if we have a doc - else we open one. we get all the colors and write them to a csv file."""
    if scribus.haveDoc() > 0:  #DOC OPEN
    #get colors, get filename, write stuff
        cols = getColorsFromDoc()
        filename = scribus.fileDialog("color2csv: Save csv color file", defaultname="colors.csv",  issave=True ,  haspreview=False)
        
        #@TODO: optimize path checking
        if filename !="":
            if os.path.exists(filename): #make sure we don't accidentally overwrite existing files
                answer= scribus.messageBox("color2csv", "File already exists! \n do you want to overwrite it?",  icon=scribus.ICON_WARNING,  button1=scribus.BUTTON_YES,  button2=scribus.BUTTON_ABORT)
                if answer == scribus.BUTTON_YES:
                    writeColorCsvFile(filename,  cols)
                else:
                    sys.exit()
            else:
                writeColorCsvFile(filename,  cols)
        else:
            sys.exit()
    else: # NO DOC OPEN - open one!
        scribusfile = scribus.fileDialog("color2csv: Open scribus file",  "Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)")
        if scribusfile !="":
            try:
                scribus.openDoc(scribusfile)
            except:
                scribus.messageBox("color2csv", "Could not open file!")
                sys.exit()
            #get colors, get filename, write stuff
            cols = getColorsFromDoc()
            filename = scribus.fileDialog("color2csv: Save csv color file", defaultname="colors.csv",  issave=True )
            writeColorCsvFile(filename,  cols)
        else:
            sys.exit()
    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 syncPageNumbers(self):
        scribus.messageBox("Debut", "Apply page numbers", icon=0, button1=1)
        i = 0
        totalpages = 1
        # parses the book file; for each book document
        for element in self.root.iter("file"):
            files = element.text
            thing = etree.parse(files)
            # scribus.messageBox("Debut",str(files),icon=0,button1=1)

            rawstr = r"""Start=".+" R"""
            matchstr = etree.tostring(thing)
            compile_obj = re.compile(rawstr)
            textpage = 'Start="' + str(totalpages) + '" R'
            newstr = compile_obj.subn(str(textpage), etree.tostring(thing))

            # Open file in Scribus to get the page quantity for each file through scribus own method
            doc = scribus.openDoc(files)
            pageqty = scribus.pageCount()
            totalpages += pageqty  # sets the amount of page from the beginning of the first file
            scribus.closeDoc()
            # scribus.messageBox("Debut","begins at "+str(newstr[0]),icon=0,button1=1)

            FILE = open(files, "w")
            FILE.write(newstr[0])
            FILE.close()
Example #10
0
def main():
   docfile = scribus.fileDialog("Find Guidebook Config File", "*.gbk", DOCFILE, haspreview=True, issave=False, isdir=False)
   if len(docfile) != 0:
      if not os.path.exists(docfile):
         scribus.messageBox("Bwaahaha","File does not exist")
      else:
         create_guide(fetch.GuidebookParser(docfile))
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 main(argv):
    """A simple scripts to set baseline grid and matching guides."""

    CurrentUnit = scribus.getUnit() 
    
    scribus.setUnit(0) 
    H_Guides = [] 
    
    GuideHeight = float(scribus.valueDialog('Set BaseLine Grid & Guides', 'Enter value for Grid and Guide Height (pt).', '14.40') )
    GuideOffset = float(scribus.valueDialog('Set Grid & Guide Offsets', 'Enter value for Grid and Guide Offset (pt).', '0.0') )
    
    PageWidth, PageHeight = scribus.getPageSize() 
    
    NumLoops = math.floor(1 + (PageHeight - GuideOffset) / GuideHeight)
    
    for i in range(int(NumLoops)):
    	if i > 0:
    		H_Guides.append(GuideOffset + i * GuideHeight)
    
    scribus.setBaseLine(GuideHeight, GuideOffset)
    scribus.setHGuides(scribus.getHGuides() + H_Guides)
    
    scribus.setUnit(CurrentUnit)
    
    scribus.messageBox('Script', '<h3>Script by ugajin</h3><p>Thanks a bunch for using setBaselineGuides and Scribus!</p><p>[email protected]</p>', scribus.ICON_INFORMATION, scribus.BUTTON_OK, scribus.BUTTON_CANCEL)
Example #13
0
def main(argv):
    """just invokes createChart() and displays a message after the chart is finished."""
    createChart()
    scribus.messageBox(
        "ColorChart Script by Sebastian Stetter",
        "Your chart has been created, but not saved, yet!\nThanks for using ColorChart and Scribus!",
    )
Example #14
0
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)
Example #15
0
def main():
    global timer
    timer = qt.QTimer()
    timer.connect(timer, qt.SIGNAL("timeout()"), msg)
    scribus.messageBox("Scribus - Python Timer",
                       "About to start a 5 second timer", scribus.BUTTON_OK)
    timer.start(5 * 1000, True)
Example #16
0
def getColorsFromCsv(filename):
    """get colors from csv file and return a list with name and cmyk 255 values"""
    csvreader=csv.reader(file(filename))

    csvcolors=[]
    i=0
    for row in csvreader:
        name=row[0]
        name=name.strip()
        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("csv2color", "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()
        else:
            pass
        color=(name, c, m, y, k)
        csvcolors.append(color)
        i=i+1
    return csvcolors
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
Example #18
0
def getColorsFromDoc():
    """returns a list ("name", c,y,m,k)
    get all the colors of that doc. """
    #get a list of al the colornames
    scribus.statusMessage("Reading Colors...")

    try:
        colorlist = scribus.getColorNames()
        scribus.progressTotal(len(colorlist))
        i=0
        colordata=[]
        for color in colorlist:
            colorvalues=scribus.getColor(color)
            c=int(colorvalues[0]/2.55) #convert values from 0-255 to 0-100
            m=int(colorvalues[1]/2.55)
            y=int(colorvalues[2]/2.55)
            k=int(colorvalues[3]/2.55)
            name=color.strip() #eliminate leading and tailing whitespace
            cd = [name,c ,m,y,k] 
            colordata.append(cd)
            i=i+1
            scribus.progressSet(i)
        
        return colordata
    except:
        scribus.messageBox("color2csv", "Can not retrieve colors - There is no Document", icon=scribus.ICON_WARNING)
        sys.exit()
Example #19
0
def main():
    global timer
    timer = qt.QTimer()
    timer.connect(timer, qt.SIGNAL("timeout()"), msg)
    scribus.messageBox("Scribus - Python Timer",
                       "About to start a 5 second timer",
                       scribus.BUTTON_OK)
    timer.start(5*1000, True)
Example #20
0
def applyGradient(gradient_function, gradient_parameters):
    '''Run the given gradient function with the given parameters.'''
    try:
        gradient_function(gradient_parameters)
    except:
        print error_message_apply_gradient
        scribus.messageBox(TITLE, error_message_apply_gradient,
                           scribus.ICON_WARNING)
 def __init__(self):
     # scribus.messageBox("Debut",'Init',icon=0,button1=1)
     # loads the file
     try:
         # scribus.messageBox("Debut","try OK : fichier charge dans Books",icon=0,button1=1)
         self.outputfile = scribus.fileDialog("Choose book file", filter="Book Files (*.sla.bk);;All Files (*)")
         # self.books = etree.parse("/home/cedric/.scribus/plugins/bookfiles/guideapi.sla.bk")
         self.books = etree.parse(self.outputfile)
     except Exception, e:
         scribus.messageBox("Debut", e, icon=0, button1=1)
Example #22
0
def gradientPoint(start, stop, steps, currentStep):
    '''return the value of a point at step currentStep/steps
    on a gradient between start and stop.'''
    try:
        return start + currentStep * (stop - start) / (steps - 1.0)
    except:
        print error_message_gradientpoint
        scribus.messageBox(TITLE, error_message_gradientpoint,
                           scribus.ICON_WARNING)
        return 0
Example #23
0
def sequentialTextFrameSelection(selection, CMYKstart, CMYKend,
                                 gradient_function):
    '''Run the given function sequentially on each element of the selection list argument.'''
    try:
        for TextFrame_object in selection:
            applyGradient(gradient_function,
                          (TextFrame_object, CMYKstart, CMYKend))
    except:
        print error_message_sequential_selection
        scribus.messageBox(TITLE, error_message_sequential_selection,
                           scribus.ICON_WARNING)
def main():
   """Formats xml file using Scribus template"""
   try:
       xml_file = getFile("XML File", 'XML (*.xml)', "", False)
       template = getFile("Scribus template", "Scribus document (*.sla)", "", False)
       document = getFile("Save document", "Alles (*.*)", xml_file.replace(".xml", ".sla"), True)
       format (xml_file, template, document)
   except UserCanceled:
       pass
   except xml.sax.SAXParseException:
       scribus.messageBox("XML Error", "XML Error: please check your document")
Example #25
0
def getColors():
    '''Get the stop and start color from Scribus environment.
    (This implies that you must define two colours names start and stop prior to launch this.'''
    start = None
    stop = None
    try:
        return scribus.getColor('start'), scribus.getColor('stop')
    except:
        print error_message_colours_undefined
        scribus.messageBox(TITLE, error_message_colours_undefined,
                           scribus.ICON_WARNING)
        return None, None
Example #26
0
def getPosition():
    if scribus.selectionCount() == 1:
        areaname = scribus.getSelectedObject()
        position= scribus.getPosition(areaname)
        vpos = position[1]
        hpos = position[0]
        scribus.deleteObject(areaname)
        return vpos, hpos
        
    else: 
        scribus.messageBox("csv2table", "please select ONE Object to mark the drawing area for the table")
        sys.exit()
Example #27
0
def main():
    docfile = scribus.fileDialog("Find Guidebook Config File",
                                 "*.gbk",
                                 DOCFILE,
                                 haspreview=True,
                                 issave=False,
                                 isdir=False)
    if len(docfile) != 0:
        if not os.path.exists(docfile):
            scribus.messageBox("Bwaahaha", "File does not exist")
        else:
            create_guide(fetch.GuidebookParser(docfile))
Example #28
0
def getPosition():
    if scribus.selectionCount() == 1:
        areaname = scribus.getSelectedObject()
        position = scribus.getPosition(areaname)
        vpos = position[1]
        hpos = position[0]
        scribus.deleteObject(areaname)
        return vpos, hpos

    else:
        scribus.messageBox("csv2table", "please select ONE Object to mark the drawing area for the table")
        sys.exit()
Example #29
0
    def __init__(self):
        if not scribus.haveDoc():
            scribus.messageBox('Scribus - Script Error', "No document open", scribus.ICON_WARNING, scribus.BUTTON_OK)
            sys.exit(1)

        if scribus.selectionCount() == 0:
            scribus.messageBox('Scribus - Script Error',
                               "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 - Script 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)

        self.textbox = scribus.getSelectedObject()
        ftype = scribus.getObjectType(self.textbox)

        if ftype != "TextFrame":
            scribus.messageBox('Scribus - Script Error', "This is not a textframe. Try again.", scribus.ICON_WARNING,
                               scribus.BUTTON_OK)
            sys.exit(2)

        scribus.deleteText(self.textbox)
        self.insertPos = 0
        self.lastPStyle = ""
        self.insertText('Radtouren\n', 'Radtouren_titel')
Example #30
0
def writeColorCsvFile(filename, colorlist):
    """writes all the colors to a csv file"""
    scribus.statusMessage("Writing colors to csv file...")
    scribus.progressTotal(len(colorlist))
    i=0
    try:
        csvwriter=csv.writer(file(filename, "w"), quoting=csv.QUOTE_NONNUMERIC)
        for line in colorlist:
            csvwriter.writerow(line)
            i=i+1
            scribus.progressSet(i)
    except:
        scribus.messageBox("color2csv", "Could not write file!", icon=scribus.ICON_WARNING)
        sys.exit()
def readSocietes(filename, fileCat, mapCat, arrLines, mapCol):
    bHeader=True
    nbCat=0
    with open(fileCat,'rb') as fCsv:#Lecture du fichier CSV des catégories
        reader=csv.reader(fCsv)
        for line in reader:
            if bHeader:
                bHeader=False
            elif len(line)>0:
                # mapCat[int(line[1])]=line[0]
                nbCat+=1
    
    bHeader=True
    iLig=0
    with open(filename,'rb') as fCsv:#Lecture du fichier CSV des pros
        reader=csv.reader(fCsv)
        for line in reader:
            iLig+=1
            if bHeader:
                bHeader=False
                iCol=0
                for colName in line:#table de correspondance des colonnes du fichier des pros
                    if "name" == colName.lower(): mapCol["nom"]=iCol
                    elif "street" == colName.lower(): mapCol["adr"]=iCol
                    elif "zip" in colName.lower(): mapCol["post"]=iCol
                    elif "city" in colName.lower(): mapCol["ville"]=iCol
                    elif "email" in colName.lower(): mapCol["mail"]=iCol
                    elif "phone_pro" in colName.lower(): mapCol["tel"]=iCol
                    elif "industry_id/name" == colName.lower(): mapCol["cat"]=iCol
                    elif "detailed_activity" in colName.lower(): mapCol["desc"]=iCol
                    elif "currency_exchange" in colName.lower(): mapCol["chg"]=iCol
                    elif "latitude" in colName.lower(): mapCol["lat"]=iCol
                    elif "longitude" in colName.lower(): mapCol["lng"]=iCol
                    iCol+=1

            elif len(line)>0 and estSelectionnee(line, mapCol, iLig):
                arrLines.append(line)
                try: 
                    strCat=line[mapCol["cat"]]
                    # i=int(strCat)
                    # if not i in mapCat:     
                    #     scribus.messageBox("Erreur","le domaine de la ligne %d n'est pas dans la liste des catégories (%s)"%(iLig, line))
                        
                except:
                    log(("domaine incorrect ligne %d : %s\n")%(iLig, line)) 
                    scribus.messageBox( "Erreur","le domaine de la ligne %d est incorrect (%s):\n%s" %(iLig, strCat, line))
                    sys.exit()

    arrLines.sort(key=lambda line: (line[mapCol["cat"]], line[mapCol["nom"]])) #classement par nom de categorie puis nom
    return nbCat
Example #32
0
def getCSVdata():
    """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
    csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
    if csvfile != "":
        try:
            reader = csv.reader(file(csvfile))
            datalist = []
            for row in reader:
                rowlist = []
                for col in row:
                    rowlist.append(col)
                datalist.append(rowlist)
            return datalist
        except Exception, e:
            scribus.messageBox("csv2table", "Could not open file %s" % e)
Example #33
0
def getCSVdata():
    """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
    csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
    if csvfile != "":
        try:
            reader = csv.reader(file(csvfile))
            datalist = []
            for row in reader:
                rowlist = []
                for col in row:
                    rowlist.append(col)
                datalist.append(rowlist)
            return datalist
        except Exception, e:
            scribus.messageBox("csv2table", "Could not open file %s" % e)
Example #34
0
def main():
    config = prepare_config(get_config())
    new_images = get_images(config['image_dir'], config['images'])
    image_frames = get_sff_image_frames_details(0, empty_only=True)

    if len(image_frames) > 0:
        if len(new_images) < len(image_frames):
            max_imports = len(new_images)
        else:
            max_imports = len(image_frames)

        import_text = [
            'Found {} empty image frames on the current page.'.format(
                len(image_frames)), 'Following Images will be imported:'
        ]
        import_text.extend(new_images[:max_imports])
        import_text.extend(
            ['', 'Click "Retry" to get further configuation options.'])

        answer = sc.messageBox('Image import',
                               '\n'.join(import_text),
                               button1=sc.BUTTON_OK | sc.BUTTON_DEFAULT,
                               button2=sc.BUTTON_RETRY,
                               button3=sc.BUTTON_ABORT | sc.BUTTON_ESCAPE)

        if answer == sc.BUTTON_OK:
            stored_images = store_images(new_images[:max_imports])
            image_frame_names = []
            for idx in image_frames:
                image_frame_names.append(image_frames[idx].name)
                logging.debug("image frame: {}".format(image_frames[idx].name))
            fill_frames(image_frame_names, stored_images)
            config['images'].extend(stored_images)
            write_config(config)
        elif answer == sc.BUTTON_ABORT:
            sys.exit(0)
        elif answer == sc.Retry:
            print("Sorry not implemented jet :-(")
            sys.exit(0)

    else:
        sc.messageBox('Script failed',
                      "Current page, doesn't contain empty image frames.",
                      sc.ICON_CRITICAL)
        sys.exit(1)

    sc.docChanged(1)
    sc.setRedraw(True)
def getCSVdata():
    """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
    #csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
    csvfile = "/home/toast/diskstation/intern/Publikationen/Info-Tafeln/Rosenlehrpfad/data.csv"
    if csvfile != "":
        try:
            reader = csv.reader(file(csvfile))
            datalist=[]
            for row in reader:
                rowlist=[]
                for col in row:
                    rowlist.append(col)
                datalist.append(rowlist)
            return datalist
        except Exception,  e:
            scribus.messageBox("csv2table", "Could not open file %s"%e)
def main(argv):
    """Main method - here we check if we have a doc - else we open one. we get all the colors and write them to a csv file."""
    if scribus.haveDoc() > 0:  #DOC OPEN
        #get colors, get filename, write stuff
        cols = getColorsFromDoc()
        filename = scribus.fileDialog("color2csv: Save csv color file",
                                      defaultname="colors.csv",
                                      issave=True,
                                      haspreview=False)

        #@TODO: optimize path checking
        if filename != "":
            if os.path.exists(
                    filename
            ):  #make sure we don't accidentally overwrite existing files
                answer = scribus.messageBox(
                    "color2csv",
                    "File already exists! \n do you want to overwrite it?",
                    icon=scribus.ICON_WARNING,
                    button1=scribus.BUTTON_YES,
                    button2=scribus.BUTTON_ABORT)
                if answer == scribus.BUTTON_YES:
                    writeColorCsvFile(filename, cols)
                else:
                    sys.exit()
            else:
                writeColorCsvFile(filename, cols)
        else:
            sys.exit()
    else:  # NO DOC OPEN - open one!
        scribusfile = scribus.fileDialog(
            "color2csv: Open scribus file",
            "Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)")
        if scribusfile != "":
            try:
                scribus.openDoc(scribusfile)
            except:
                scribus.messageBox("color2csv", "Could not open file!")
                sys.exit()
            #get colors, get filename, write stuff
            cols = getColorsFromDoc()
            filename = scribus.fileDialog("color2csv: Save csv color file",
                                          defaultname="colors.csv",
                                          issave=True)
            writeColorCsvFile(filename, cols)
        else:
            sys.exit()
def writeColorCsvFile(filename, colorlist):
    """writes all the colors to a csv file"""
    scribus.statusMessage("Writing colors to csv file...")
    scribus.progressTotal(len(colorlist))
    i = 0
    try:
        csvwriter = csv.writer(file(filename, "w"),
                               quoting=csv.QUOTE_NONNUMERIC)
        for line in colorlist:
            csvwriter.writerow(line)
            i = i + 1
            scribus.progressSet(i)
    except:
        scribus.messageBox("color2csv",
                           "Could not write file!",
                           icon=scribus.ICON_WARNING)
        sys.exit()
Example #38
0
def getCSVdata(delim, qc):
    """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
    csvfile = scribus.fileDialog("csv2table new:: open file", "*.csv")
    if csvfile != "":
        try:
            reader = csv.reader(file(csvfile), delimiter=delim, quotechar=qc)
            datalist=[]
            skipfirst=False
            for row in reader:
                if skipfirst==True:
                    rowlist=[]
                    for col in row:
                        rowlist.append(col)
                    datalist.append(rowlist)
                else : skipfirst=True
            return datalist
        except Exception,  e:
            scribus.messageBox("csv2table new", "Could not open file %s"%e)
Example #39
0
def getCSVdata(delim, qc):
    """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
    csvfile = scribus.fileDialog("csv2table new:: open file", "*.csv")
    if csvfile != "":
        try:
            reader = csv.reader(file(csvfile), delimiter=delim, quotechar=qc)
            datalist=[]
            skipfirst=False
            for row in reader:
                if skipfirst==True:
                    rowlist=[]
                    for col in row:
                        rowlist.append(col)
                    datalist.append(rowlist)
                else : skipfirst=True
            return datalist
        except Exception,  e:
            scribus.messageBox("csv2table new", "Could not open file %s"%e)
def main_wrapper(argv):
    try:
        if(scribus.haveDoc()):
            scribus.setRedraw(False)
            scribus.statusMessage(CONST.APP_NAME)
            scribus.progressReset()
            main(argv)
        else:
            scribus.messageBox('Usage Error', 'You need a Document open', icon=scribus.ICON_WARNING, button1=scribus.BUTTON_OK)
            sys.exit(2)
    finally:
        # Exit neatly even if the script terminated with an exception,
        # so we leave the progress bar and status bar blank and make sure
        # drawing is enabled.
        if scribus.haveDoc():
            scribus.setRedraw(True)
        scribus.statusMessage("")
        scribus.progressReset()
def main(argv):
    
    
##########################################   

    # 1.import all images
    import_all_images.main_wrapper(sys.argv)
    
    # 2.add exit buttons
    add_exit_buttons.main_wrapper(sys.argv)
    
    # 3.add arrows and links
    add_arrows_and_links.main_wrapper(sys.argv)
    
    # done
    pagenum = scribus.pageCount()
    donetext = """
The photo documentation is ready!

Page(s): """ + str(pagenum) + """
    
The following layers have been created:
    - Arrowlinks: a layer with the arrows and the annotation links to the pages
    - Exitbuttons: a layer with the exit buttons
    - Filenames:  a layer with the file names of the images (if wanted)
    - Background : a layer with the images
    
Tips:
    - Show layers in Scribus: Menu/Windows/Layers or F6
    - Rotate object (e.g. arrows): R (do not rotate the links!)
    - Show object properties: Menu/Windows/Properties or F2
    - In the properties, you can rotate and resize the images
        (select the "Background" layer first)
    - The object name of a link shows the destination page, e.g. "link_to_page_7"
    - Try to put also arrows and links into the images to navigate directly
    - Reduce the size of your pictures before starting PhotoDoc to speed up
        the process and reduce the PDF file size
    - Use the power of Scribus to enhance the documentation with textes, 
        arrows, weblinks...
    - If you need to reproduce a step, delete the step layer and restart step script,
        e.g. "add_exit_buttons.py"
    - Export a PDF with 96 dpi as image resolution to reduce the PDF file size
"""
    scribus.messageBox("PhotoDoc", donetext)
Example #42
0
    def __init__(self, gui):
        super().__init__()
        if not scribus.haveDoc():
            scribus.messageBox('Scribus - Script Error', "No document open",
                               scribus.ICON_WARNING, scribus.BUTTON_OK)
            sys.exit(1)

        self.gui = gui
        self.terminselections = {}
        self.tourselections = {}
        self.touren = []
        self.termine = []
        self.url = None
        self.run = None
        self.textbox = None
        self.linkType = "Frontend"
        self.gliederung = None
        self.includeSub = False
        self.start = None
        self.end = None
        self.pos = None
        self.ausgabedatei = None
        self.toBeDelPosParam = None
        self.toBeDelPosToc = None
        self.pageNr = None
        self.frameLinks = {}
        self.selecter = selektion.Selektion()

        global debug
        try:
            _ = os.environ["DEBUG"]
            debug = True
        except:
            debug = True  # False

        self.openScrb()
        self.scrbExtension = ScrbExtension()
        self.md = markdown.Markdown(extensions=[
            self.scrbExtension,
            markdown.extensions.tables.makeExtension()
        ],
                                    enable_attributes=True,
                                    logger=logger)
        self.scrbExtension.scrbTreeProcessor.setDeps(self)
Example #43
0
def CMYKgradientPoint(CMYKstart, CMYKend, steps, currentStep):
    '''Returns CMYK values based on the given parameters.
    CMYKstart, CMYKend : tuple of size 4.
    As strange as it is, Scribus encode CMYK values from 0 to 255.'''
    try:
        C = int(
            round(gradientPoint(CMYKstart[0], CMYKend[0], steps, currentStep)))
        M = int(
            round(gradientPoint(CMYKstart[1], CMYKend[1], steps, currentStep)))
        Y = int(
            round(gradientPoint(CMYKstart[2], CMYKend[2], steps, currentStep)))
        K = int(
            round(gradientPoint(CMYKstart[3], CMYKend[3], steps, currentStep)))
        return (C, M, Y, K)
    except:
        print error_message_CMYKgradientpoint
        scribus.messageBox(TITLE, error_message_CMYKgradientpoint,
                           scribus.ICON_WARNING)
        return (0, 0, 0, 0)
Example #44
0
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)
Example #45
0
def main():
    pass

    n = scribus.selectionCount()
    if n == 0:
        scribus.messageBox('Error', 'No item selected')
        return

    items = []
    for i in range(n):
        items.append(scribus.getSelectedObject(i))

    for item in items:
        pos = scribus.getPosition(item)
        dx, dy = pos
        scribus.pasteObject()
        new_item = scribus.getSelectedObject()
        pos = scribus.getPosition(new_item)
        dx, dy = dx - pos[0], dy - pos[1]
        scribus.moveObject(dx, dy, new_item)
        scribus.deleteObject(item)
Example #46
0
def getSelection():
    '''Returns a list of the selected TextFrame objects.
    Returns an empty list if there is no TextFrame Object currently selected.'''
    try:
        filtered_selection = [
        ]  # list we're going to use to put all the TextFrame elements
        # first, we check if there is something to work on
        if scribus.selectionCount() > 0:
            # then we check for each element
            # if it's a TextFrame object.
            # if so, we add it's name to the filtered list.
            for i in range(0, scribus.selectionCount()):
                if scribus.getObjectType(
                        scribus.getSelectedObject(i)) == 'TextFrame':
                    filtered_selection.append(scribus.getSelectedObject(i))
        return filtered_selection
    except:
        print error_message_selection_error
        scribus.messageBox(TITLE, error_message_selection_error,
                           scribus.ICON_WARNING)
        return []
Example #47
0
def main():
    # haben wir ein Dokument geoeffnet
    if scribus.haveDoc():
        # haben wir in diesem Dokument genau *ein* Objekt markiert
        if (scribus.selectionCount() == 1):
            # Ist dieses Objekt ein Bild, dann
            if (scribus.getObjectType() == "ImageFrame"):
                # lese den vollstaendigen Namen der datei (inkl. Pfad) in die Variable name
                name = scribus.getImageFile()
                # bastele einen neuen Namen aus dem Pfad, %VAR_ und dem Objektnamen und schreibe ihn als Standardwert in den Dialog
                newname = scribus.valueDialog(
                    os.path.split(name)[1] +
                    " wird ersetzt durch %VAR_[name]%",
                    "Variablenname ergänzen: ",
                    os.path.split(name)[0] + "/%VAR_" +
                    scribus.getSelectedObject() + "%")
                # uebernehme den Wert aus dem Dialogfenster (keine plausibilitaetspruefung. das ist ein beliebiger String
                scribus.loadImage(newname)
            else:
                scribus.messageBox("Fehler",
                                   "markierter Frame ist kein Bildrahmen",
                                   scribus.ICON_CRITICAL)
        else:
            scribus.messageBox("Fehler", "bitte *einen* Bildrahmen markieren",
                               scribus.ICON_CRITICAL)
    else:
        scribus.messageBox("Fehler", "kein Dokument geöffnet",
                           scribus.ICON_CRITICAL)
Example #48
0
def main():
    """
    This script applies a colour gradient to all the characters, sequentially,
    of all the selected TextFrame objects in Scribus.
    You have to define two colours (start and stop) prior to run it.
    """
    try:
        # first, get the colors
        CMYKstart, CMYKend = getColors()
        # second, the selection of item we can actually work on
        selection = getSelection()
        # If the values are not defined or if there is no selection,
        # we stop here, if they are, we continue
        if CMYKstart != None and CMYKend != None and len(selection) > 0:
            sequentialTextFrameSelection(selection, CMYKstart, CMYKend,
                                         simpleGradient)
            print success_message
            scribus.messageBox(TITLE, success_message,
                               scribus.ICON_INFORMATION)
    except:
        print error_message_main_error
        scribus.messageBox(TITLE, error_message_main_error,
                           scribus.ICON_WARNING)
        if debug != None:
            scribus.messageBox(TITLE, debug, scribus.ICON_WARNING)
def extract(chart):
    """
    Extract the graphic chart of the current document.
    """
    if not scribus.haveDoc():
        return  
    
    try:
        scribus.saveDoc()
        if not scribus.getDocName():
            raise IOError('Could not save document.')
    except:
        scribus.messageBox('Script failed',
                           'This script only works if you saved the document.')
        return

    colors = extract_colors()
    fonts = extract_fonts()
    for color in colors:
        chart.add_color(color)
    for font in fonts:
        chart.add_font(font)
    return chart
Example #50
0
def main_wrapper():
   """The main_wrapper() function disables redrawing, sets a sensible generic
   status bar message, and optionally sets up the progress bar. It then runs
   the main() function. Once everything finishes it cleans up after the main()
   function, making sure everything is sane before the script terminates."""
   scribus.messageBox("Version",SCRIPT_VERSION)
   if not scribus.haveDoc():
      scribus.messageBox("Bwaaaahaha","Need a base document open")
   else:
      scribus.setRedraw(False)
      try:
          scribus.statusMessage("Running script...")
          scribus.progressReset()
          main()
      finally:
          # Exit neatly even if the script terminated with an exception,
          # so we leave the progress bar and status bar blank and make sure
          # drawing is enabled.
          if scribus.haveDoc():
              scribus.setRedraw(True)
              scribus.docChanged(True)
          scribus.statusMessage("")
          scribus.progressReset()
Example #51
0
    def loadCSVData (self, csvFile) :
        '''Load up the CSV data and return a dictionary'''

        if os.path.isfile(csvFile) :
            records = list(csv.DictReader(open(csvFile,'r')))
            records = list(filter(self.select,
                    imap(self.sanitise, records)))

            # Now sort starting with least significant to greatest
            records.sort(key=operator.itemgetter('NameFirst'))
            records.sort(key=operator.itemgetter('NameLast'))
            return records
        else :
            result = scribus.messageBox ('File not Found', 'Data file: [' + csvFile + '] not found!', scribus.BUTTON_OK)
Example #52
0
def getColorsFromDocument():
    """gets colors from opend document. if there is no document, display dialog to chose a file. returns a list[name,c,m,y,k]"""

    def getColors():
        """gets the colors and returns a list[name,c,m,y,k]"""
        colorNames = scribus.getColorNames()
        list = []
        scribus.statusMessage("Reading Colors...")
        stepsTotal = len(colorNames)
        scribus.progressTotal(stepsTotal)
        steps = 0
        for name in colorNames:
            color = scribus.getColor(name)
            listitem = [name, color[0], color[1], color[2], color[3]]
            list.append(listitem)
            # update progress bar
            steps = steps + 1
            scribus.progressSet(steps)
        return list

    # check if we have a document - otherwise display open file dialog
    if scribus.haveDoc() > 0:
        pass
        list = getColors()
        return list
    else:
        pass
        # display file open dialog
        file = scribus.fileDialog("ColorChart by Sebastian Stetter", "Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)")
        # open file
        try:
            scribus.openDoc(file)
        except:
            scribus.messageBox("ColorChart by Sebastian Stetter", "could not open file")
            sys.exit()
        list = getColors()
        return list
def checkForOneFrameSelected() :
    if not scribus.haveDoc():
        scribus.messageBox('Usage Error', 'You need a Document open', icon=0, button1=1)
        sys.exit(2)

    if scribus.selectionCount() == 0:
        scribus.messageBox('Scribus - Usage Error',
            "There is no frame 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 frame selected.\nPlease select one text frame and try again.", scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(2)
Example #54
0
def main(argv):
    """Main method for importing colors."""
    if not scribus.haveDoc() > 0: #do we have a doc?
        scribus.messageBox("csv2color", "No document to import colors \n Please open one, first.")
        sys.exit()
    else:
        filename=scribus.fileDialog("csv2color",  "CSV files(*.csv *.CSV *.txt *.TXT)")
        while os.path.isdir(filename):
            filename=scribus.fileDialog("csv2color",  "CSV files(*.csv *.CSV *.txt *.TXT)") #proper filename?
        else:
            try:
                colorlist=getColorsFromCsv(filename)
                messagestring = "You are going to import %i colors \n This may take a while" % len(colorlist)
                answer = scribus.messageBox("csv2color", messagestring, button1=scribus.BUTTON_OK,  button2=scribus.BUTTON_CANCEL)
                if answer != scribus.BUTTON_OK:
                    sys.exit()
                else:
                    importColors(colorlist)
                    scribus.docChanged(True)
                    scribus.messageBox("csv2color", "Colors imported! \n Thank you for using csv2color and Scribus!")
            except:
                scribus.messageBox("csv2color", "Could not import file!", icon=scribus.ICON_WARNING)
                sys.exit()
# create a list of items with a brokein link
for page_i in range(0, page_n) :
    scribus.gotoPage(page_i + 1)
    item_list = scribus.getPageItems()
    #print(item_list)
    for item in item_list :
        if item[1] == 2 :
            image_filepath = ""
            image_filepath = scribus.getImageFile(item[0])
            print(image_filepath)
            if image_filepath != "" and not os.path.isfile(image_filepath) :
                item_missing.append((item[0], image_filepath))
# print(item_missing)

# read the link for the first image with a broken link and try to apply the path
# to each other image with a broken link
if item_missing :
    if scribus.messageBox("Missing images", "There are missing images. Do you want to look for them?", scribus.ICON_WARNING, scribus.BUTTON_YES, scribus.BUTTON_NO) == scribus.BUTTON_YES:
        filename_found = scribus.fileDialog("Find "+os.path.basename(item_missing[0][1]), "Image files (*."+os.path.splitext(item_missing[0][1])[1][1:]+")")
        # print(filename_found)

        if filename_found:
            path_found = os.path.dirname(filename_found)
            # print("path_found "+path_found)
            for item in item_missing:
                item_filename = os.path.join(path_found, os.path.basename(item[1]))
                # print(item_filename)
                if os.path.isfile(item_filename) :
                    scribus.loadImage(item_filename, item[0])
Example #56
0
def msg():
    scribus.messageBox("Scribus - Python Timer",
                       "The timer has run out",
                       scribus.BUTTON_OK)
Example #57
0
        scribus.setColumns(1, new_textbox)
        scribus.textFlowMode(new_textbox, 1)
    else:
        if (frametype == 'imageL'):
	    imageload = scribus.fileDialog('Load image','Images(*.jpg *.png *.tif *.JPG *.PNG *.jpeg *.JPEG *.TIF)',haspreview=1)
	    new_image = scribus.createImage(new_left, float(new_top), new_width, float(new_height),framename)
	    scribus.loadImage(imageload, new_image)
            scribus.messageBox('Please Note',"Your frame will be created once you click OK.\n\nUse the Context Menu to Adjust Frame to Image.\n\nIf your image does not fill the width completely,\nstretch the frame vertically first.",scribus.BUTTON_OK)
        else:
	    new_image = scribus.createImage(new_left, float(new_top), new_width, float(new_height),framename)
        scribus.textFlowMode(new_image, 1)
        scribus.setScaleImageToFrame(scaletoframe=1, proportional=1, name=new_image)
if __name__ == '__main__':
    # This script makes no sense without a document open
    if not scribus.haveDoc():
        scribus.messageBox('Scribus - Script Error', "No document open", scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(1)
    # Disable redraws
    scribus.setRedraw(False)
    # Run the main script, ensuring redraws are re-enabled even if the
    # script aborts with an exception, and don't fail with an exception
    # even if the document is closed while the script runs.
    try:
        main(sys.argv)
    finally:
        try:
            scribus.setRedraw(True)
        except:
            pass

Example #58
0
def main(argv):
    unit = scribus.getUnit()
    units = [' pts','mm',' inches',' picas','cm',' ciceros']
    unitlabel = units[unit]
    if scribus.selectionCount() == 0:
        scribus.messageBox('Scribus - Script Error',
            "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 - Script 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 - Script Error', 
                          "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK)
                sys.exit(2)

# While we're finding out what kind of frame is selected, we'll also make sure we
# will come up with a unique name for our infobox frame - it's possible we may want
# more than one for a multicolumn frame.
        if (item[0] == ("infobox" + str(boxcount) + textbox)):
                boxcount += 1
    left, top = scribus.getPosition(textbox)
    o_width, o_height = scribus.getSize(textbox)
    o_cols = int(scribus.getColumns(textbox))
    o_gap = scribus.getColumnGap(textbox)
            
    columns_width = 0
    column_pos = 0
    o_colwidth = (o_width - ((o_cols - 1) * o_gap)) / o_cols
    if (o_cols > 1):
        while (columns_width > o_cols or columns_width < 1):
            columns_width = scribus.valueDialog('Width',
                                            'How many columns width shall the '+
                                            'box be (max ' + str(o_cols) + ')?','1')
            columns_width = int(columns_width)
        if (columns_width < o_cols):
            max = o_cols - columns_width
            while (column_pos <= max and column_pos <= 1):
                column_pos = scribus.valueDialog('Placement',
                                         'In which column do you want '
                                         'to place the box (1 to ' +
                                         str(o_cols) + ')?','1')
            column_pos = int(column_pos) - 1 
    if (o_cols == 1):
	columns_width = 1
    new_height = 0
    while (new_height == 0):
        new_height = scribus.valueDialog('Height','Your frame height is '+ str(o_height) +
                                                 unitlabel +'. How tall\n do you want your ' +
                                                 'infobox to be in '+ unitlabel +'?\n If you load an image, height will be\n calculated, so the value here does not\n matter.', str(o_height))
    new_top = -1
    while (new_top < 0):
        new_top = scribus.valueDialog('Y-Pos','The top of your infobox is currently\n'+ str(top) +
                                                 unitlabel +'. Where do you want \n' +
                                                 'the top to be in '+ unitlabel +'?', str(top))
    framename = scribus.valueDialog('Name of Frame','Name your frame or use this default name',"infobox" + str(boxcount) + textbox)
    frametype = 'text'
    frametype = scribus.valueDialog('Frame Type','Change to anything other\n than "text" for image frame.\nEnter "imageL" to also load an image',frametype)
    new_width = columns_width * o_colwidth + (columns_width-1) * o_gap
    new_left = left + ((column_pos) * o_colwidth) + ((column_pos) * o_gap)
    if (frametype == 'text'):
        new_textbox = scribus.createText(new_left, float(new_top), new_width, float(new_height),framename)
        scribus.setColumnGap(0, new_textbox)
        scribus.setColumns(1, new_textbox)
        scribus.textFlowMode(new_textbox, 1)
    else:
        if (frametype == 'imageL'):
	    imageload = scribus.fileDialog('Load image','Images(*.jpg *.png *.tif *.JPG *.PNG *.jpeg *.JPEG *.TIF)',haspreview=1)
	    new_image = scribus.createImage(new_left, float(new_top), new_width, float(new_height),framename)
	    scribus.loadImage(imageload, new_image)
            scribus.messageBox('Please Note',"Your frame will be created once you click OK.\n\nUse the Context Menu to Adjust Frame to Image.\n\nIf your image does not fill the width completely,\nstretch the frame vertically first.",scribus.BUTTON_OK)
        else:
	    new_image = scribus.createImage(new_left, float(new_top), new_width, float(new_height),framename)
        scribus.textFlowMode(new_image, 1)
        scribus.setScaleImageToFrame(scaletoframe=1, proportional=1, name=new_image)
Example #59
0
        lead_double = u"\u00ab"
        follow_double = u"\u00bb"
	follow_double = u"\u201d"
        lead_single = u"\u2018"
    elif ((lang == 'lt') or (lang == 'mk') or (lang == 'is') or (lang == 'sk') or (lang == 'sl') or (lang == 'cs') or (lang == 'et')):
        lead_double = u"\u201e"
        follow_double = u"\u201c"
        lead_single = u"\u2019"
        follow_single = u"\u201a"
    elif ((lang == 'hu') or (lang == 'nl')):
	lead_double = u"\u201e"
	follow_double = u"\u201d"
	lead_single = u"\u00bb"
	follow_single = u"\u00ab"
    else:
        scribus.messageBox('Language Error', 'You need to choose an available language', icon=0, button1=1)
        sys.exit(2)
        
else:
    scribus.messageBox('Usage Error', 'You need a Document open', icon=0, button1=1)
    sys.exit(2)

if scribus.selectionCount() == 0:
    scribus.messageBox('Scribus - Usage Error',
        "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)