예제 #1
0
def get_imageframes_on_page(page_number, empty_only=False, name_filter=None):
    """
    page_number:  if 0 use current page, otherwise the given page
    set emty_only to return empty frames only
    name_filter: return frame if name conatins filter string
    returns a list of the image objects on the current page
    get all the items on the page
    """

    current_page = sc.currentPage()
    if page_number > 0:
        if page_number <= sc.pageCount():
            sc.gotoPage(page_number)
        else:
            logging.warning('Page {} out of rage.'.format(page_number))
            return []

    item_list = sc.getPageItems()
    # refine it to a list of only image objects
    objs = []
    for item in item_list:
        if item[1] == 2:  #type 2 == image
            add_image = True
            if empty_only:
                add_image = is_imageframe_empty(item[0]) and add_image
            if name_filter:
                if name_filter in item[0]:
                    add_image = True and add_image
                else:
                    add_image = False and add_image
            if add_image:
                objs.append(item[0])
    sc.gotoPage(current_page)
    return objs
예제 #2
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)
예제 #3
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, scribus.ICON_NONE,
                       scribus.BUTTON_OK)
예제 #4
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)
예제 #5
0
 def makeToc(self, firstPageNr):
     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
             self.textbox = item[0]
             self.evalTocTemplate(firstPageNr)
     scribus.redrawAll()
예제 #6
0
def createDOMDocument():
    root = None;
    d = dict();
    i = dict();
    impl = getDOMImplementation();
    newdoc = impl.createDocument(None, "root", None);
 
    pageitems = scribus.getPageItems()
    for item in pageitems:
        if (item[1] == 4):
            elemId = getElemId(item[0]);
            pElemId = getParentElemId(item[0]);
            if (elemId != -1 and pElemId == -1):
                root = item[0];
            if (elemId != -1 and pElemId != -1):
                xmlElem = createDOMElement(newdoc, item[0]);
                d[elemId] = xmlElem;
                i[elemId] = pElemId;

    #for now flat tree
    #xmlRoot = newdoc.documentElement;
    #xmlRoot.setAttribute("id", str(getElemId(root)));
    #xmlRoot.tagName = getElemName(root);
    #for x in d.values():
    #    xmlRoot.appendChild(x);

    xmlRoot = newdoc.documentElement;
    xmlRoot.setAttribute("id", str(getElemId(root)));
    xmlRoot.tagName = getElemName(root);

    #append childs level below root
    for x in i.values():
        key = -1;
        for u in d.keys():
            if (u == x):
                key = x;
        if (key != -1):
            pXmlElem = d[key];
        
            # TODO: order of child is missing
            for y in i.keys():
                if (i[y] == key):
                    pXmlElem.appendChild(d[y]);


    #append root childs
    rootId = getElemId(root);
    # TODO: order of child is missing
    for y in i.keys():
        if (i[y] == rootId):
            xmlRoot.appendChild(d[y]);

    return newdoc;
예제 #7
0
 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()
예제 #8
0
def TemplateCheck():
    """ Performs some sanity checks on the template page.
	
	Args:
		none
	
	Returns:
		None:   No error.
		string: A string containing the error message
	"""

    # check number of documents open; we accept only one
    numDocs = scribus.haveDoc()
    if numDocs < 1:
        return "No document opened."
    elif numDocs > 1:
        return "More than one document is opened."

    # check number of pages that exist; we accept only one
    numPages = scribus.pageCount()
    if numPages < 1:
        return "No page created."
    elif numPages > 1:
        return "Please reduce the document to a single calendar template page."

    # check if items exist on this page
    numItems = len(scribus.getPageItems())
    if numItems < 1:
        return "This page is empty."

    # check if at least one object's name starts with the MAGICSTRING
    magicStrings = 0
    for item in scribus.getPageItems():
        if item[0].find(MAGICSTRING) == 0:
            magicStrings += 1
    if magicStrings == 0:
        return "No object with file name tag 't365_' found."

    return None
def listImages(filename):

    file_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] == 2:
                file_content.append(scribus.getImageFile(item[0]) + '\n')

        file_content.append('\n')
    output_file = open(filename, 'w')
    output_file.writelines(file_content)
    output_file.close()
def get_all_empty_images_frames():
    image_frames = []
    for page in range(1, scribus.pageCount() + 1):
        page_image_frames = []
        scribus.gotoPage(page)
        # get all empty image frames on the page
        for item in scribus.getPageItems():
            if item[1] == 2:
                if scribus.getImageFile(item[0]) == "":
                    x, y = scribus.getPosition(item[0])
                    page_image_frames.append((item[0], x, y))
        # sort the frames by position
        page_image_frames.sort(key=lambda k: [k[2], k[1]])
        image_frames += [i[0] for i in page_image_frames]
    return image_frames
def fileMatchingTextFrame(sampleFrameName, pattern):
    pagenum = scribus.pageCount()
    for page in range(1, pagenum + 1):
        scribus.gotoPage(page)
        d = scribus.getPageItems()
        for item in d:
            # print(item)
            frameName = item[0]
            if (item[1] == 4):
                if frameName != sampleFrameName and remove_copy_prefix(frameName).startswith(pattern):
                    print(frameName + " found")
                    position = scribus.getPosition(frameName)
                    scribus.selectObject(sampleFrameName)
                    scribus.duplicateObject()
                    #duplicateFrameName = scribus.getSelectedObject()
                    scribus.moveObjectAbs(position[0], position[1])
                    scribus.deleteObject(frameName)
예제 #12
0
def get_placeholders():
    text_frames = []
    image_frames = []

    page_n = scribus.pageCount()
    for page in range(1, page_n + 1):
        scribus.gotoPage(page)
        for item in scribus.getPageItems():
            if item[1] == 2:
                placeholders = get_image_placeholders(item[0])
                if placeholders:
                    image_frames.append((item[0], placeholders))
            if item[1] == 4:
                placeholders = get_text_placeholders(item[0])
                if placeholders:
                    text_frames.append((item[0], placeholders))
    return text_frames, image_frames
def fileMatchingTextFrame(sampleFrameName, pattern):
    pagenum = scribus.pageCount()
    for page in range(1, pagenum + 1):
        scribus.gotoPage(page)
        d = scribus.getPageItems()
        for item in d:
            # print(item)
            frameName = item[0]
            if (item[1] == 4):
                if frameName != sampleFrameName and remove_copy_prefix(
                        frameName).startswith(pattern):
                    print(frameName + " found")
                    position = scribus.getPosition(frameName)
                    scribus.selectObject(sampleFrameName)
                    scribus.duplicateObject()
                    #duplicateFrameName = scribus.getSelectedObject()
                    scribus.moveObjectAbs(position[0], position[1])
                    scribus.deleteObject(frameName)
예제 #14
0
def findElemById(elemId):
    
    pageitems = scribus.getPageItems()
    for item in pageitems:

        felemId = 0;

        if (len(item)>1 and item[1] == 4):
            #scribus.messageBox('dde', str(item[0]), scribus.ICON_WARNING, scribus.BUTTON_OK)

            attrs = scribus.getObjectAttributes(item[0]);
            if (len(attrs)>1):
                #scribus.messageBox('dde', str(attrs[1]), scribus.ICON_WARNING, scribus.BUTTON_OK)
                felemId = int(attrs[1]['Value']);
                #scribus.messageBox('ddx', str(type(felemId)))

        if (felemId == elemId):
            return item[0];
    return None; 
예제 #15
0
def TemplateGetFileNames():
    """ Analyse Scibus' object names and return a list of file names associated with them.
	
	Args:
		none
	
	Returns:
		list:   A list with file names, e.g [ "day.t365", "month.t365", ... ]
		        If nothing was found, an empty list [] will be returned.
	"""

    listNames = []
    for item in scribus.getPageItems():
        if item[0].find(MAGICSTRING) == 0:
            fileName = item[0][len(MAGICSTRING):]
            if fileName != "":
                listNames += [fileName]

    return listNames
예제 #16
0
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')
예제 #17
0
def duplicate_content(pages, named_items):
    """ duplicate the content of pages at the end of the document
        and track the new item names for the items in named_items
    return the list of created item names from named_items """
    result = {}
    page_n = scribus.pageCount()
    for page in pages:
        scribus.gotoPage(page)
        items = [item[0] for item in scribus.getPageItems()]
        scribus.newPage(-1, scribus.getMasterPage(page))
        page_n += 1

        for item in items:
            scribus.gotoPage(page)
            scribus.copyObject(item)
            scribus.gotoPage(page_n)
            scribus.pasteObject()
            if item in named_items:
                result[item] = scribus.getSelectedObject()
    return result
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()
예제 #19
0
def main():

    familles = get_families_ascii_names()
    for famille in familles:
        for n in range(1, 7):
            scribus.openDoc("template.sla")
            items = scribus.getPageItems()

            change_title(famille, n, items)
            change_number(famille, n, items)
            change_family(famille, n, items)
            change_advice(famille, n, items)
            change_family_members(famille, n, items)
            change_flavor(famille, n, items)
            change_background(famille, n, items)

            image = scribus.ImageExport()
            image.type = 'PNG'
            image.scale = 100
            image.saveAs(famille + "_" + str(n) + ".png")

            scribus.closeDoc()
예제 #20
0
 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()
예제 #21
0
        
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)
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)
예제 #22
0
#!/usr/bin/env python

import scribus
import sys
import os
from random import randint
magtxt = 'Enter a magnetude number between 1 and 10'
pagetxt = 'What page to shake?'
magnetude = int(scribus.valueDialog("Magnetude", magtxt, "1"))
page = int(scribus.valueDialog("Enter page number, '0' for all", pagetxt, "1"))
pagenum = scribus.pageCount()
content = []
if page == 0:
    page = 1
else:
    pagenum = page
    pass
while (page <= pagenum):
    scribus.gotoPage(page)
    d = scribus.getPageItems()
    for item in d:
        rand = randint(-magnetude * 10, magnetude * 10)
        itemname = item[0]
        print itemname
        scribus.rotateObjectAbs(rand, itemname)
        scribus.moveObject(rand, rand, itemname)
    page += 1
예제 #23
0
파일: InfoBox.py 프로젝트: moceap/scribus
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)
예제 #24
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 with the script, height will be\n calculated, so the value here will not\n matter in that case.',
            str(o_height))
        if (not new_height):
            sys.exit(0)
        new_height = float(new_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))
        if (not new_top):
            sys.exit(0)
        new_top = float(new_top)
    framename = scribus.valueDialog(
        'Name of Frame', 'Name your frame or use this default name',
        "infobox" + str(boxcount) + textbox)
    if (not framename):
        sys.exit(0)
    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)
    if (not frametype):
        sys.exit(0)
    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.textFlowMode(new_image, 1)
            scribus.loadImage(imageload, new_image)
            scribus.setScaleImageToFrame(1, 0, new_image)
            currwidth, currheight = scribus.getSize(new_image)
            Xscale, Yscale = scribus.getImageScale(new_image)
            if (Xscale != Yscale):
                scribus.sizeObject(currwidth, currheight * Xscale / Yscale,
                                   new_image)
            scribus.setScaleImageToFrame(1, 1, new_image)
        else:
            new_image = scribus.createImage(new_left,
                                            float(new_top), new_width,
                                            float(new_height), framename)
            scribus.textFlowMode(new_image, 1)
            scribus.setScaleImageToFrame(1, 1, new_image)
예제 #25
0
#!/usr/bin/env python

import scribus
import sys
import os
from random import randint
magtxt = 'Enter a magnetude number between 1 and 10'
pagetxt = 'What page to shake?'
magnetude = int(scribus.valueDialog("Magnetude",magtxt,"1"))
page = int(scribus.valueDialog("Enter page number, '0' for all",pagetxt,"1"))
pagenum = scribus.pageCount()
content = []
if page == 0:
	page = 1
else:
	pagenum = page
	pass
while (page <= pagenum):
	scribus.gotoPage(page)
	d = scribus.getPageItems()
	for item in d:
		rand = randint(- magnetude * 10 , magnetude * 10)
		itemname = item[0]
		print itemname
		scribus.rotateObjectAbs(rand,itemname)
		scribus.moveObject(rand,rand,itemname)
	page += 1
예제 #26
0
    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]]
예제 #27
0
filenames = glob.glob(directory + '/[0-9]*.sla')
# Cards whose text is too long, and must therefore use a smaller font
indices_with_long_text = [10, 12, 23, 39, 44, 46, 57]
# HACK! I'm sorry :(
files_with_long_text = [
    "{}{}.sla".format(directory, i) for i in indices_with_long_text
]
if not filenames:
    print("No documents with expected name found in " + directory)
for infile in filenames:
    print("Opening " + infile)
    scribus.openDoc(infile)
    # Auto-scale the picture
    try:
        # Find which image object we must change
        images = [s for s in scribus.getPageItems() if s[1] == IMG_TYPE]
        frame = sorted(images, key=lambda s: s[2])[-1][0]
        # frame should be "Image9" if all elements are rendered
        scribus.setScaleImageToFrame(True, name=frame)
        scribus.saveDoc()
    except NoValidObjectError, err:
        print("Image not found in " + infile)
    # Change the text size if necessary
    print(infile)
    if infile in files_with_long_text:
        print("Found " + infile + "!!!")
        try:
            frame = "Text7"
            scribus.setFontSize(11, frame)
            scribus.saveDoc()
        except NoValidObjectError, err:
예제 #28
0
                "Voulez vous aussi appliquer ce traitement sur les double-guillemets français déjà en place ? Oui: O ; Non : N ", 
                'O')
    else:
       replace_existing = scribus.valueDialog("What about existing qyotes ?", 
                "Should the script apply your spaces-choice ALSO on already existing quotes ? Yes : Y ; No : N", 
                'N')

if ((replace_existing=='y') or (replace_existing=='Y') or (replace_existing=='o') or (replace_existing=='O')):
    replace_existing=1
else:
    replace_existing=0

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'
예제 #29
0
    else:
        replace_existing = scribus.valueDialog(
            "What about existing qyotes ?",
            "Should the script ALSO apply your spaces-choice on already existing quotes? Yes : Y ; No : N",
            'N')

if ((replace_existing == 'y') or (replace_existing == 'Y')
        or (replace_existing == 'o') or (replace_existing == 'O')):
    replace_existing = 1
else:
    replace_existing = 0

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)
예제 #30
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

    elem = textbox;
    pathUp = '';
    pathUpShort = "";

    while elem != None:
        elemId = getElemId(elem);
        pElemId = getParentElemId(elem);

        text = scribus.getText(elem);
        if (text.find("Holder")!=-1):
            text = "";
        
        pathUpShort = "<" + getElemName(elem) + " id=\"" + str(getElemId(elem)) + "\">" + text + "\n" + pathUpShort;
        pathUp = dumpElem(elem) + " // " +  pathUp;
        elem = findElemById(pElemId);

    if (pathUp != ''):
        pathUp = pathUp[0:len(pathUp)-4];
    if (pathUpShort != ''):
        pathUpShort = pathUpShort[0:len(pathUpShort)-1];

    #framename = scribus.valueDialog('XML Tree','XML Tree', elemName + '[@id=' + elemId + '] parent: ' + parent + ' text:' + text + "," + parent)
    #scribus.messagebarText("It works !!!");
    scribus.statusMessage(pathUp);
    #scribus.zoomDocument(200);
    #scribus.selectFrameText(0,100);
    #framename = scribus.valueDialog('XML Tree','XML Tree (Path UP)', pathUp);

    #t = scribus.qApp.mainWidget();
    
    #if (not framename) :
    #    sys.exit(0)
    #scribus.messageBox('XML struct',
    #        pathUp + "\n\n" + pathUpShort,
    #        scribus.ICON_WARNING, scribus.BUTTON_OK)

    #impl = getDOMImplementation();
    #newdoc = impl.createDocument(None, "root", None);

    newdoc = createDOMDocument();
    #xmlelem = createDOMElement(newdoc, root);
    #newdoc.documentElement.appendChild(xmlelem);
    x = newdoc.toxml();
    #x = str(dir(root));

    scribus.structview(x);
예제 #31
0
else:
    scribus.messageBox('Usage Error',
                       'You need a Document open',
                       icon=0,
                       button1=1)
    sys.exit(2)

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)
예제 #32
0
replaced.

You would be wise to work on a copy of the original to avoid accidentally include
the wrong images.
"""

import scribus
import os.path

page_n = scribus.pageCount()
item_missing = []

# 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",
replaced.

You would be wise to work on a copy of the original to avoid accidentally include
the wrong images.
"""

import scribus
import os.path

page_n = scribus.pageCount()
item_missing = []

# 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:]+")")
예제 #34
0
    def handleEnd(self):
        self.linkType = self.gui.getLinkType()
        self.gliederung = self.gui.getGliederung()
        self.includeSub = self.gui.getIncludeSub()
        self.start = self.gui.getStart()
        self.end = self.gui.getEnd()

        pos1, pos2, tbox = self.toBeDelPosParam
        scribus.selectText(pos1, pos2 - pos1, tbox)
        scribus.deleteText(tbox)

        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
                self.textbox = item[0]
                self.evalTemplate()

        # hyphenate does not work
        # 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
        #         self.textbox = item[0]
        #         b = scribus.hyphenateText(self.textbox) # seems to have no effect!

        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]
                tbox2 = tbox
                while scribus.textOverflows(tbox2):
                    tbox2 = self.createNewPage(tbox2)
                    self.frameLinks[
                        tbox2] = tbox  # frame tbox2 has tbox as root

        scribus.redrawAll()
        ausgabedatei = self.ausgabedatei
        if ausgabedatei is None or ausgabedatei == "":
            ausgabedatei = "ADFC_" + self.gliederung + (
                "_I_" if self.includeSub else "_"
            ) + self.start + "-" + self.end + "_" + self.linkType[0] + ".sla"
        try:
            scribus.saveDocAs(ausgabedatei)
        except Exception as e:
            print("Ausgabedatei", ausgabedatei,
                  "konnte nicht geschrieben werden")
            raise e
        finally:
            self.touren = []
            self.termine = []
            # self.gui.destroy()
            # self.gui.quit()
            self.gui.disableStart()