def create_content():
    dirname = scribus.fileDialog("Select Directory", "", "", False, False, True)
    files = sorted(glob(os.path.join(dirname, "*")))
    if len(files) == 0:
        return

    scribus.progressReset()
    scribus.progressTotal(len(files))
    scribus.messagebarText("Creating pages...")
    progress = 0

    for f in files:

        scribus.progressSet(progress)
        progress = progress + 1

        add_image(f)

        if len(files) > progress:
            # add page for next image
            scribus.newPage(-1)

    scribus.progressReset()
    scribus.messagebarText("")
    scribus.deselectAll()
    scribus.gotoPage(1)
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()
Beispiel #3
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()
def create_content():
    dirname = scribus.fileDialog("Select Directory", "", "", False, False,
                                 True)
    files = sorted(glob(os.path.join(dirname, "*")))
    if len(files) == 0:
        return

    scribus.progressReset()
    scribus.progressTotal(len(files))
    scribus.messagebarText("Creating pages...")
    progress = 0

    for f in files:

        scribus.progressSet(progress)
        progress = progress + 1

        add_image(f)

        if len(files) > progress:
            # add page for next image
            scribus.newPage(-1)

    scribus.progressReset()
    scribus.messagebarText("")
    scribus.deselectAll()
    scribus.gotoPage(1)
def add_songs(all_songs, songs_double_page, manual_processing, songs_data, cache):
    # let's get the best sorting
    songs_combined = simplebin.best_fit(all_songs, EFFECTIVE_PAGE_HEIGHT)
    # sorting the songs alphabetic
    songs_sorted = sorted(songs_combined, key=lambda x: x[0])

    # make sure the double page will be added on the left side
    page_num = scribus.pageCount()
    for double_page in songs_double_page:
        if not double_page in all_songs:
            continue
        offset = songs_sorted.index([double_page])
        songs_sorted.insert(offset+1, None) # add a empty page after the song
        if (page_num + offset) % 2 != 0: # song is on right side, empty side on the left side.
            songs_sorted.insert(offset, songs_sorted.pop(offset+2)) # move next song before the double page
            # TODO: what if double sided song is last song?

    for songs in songs_sorted:
        current_pos = 0
        if songs == None: # we added this for a song that should be set on double page
            new_page()
            continue
        for filename in songs:
            if not manual_processing[filename].get("show", True):
                continue
            data = songs_data[filename]
            height, page_num = load_song(data, current_pos, manual_processing[filename])
            current_pos += math.ceil(height/BASELINE_GRID) * BASELINE_GRID
            cache[filename]["height"] = round(height, 2)
            cache[filename]["page"] = page_num
            scribus.progressSet(1)
        if current_pos != 0:
            new_page()
Beispiel #6
0
def main(argv):
    """This is a documentation string. Write a description of what your code
    does here. You should generally put documentation strings ("docstrings")
    on all your Python functions."""
    #########################
    #  YOUR CODE GOES HERE  #
    #########################
    userdim = scribus.getUnit()  # get unit and change it to mm
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
    cellwidthleft = 0
    cellwidthright = 0
    cellHeight = 0
    pos = getPosition()
    while cellwidthleft <= 0:
        cellwidthL = scribus.valueDialog("Left Cell Width", "How wide (mm) do you wish left cells to be?", "30.0")
        cellwidthleft = float(cellwidthL)
    while cellwidthright <= 0:
        cellwidthR = scribus.valueDialog("Right Cell Width", "How wide (mm) do you wish right cells to be?", "30.0")
        cellwidthright = float(cellwidthR)
    while cellHeight <= 0:
        cellheight = scribus.valueDialog("Cell Height", "How tall (mm) do you wish cells to be?", "10.0")
        cellHeight = float(cellheight)
    data = getCSVdata()
    di = getDataInformation(data)
    hposition = pos[1]
    vposition = pos[0]

    objectlist = []  # here we keep a record of all the created textboxes so we can group them later
    i = 0
    scribus.progressTotal(len(data))
    scribus.setRedraw(False)
    for row in data:
        c = 0
        for cell in row:
            cell = cell.strip()
            cellsize = cellwidthleft
            if c == 1:
                cellsize = cellwidthright
            textbox = scribus.createText(hposition, vposition, cellsize, cellHeight)  # create a textbox
            objectlist.append(textbox)
            scribus.insertText(cell, 0, textbox)  # insert the text into the textbox
            hposition = hposition + cellwidthleft  # move the position for the next cell
            c = 1
        vposition = vposition + cellHeight  # set vertical position for next row
        hposition = pos[1]  # reset vertical position for next row
        i = i + 1
        scribus.progressSet(i)

    scribus.groupObjects(objectlist)
    scribus.progressReset()
    scribus.setUnit(userdim)  # reset unit to previous value
    scribus.docChanged(True)
    scribus.statusMessage("Done")
    scribus.setRedraw(True)
Beispiel #7
0
def getColorDict():
    """get the colors that already exist from the opened Document and return a dictionary"""
    scribus.statusMessage("Reading existing colors...")
    colornames = scribus.getColorNames()
    scribus.progressTotal(len(colornames))
    i=0
    colordict={}
    for name in colornames:
        colordict[name]=None
        i=i+1
        scribus.progressSet(i)
    return colordict #we can ask this dict if the color already exists
Beispiel #8
0
def getColorDict():
    """get the colors that already exist from the opened Document and return a dictionary"""
    scribus.statusMessage("Reading existing colors...")
    colornames = scribus.getColorNames()
    scribus.progressTotal(len(colornames))
    i = 0
    colordict = {}
    for name in colornames:
        colordict[name] = None
        i = i + 1
        scribus.progressSet(i)
    return colordict  #we can ask this dict if the color already exists
def main(argv):

	rectColor = "Black"
	topMargin, leftMargin, rightMargin, bottomMargin = scribus.getPageMargins()
	pageWidth, pageHeight = scribus.getPageSize()
	printAreaWidth  = pageWidth  - leftMargin - rightMargin
	printAreaHeight = pageHeight - topMargin  - bottomMargin

	vertRectW = random.randrange(2,4)
	vertRectH = random.randrange(48,50)
	horRectW = random.randrange(47,49)
	horRectH = random.randrange(2,5)

	startx = leftMargin
	endx = pageWidth - leftMargin - horRectW
	starty = topMargin
	endy = pageHeight - topMargin - vertRectH

	numberRectVert = random.randrange(400,600)
	numberRectHor = random.randrange(400,600)
	opacity = 0

	scribus.progressTotal(numberRectVert+numberRectHor)
	scribus.setRedraw(False)

	for i in range(1, numberRectVert):
		opacity = opacity + 0.002
		xpos = random.randrange(int(startx),int(endx))
		ypos = random.randrange(int(starty),int(endy))
		rect = scribus.createRect(xpos, ypos, vertRectW, vertRectH)
		scribus.setFillColor(rectColor, rect)
		scribus.setLineColor("None", rect) 
		if opacity < 1:
			scribus.setFillTransparency(opacity, rect) 
		scribus.progressSet(i*2)


	for i in range(1, numberRectVert):
		opacity = opacity + 0.002
		xpos = random.randrange(int(startx),int(endx))
		ypos = random.randrange(int(starty),int(endy))
		recthor = scribus.createRect(xpos, ypos, horRectW, horRectH)
		scribus.setFillColor(rectColor, recthor)
		scribus.setLineColor("None", recthor) 
		if opacity < 1:
			scribus.setFillTransparency(opacity, recthor)

	scribus.progressReset()
	scribus.docChanged(True)
	scribus.statusMessage("Done")
	scribus.setRedraw(True)
Beispiel #10
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()
Beispiel #11
0
 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
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()
Beispiel #13
0
def importColors(colorlist):
    """check if colors exists an import"""
    colordict = getColorDict()
    scribus.statusMessage("Defining new colors...")
    scribus.progressTotal(len(colorlist))
    i = 0
    for color in colorlist:
        name = color[0]
        c = color[1]
        m = color[2]
        y = color[3]
        k = color[4]
        while name in colordict:  # check if color already exists - then add PREFIX to name
            name = PREFIX + name

        scribus.defineColorCMYK(name, c, m, y, k)
        i = i + 1
        scribus.progressSet(i)
Beispiel #14
0
def importColors(colorlist):
        """check if colors exists an import"""
        colordict=getColorDict()
        scribus.statusMessage("Defining new colors...")
        scribus.progressTotal(len(colorlist))
        i=0
        for color in colorlist:
            name=color[0]
            c=color[1]
            m=color[2]
            y=color[3]
            k=color[4]
            while colordict.has_key(name):# check if color already exists - then add PREFIX to name
                name = PREFIX+name
            
            scribus.defineColor(name, c, m, y, k)
            i=i+1
            scribus.progressSet(i)
def add_songs(all_songs, songs_double_page, manual_processing, songs_data,
              cache):
    # let's get the best sorting
    songs_combined = simplebin.best_fit(all_songs, EFFECTIVE_PAGE_HEIGHT)
    # sorting the songs alphabetic
    songs_sorted = sorted(songs_combined, key=lambda x: x[0])

    # make sure the double page will be added on the left side
    page_num = scribus.pageCount()
    for double_page in songs_double_page:
        if not double_page in all_songs:
            continue
        offset = songs_sorted.index([double_page])
        songs_sorted.insert(offset + 1,
                            None)  # add a empty page after the song
        if (page_num + offset
            ) % 2 != 0:  # song is on right side, empty side on the left side.
            songs_sorted.insert(
                offset,
                songs_sorted.pop(offset +
                                 2))  # move next song before the double page
            # TODO: what if double sided song is last song?

    for songs in songs_sorted:
        current_pos = 0
        if songs == None:  # we added this for a song that should be set on double page
            new_page()
            continue
        for filename in songs:
            if not manual_processing[filename].get("show", True):
                continue
            data = songs_data[filename]
            height, page_num = load_song(data, current_pos,
                                         manual_processing[filename])
            current_pos += math.ceil(height / BASELINE_GRID) * BASELINE_GRID
            cache[filename]["height"] = round(height, 2)
            cache[filename]["page"] = page_num
            scribus.progressSet(1)
        if current_pos != 0:
            new_page()
Beispiel #16
0
def createChart():
    """actually handles the whole chart creation process"""
    prepareDocument()
    # get page size
    pageSize=scribus.getPageSize()
    pageWidth=pageSize[0]
    pageHeight=pageSize[1]
    #pageMargins
    pageMargins=scribus.getPageMargins()
    topMargin=pageMargins[0]
    leftMargin=pageMargins[1]
    rightMargin=pageMargins[2]
    bottomMargin=pageMargins[3]

    #color field dimensions
    colorFieldWidth= pageWidth - leftMargin - rightMargin - (TEXT_BOX_WIDTH+HSPACE) #50+5 is the with of the textbox plus the space between textbox and colorfield

    #how much space does one field use?
    vSpaceUsedByField = COLOR_FIELD_HEIGHT+VSPACE

    #how much space is available per row?
    vSpaceAvailable=pageHeight-topMargin-bottomMargin-HEADERSIZE-FOOTERSIZE

    #counts the colorFields created for a page. reset this variable after creation of new page
    colorFieldCounter=0

    #get list of all colors in document
    colorList = scribus.getColorNames()
    #prepare the progressbar
    colorNumber=len(colorList)
    scribus.progressTotal(colorNumber)
    #@TODO: implement possibility to abort script (button2=scribus.BUTTON_CANCEL) buttons should return int 1 or 2
    #scribus.messageBox("ColorChart Script by Sebastian Stetter", "...going to create a chart of "+str(colorNumber)+" colors.\n This may take a while.",  button1 = scribus.BUTTON_OK)
    scribus.statusMessage("Drawing color fields...")
    stepCompleted=0
    #disable redrawing for better performance
    scribus.setRedraw(False)
    for color in colorList:
        if (vSpaceUsedByField * (colorFieldCounter+1)) <= vSpaceAvailable:
            # when there is enought space left draw a color field...

            #calculate Position for new colorField
            h=leftMargin
            v=topMargin + (vSpaceUsedByField * colorFieldCounter)+HEADERSIZE
            #draw the colorField
            drawColor(color, h, v,  colorFieldWidth, COLOR_FIELD_HEIGHT)
            colorFieldCounter = colorFieldCounter+1
            #update progressbar
            stepCompleted = stepCompleted+1
            scribus.progressSet(stepCompleted)
        else:
            #not enough space? create a new page!
            createPage()
            #reset the colorFieldCounter to '0' since we created a new page
            colorFieldCounter = 0
            h=leftMargin
            v=topMargin + (vSpaceUsedByField * colorFieldCounter)+HEADERSIZE
            drawColor(color, h, v,  colorFieldWidth, COLOR_FIELD_HEIGHT)
            colorFieldCounter = colorFieldCounter+1

            #update progressbar
            stepCompleted = stepCompleted+1
            scribus.progressSet(stepCompleted)

    #make shure pages are redrawn
    scribus.setRedraw(True)
Beispiel #17
0
def main(argv):

    scribus.setUnit(scribus.UNIT_MILLIMETERS)

    # get page size
    pagesize = scribus.getPageSize()

    ###########################################

    # size and position of the exit buttons
    linksize = pagesize[0] / 30
    linkpos = pagesize[0] - linksize - 2

    # set up exit to page
    pagenum = scribus.pageCount()
    exittopage = scribus.valueDialog(
        "Exit to page",
        "Exit buttons should go to page (1-" + str(pagenum) + ") :", "1")

    #error
    #if exittopage > pagenum:
    #    scribus.messageBox("Error", "This page doesn't exist.")
    #    sys.exit()

    # get active layer, create new layer for exit buttons, set it as active
    activelayer = scribus.getActiveLayer()
    scribus.createLayer("Exitbuttons")
    scribus.setActiveLayer("Exitbuttons")

    #progressbar max
    scribus.progressTotal(pagenum)

    # iterate through all the pages
    page = 1
    while (page <= pagenum):

        #messagebar text
        scribus.messagebarText("Create exit buttons...")

        scribus.progressSet(page)
        scribus.gotoPage(page)

        # create rectangle
        exitrect = scribus.createRect(linkpos, 2, linksize, linksize,
                                      "exitrect" + str(page))
        scribus.setFillColor("White", exitrect)

        # create text in rectangle
        exittext = scribus.createText(linkpos, 4, linksize, linksize,
                                      "exittext" + str(page))

        scribus.setText("X", exittext)
        scribus.setFontSize(20, exittext)
        scribus.setTextAlignment(1, exittext)

        # create link annotation
        exitlink = scribus.createText(linkpos, 2, linksize, linksize,
                                      "exitlink" + str(page))
        #setLinkAnnotation(page,x,y,["name"])
        scribus.setLinkAnnotation(int(exittopage), 0, 0, exitlink)

        # add page number to iteration
        page += 1

    # go back to active layer
    scribus.setActiveLayer(activelayer)
def main(argv):

    ###########################################

    scribus.newDocDialog()

    if scribus.haveDoc:
        scribus.setUnit(scribus.UNIT_MILLIMETERS)
        (w, h) = scribus.getPageSize()

        ###################

        # ask for workdir
        workdir = scribus.fileDialog("Open directory with images",
                                     "",
                                     haspreview=False,
                                     issave=False,
                                     isdir=True)
        #workdir = "/media/sda7/StudioSession3/PDFTools/pics"
        #workdir = "/media/sda7/ISG/Itex/PhotoVisit/Boilerroom"

        # file filter
        filefilter = scribus.valueDialog(
            "File filter",
            "File filter examples: \n\n* or *.* = add all files\n*.jpg = add .jpg files only\nIMG_*.* = add all files starting with IMG_\n\nThis filter is case sensitive!",
            "*.*")

        # get image paths
        filelist = sorted(glob.glob(os.path.join(workdir, filefilter)))
        #scribus.messageBox("Help", str(filelist))

        # count files
        filesinworkdir = len(filelist)
        #scribus.messageBox("Help", str(filesinworkdir))

        #messagebar text
        scribus.messagebarText("Importing images...")

        #error
        if filesinworkdir == 0:
            scribus.messageBox("Error", "This directory is empty.")
            sys.exit()

        # add filename text?
        addfilenames = scribus.messageBox("Import images",
                                          "Files found in workdir : " +
                                          str(filesinworkdir) +
                                          "\n\nAdd file names to images?",
                                          button1=scribus.BUTTON_YES,
                                          button2=scribus.BUTTON_NO)

        #create text layer
        if addfilenames == 16384:
            activelayer = scribus.getActiveLayer()
            scribus.createLayer("Filenames")
            scribus.setActiveLayer(activelayer)

        #progressbar max
        scribus.progressTotal(filesinworkdir)

        page = 1

        #create page, add and load image
        for i in filelist:
            scribus.progressSet(page)

            scribus.gotoPage(page)
            scribus.createImage(0, 0, w, h, "imagename" + str(page))
            scribus.loadImage(filelist[page - 1], "imagename" + str(page))
            scribus.setScaleImageToFrame(True,
                                         proportional=True,
                                         name="imagename" + str(page))
            #scribus.setImageOffset(0, 0, "imagename"+str(page))
            #scribus.setScaleFrameToImage(name="imagename"+str(page))

            # add filename on page?
            if addfilenames == 16384:
                scribus.setActiveLayer("Filenames")
                filename = scribus.createText(2, 2, 50, 10, filelist[page - 1])
                scribus.setText(os.path.basename(filelist[page - 1]), filename)
                scribus.setTextColor("White", filename)
                scribus.setActiveLayer(activelayer)

            scribus.newPage(-1)
            page += 1

        #delete last blank page
        scribus.deletePage(filesinworkdir + 1)
Beispiel #19
0

# open CSV file
data = getCSVdata(delim=delim, qc=qc)

# Process data
scribus.messagebarText("Processing "+str(nol)+" elements")
scribus.progressTotal(len(data))
for row in data:
    scribus.messagebarText("Processing "+str(nol)+" elements")
    celltext = row[numcol].strip()
    if len(celltext)!=0:
        createCell(celltext, cr, cc, CARDWIDTH, CARDHEIGHT, MARGINS[0], MARGINS[2], isBlack)
        nol=nol+1
        if cr==colstotal and cc==rowstotal:
            #create new page
            scribus.newPage(-1)
            scribus.gotoPage(scribus.pageCount())
            cr=1
            cc=1
        else:
            if cr==colstotal:
                cr=1
                cc=cc+1
            else:
                cr=cr+1
        scribus.progressSet(nol)
scribus.messagebarText("Processed "+str(nol)+" items. ")
scribus.progressReset()

Beispiel #20
0
    def main (self) :

        # Load up all the file and record information.
        # Use CSV reader to build list of record dicts
        records         = self.loadCSVData(self.dataFile)
        totalRecs       = len(records)

        # Reality check first to see if we have anything to process
        if totalRecs <= 0 :
            scribus.messageBox('Not Found', 'No records found to process!')
            sys.exit()

        pageNumber      = 1
        recCount        = 0
        row             = 0
        pageSide        = 'Odd'
        scribus.progressTotal(totalRecs)
        paIndex         = {}
        lastName        = ''
        firstName       = ''
        photoFirstName  = ''
        verseRef        = ''
        verseText       = ''

        # Get the page layout coordinates for this publication
        crds = self.getCoordinates(self.dimensions)

        # Make a new document to put our records on
        if scribus.newDocument(getattr(scribus, self.dimensions['page']['scribusPageCode']), 
                    (self.dimensions['margins']['left'], self.dimensions['margins']['right'], self.dimensions['margins']['top'], self.dimensions['margins']['bottom']),
                        scribus.PORTRAIT, 1, scribus.UNIT_POINTS, scribus.NOFACINGPAGES, 
                            scribus.FIRSTPAGERIGHT, 1) :

            self.setPageNumber(crds, pageSide, row, pageNumber)

            while recCount < totalRecs :

                # Output a new page on the first row after we have done the first page
                if row == 0 and recCount != 0:
                    scribus.newPage(-1)
                    if pageSide == 'Odd' :
                        pageSide = 'Even'
                    else :
                        pageSide = 'Odd'

                    self.setPageNumber(crds, pageSide, row, pageNumber)

                ########### Now set the current record in the current row ##########

                # Set the last name
                lastName = records[recCount]['NameLast']

                # Adjust the NameFirst field to include the spouse if there is one
                if records[recCount]['Spouse'] != '' :
                    firstName = records[recCount]['NameFirst'] + ' & ' + records[recCount]['Spouse']
                else :
                    firstName = records[recCount]['NameFirst']
                    
                # Make the photo file name
                photoFirstName = firstName.replace('&', '-').replace('.', '').replace(' ', '')

                # Set our record count for progress display and send a status message
                scribus.progressSet(recCount)
                scribus.statusMessage('Placing record ' + `recCount` + ' of ' + `totalRecs`)

                # Add a watermark if a string is specified
                if self.outputWatermark :
                    self.addWatermark()

                # Put the last name element in this row
                nameLastBox = scribus.createText(crds[row]['nameLastXPos'], crds[row]['nameLastYPos'], crds[row]['nameLastWidth'], crds[row]['nameLastHeight'])
                scribus.setText(lastName, nameLastBox)
                scribus.setTextAlignment(scribus.ALIGN_RIGHT, nameLastBox)
                scribus.setTextDistances(0, 0, 0, 0, nameLastBox)
                scribus.setFont(self.fonts['nameLast']['bold'], nameLastBox)
                scribus.setFontSize(self.fonts['nameLast']['size'], nameLastBox)
                scribus.setTextShade(80, nameLastBox)
                scribus.rotateObject(90, nameLastBox)

                # Place the first name element in this row
                nameFirstBox = scribus.createText(crds[row]['nameFirstXPos'], crds[row]['nameFirstYPos'], crds[row]['nameFirstWidth'], crds[row]['nameFirstHeight'])
                scribus.setText(records[recCount]['Caption'], nameFirstBox)
                scribus.setTextAlignment(scribus.ALIGN_LEFT, nameFirstBox)
                scribus.setFont(self.fonts['nameFirst']['boldItalic'], nameFirstBox)
                scribus.setFontSize(self.fonts['nameFirst']['size'], nameFirstBox)

                # Place the image element in this row
                # We will need to do some processing on the first pass
                # The default output format is JPG
                orgImgFileName = records[recCount]['Photo']
                orgImgFile = os.path.join(self.orgImgDir, orgImgFileName)
                baseImgFileName = lastName + '_' + photoFirstName
                if self.willBePngImg :
                    ext = 'png'
                else :
                    ext = 'jpg'
                if not self.rgbColor :
                    imgFile = os.path.join(getattr(self, ext + 'ImgDir'), baseImgFileName + '-gray' + '.' + ext)
                else :
                    imgFile = os.path.join(getattr(self, ext + 'ImgDir'), baseImgFileName + '.' + ext)

                # Process the image now if there is none
                if not os.path.exists(imgFile) :
                    self.img_process.sizePic(orgImgFile, imgFile, self.maxHeight)
#                    self.img_process.outlinePic(imgFile, imgFile)
                    self.img_process.scalePic(imgFile, imgFile, self.imgDensity)
                    self.img_process.addPoloroidBorder(imgFile, imgFile)
                    # Color RGB is the default
                    if not self.rgbColor :
                        self.img_process.makeGray(imgFile, imgFile)

                # Double check the output and substitute with placeholder pic
                if not os.path.exists(imgFile) :
                    imgFile = self.placeholderPic
                # Create the imageBox and load the picture
                imageBox = scribus.createImage(crds[row]['imageXPos'], crds[row]['imageYPos'], crds[row]['imageWidth'], crds[row]['imageHeight'])
                if os.path.isfile(imgFile) :
                    scribus.loadImage(imgFile, imageBox)
                scribus.setScaleImageToFrame(scaletoframe=1, proportional=1, name=imageBox)

                # Place the country element in this row (add second one if present)
                countryBox = scribus.createText(crds[row]['countryXPos'], crds[row]['countryYPos'], crds[row]['countryWidth'], crds[row]['countryHeight'])
                countryLine = records[recCount]['Country1']
                try :
                    if records[recCount]['Country2'] != '' :
                        countryLine = countryLine + ' & ' + records[recCount]['Country2']
                except :
                    pass
                scribus.setText(countryLine, countryBox)
                scribus.setTextAlignment(scribus.ALIGN_RIGHT, countryBox)
                scribus.setFont(self.fonts['text']['boldItalic'], countryBox)
                scribus.setFontSize(self.fonts['text']['size'], countryBox)

                # Place the assignment element in this row
                assignBox = scribus.createText(crds[row]['assignXPos'], crds[row]['assignYPos'], crds[row]['assignWidth'], crds[row]['assignHeight'])
                scribus.setText(self.fixText(records[recCount]['Assignment']), assignBox)
                # Assign style to box
#                scribus.createParagraphStyle(name='assignStyle', alignment=0, leftmargin=10, firstindent=-10)
#                scribus.setStyle('assignStyle', assignBox)
                # Hard formated box
                scribus.setTextAlignment(scribus.ALIGN_LEFT, assignBox)
                scribus.setFont(self.fonts['text']['italic'], assignBox)
                scribus.setFontSize(self.fonts['text']['size'], assignBox)
                scribus.setLineSpacing(self.fonts['text']['size'] + 1, assignBox)
                scribus.setTextDistances(4, 0, 0, 0, assignBox)
                # Resize the frame height and determine the difference for
                # placing the next frame below it
                assignHeightNew = self.resizeFrame(assignBox)
                assignHeightDiff = crds[row]['assignHeight'] - assignHeightNew

                # Place the verse element in this row
                verseYPosNew = crds[row]['verseYPos'] - assignHeightDiff
                verseBox = scribus.createText(crds[row]['verseXPos'], verseYPosNew, crds[row]['verseWidth'], crds[row]['verseHeight'])
                # The verse element may be either a Scripture verse or a prayer request
                # If it is Scripture, and it has a verse ref, we want to set that
                # seperatly so we need to do a little preprocess on the text to find
                # out if it has a ref. This script will only recognize references
                # at the end of the string that are enclosed in brackets. See the
                # findVerseRef() function for more details
                verseRef = self.findVerseRef(records[recCount]['Prayer'])
                if verseRef :
                    verseText = self.removeVerseRef(self.fixText(records[recCount]['Prayer']))
                    scribus.setText(verseText, verseBox)
                else :
                    scribus.setText(self.fixText(records[recCount]['Prayer']), verseBox)
                # Can't find a way to set alignment to justified using setTextAlignment()
#                scribus.setTextAlignment(scribus.ALIGN_LEFT, verseBox)
                # Because of this, we make a style which seems to work
                scribus.createParagraphStyle(name='vBoxStyle', alignment=3)
                scribus.setStyle('vBoxStyle', verseBox)
                scribus.setFont(self.fonts['verse']['regular'], verseBox)
                scribus.setFontSize(self.fonts['verse']['size'], verseBox)
                scribus.setLineSpacing(self.fonts['verse']['size'] + 1, verseBox)
                scribus.setTextDistances(4, 0, 4, 0, verseBox)
                if self.hyphenate :
                    scribus.hyphenateText(verseBox)
                # Get the height difference in case we need to set ref box
                verseHeightNew = self.resizeFrame(verseBox)
                verseHeightDiff = crds[row]['verseHeight'] - verseHeightNew
                if verseRef :
                    # Set coordinates for this box
                    vRefBoxX = crds[row]['verseXPos']
                    vRefBoxY = (verseYPosNew + verseHeightNew)
                    vRefBoxH = crds[row]['nameFirstHeight'] / 2
                    vRefBoxW = crds[row]['verseWidth']
                    verseRefBox = scribus.createText(vRefBoxX, vRefBoxY, vRefBoxW, vRefBoxH)
                    scribus.setText(verseRef, verseRefBox)
                    scribus.setTextAlignment(scribus.ALIGN_RIGHT, verseRefBox)
                    scribus.setFont(self.fonts['verse']['italic'], verseRefBox)
                    scribus.setFontSize(self.fonts['verse']['size'] - 2, verseRefBox)
                    scribus.setLineSpacing(self.fonts['verse']['size'], verseRefBox)
                    scribus.setTextDistances(2, 0, 0, 0, verseRefBox)

                # Up our counts
                if row >= self.dimensions['rows']['count'] - 1 :
                    row = 0
                    pageNumber +=1
                else :
                    row +=1
                    
                recCount +=1

            # Create the index page here
            # Output a new page for the index
            if row == 0 and recCount != 0:
                scribus.newPage(-1)
                if pageSide == 'Odd' :
                    pageSide = 'Even'
                else :
                    pageSide = 'Odd'

                self.setPageNumber(crds, pageSide, 0, pageNumber)

        # Outut the index entries at this point
#        for key in paIndex.keys() :

        # Report we are done now before we loose focus
        scribus.statusMessage('Process Complete!')

###############################################################################
############################## Output Results #################################
###############################################################################

        # Now we will output the results to PDF if that is desired
        if self.makePdf :
            pdfExport =  scribus.PDFfile()
            pdfExport.info = self.pdfFile
            pdfExport.file = self.pdfFile
            pdfExport.save()

        # View the output if set
        if self.makePdf and self.viewPdf :
            cmd = ['evince', self.pdfFile]
            try :
                subprocess.Popen(cmd)
            except Exception as e :
                result = scribus.messageBox ('View PDF command failed with: ' + str(e), scribus.BUTTON_OK)
Beispiel #21
0
    def main(self):

        # Load up all the file and record information.
        # Use CSV reader to build list of record dicts
        records = self.loadCSVData(self.dataFile)
        totalRecs = len(records)

        # Reality check first to see if we have anything to process
        if totalRecs <= 0:
            scribus.messageBox('Not Found', 'No records found to process!')
            sys.exit()

        pageNumber = 1
        recCount = 0
        row = 0
        pageSide = 'Odd'
        scribus.progressTotal(totalRecs)
        paIndex = {}
        lastName = ''
        firstName = ''
        photoFirstName = ''
        verseRef = ''
        verseText = ''

        # Get the page layout coordinates for this publication
        crds = self.getCoordinates(self.dimensions)

        # Make a new document to put our records on
        if scribus.newDocument(
                getattr(scribus, self.dimensions['page']['scribusPageCode']),
            (self.dimensions['margins']['left'],
             self.dimensions['margins']['right'],
             self.dimensions['margins']['top'],
             self.dimensions['margins']['bottom']), scribus.PORTRAIT, 1,
                scribus.UNIT_POINTS, scribus.NOFACINGPAGES,
                scribus.FIRSTPAGERIGHT, 1):

            self.setPageNumber(crds, pageSide, row, pageNumber)

            while recCount < totalRecs:

                # Output a new page on the first row after we have done the first page
                if row == 0 and recCount != 0:
                    scribus.newPage(-1)
                    if pageSide == 'Odd':
                        pageSide = 'Even'
                    else:
                        pageSide = 'Odd'

                    self.setPageNumber(crds, pageSide, row, pageNumber)

                ########### Now set the current record in the current row ##########

                # Set the last name
                lastName = records[recCount]['NameLast']

                # Adjust the NameFirst field to include the spouse if there is one
                if records[recCount]['Spouse'] != '':
                    firstName = records[recCount][
                        'NameFirst'] + ' & ' + records[recCount]['Spouse']
                else:
                    firstName = records[recCount]['NameFirst']

                # Make the photo file name
                photoFirstName = firstName.replace('&', '-').replace(
                    '.', '').replace(' ', '')

                # Set our record count for progress display and send a status message
                scribus.progressSet(recCount)
                scribus.statusMessage('Placing record ' + ` recCount ` +
                                      ' of ' + ` totalRecs `)

                # Add a watermark if a string is specified
                if self.outputWatermark:
                    self.addWatermark()

                # Put the last name element in this row
                nameLastBox = scribus.createText(crds[row]['nameLastXPos'],
                                                 crds[row]['nameLastYPos'],
                                                 crds[row]['nameLastWidth'],
                                                 crds[row]['nameLastHeight'])
                scribus.setText(lastName, nameLastBox)
                scribus.setTextAlignment(scribus.ALIGN_RIGHT, nameLastBox)
                scribus.setTextDistances(0, 0, 0, 0, nameLastBox)
                scribus.setFont(self.fonts['nameLast']['bold'], nameLastBox)
                scribus.setFontSize(self.fonts['nameLast']['size'],
                                    nameLastBox)
                scribus.setTextShade(80, nameLastBox)
                scribus.rotateObject(90, nameLastBox)

                # Place the first name element in this row
                nameFirstBox = scribus.createText(crds[row]['nameFirstXPos'],
                                                  crds[row]['nameFirstYPos'],
                                                  crds[row]['nameFirstWidth'],
                                                  crds[row]['nameFirstHeight'])
                scribus.setText(records[recCount]['Caption'], nameFirstBox)
                scribus.setTextAlignment(scribus.ALIGN_LEFT, nameFirstBox)
                scribus.setFont(self.fonts['nameFirst']['boldItalic'],
                                nameFirstBox)
                scribus.setFontSize(self.fonts['nameFirst']['size'],
                                    nameFirstBox)

                # Place the image element in this row
                # We will need to do some processing on the first pass
                # The default output format is JPG
                orgImgFileName = records[recCount]['Photo']
                orgImgFile = os.path.join(self.orgImgDir, orgImgFileName)
                baseImgFileName = lastName + '_' + photoFirstName
                if self.willBePngImg:
                    ext = 'png'
                else:
                    ext = 'jpg'
                if not self.rgbColor:
                    imgFile = os.path.join(
                        getattr(self, ext + 'ImgDir'),
                        baseImgFileName + '-gray' + '.' + ext)
                else:
                    imgFile = os.path.join(getattr(self, ext + 'ImgDir'),
                                           baseImgFileName + '.' + ext)

                # Process the image now if there is none
                if not os.path.exists(imgFile):
                    self.img_process.sizePic(orgImgFile, imgFile,
                                             self.maxHeight)
                    #                    self.img_process.outlinePic(imgFile, imgFile)
                    self.img_process.scalePic(imgFile, imgFile,
                                              self.imgDensity)
                    self.img_process.addPoloroidBorder(imgFile, imgFile)
                    # Color RGB is the default
                    if not self.rgbColor:
                        self.img_process.makeGray(imgFile, imgFile)

                # Double check the output and substitute with placeholder pic
                if not os.path.exists(imgFile):
                    imgFile = self.placeholderPic
                # Create the imageBox and load the picture
                imageBox = scribus.createImage(crds[row]['imageXPos'],
                                               crds[row]['imageYPos'],
                                               crds[row]['imageWidth'],
                                               crds[row]['imageHeight'])
                if os.path.isfile(imgFile):
                    scribus.loadImage(imgFile, imageBox)
                scribus.setScaleImageToFrame(scaletoframe=1,
                                             proportional=1,
                                             name=imageBox)

                # Place the country element in this row (add second one if present)
                countryBox = scribus.createText(crds[row]['countryXPos'],
                                                crds[row]['countryYPos'],
                                                crds[row]['countryWidth'],
                                                crds[row]['countryHeight'])
                countryLine = records[recCount]['Country1']
                try:
                    if records[recCount]['Country2'] != '':
                        countryLine = countryLine + ' & ' + records[recCount][
                            'Country2']
                except:
                    pass
                scribus.setText(countryLine, countryBox)
                scribus.setTextAlignment(scribus.ALIGN_RIGHT, countryBox)
                scribus.setFont(self.fonts['text']['boldItalic'], countryBox)
                scribus.setFontSize(self.fonts['text']['size'], countryBox)

                # Place the assignment element in this row
                assignBox = scribus.createText(crds[row]['assignXPos'],
                                               crds[row]['assignYPos'],
                                               crds[row]['assignWidth'],
                                               crds[row]['assignHeight'])
                scribus.setText(self.fixText(records[recCount]['Assignment']),
                                assignBox)
                # Assign style to box
                #                scribus.createParagraphStyle(name='assignStyle', alignment=0, leftmargin=10, firstindent=-10)
                #                scribus.setStyle('assignStyle', assignBox)
                # Hard formated box
                scribus.setTextAlignment(scribus.ALIGN_LEFT, assignBox)
                scribus.setFont(self.fonts['text']['italic'], assignBox)
                scribus.setFontSize(self.fonts['text']['size'], assignBox)
                scribus.setLineSpacing(self.fonts['text']['size'] + 1,
                                       assignBox)
                scribus.setTextDistances(4, 0, 0, 0, assignBox)
                # Resize the frame height and determine the difference for
                # placing the next frame below it
                assignHeightNew = self.resizeFrame(assignBox)
                assignHeightDiff = crds[row]['assignHeight'] - assignHeightNew

                # Place the verse element in this row
                verseYPosNew = crds[row]['verseYPos'] - assignHeightDiff
                verseBox = scribus.createText(crds[row]['verseXPos'],
                                              verseYPosNew,
                                              crds[row]['verseWidth'],
                                              crds[row]['verseHeight'])
                # The verse element may be either a Scripture verse or a prayer request
                # If it is Scripture, and it has a verse ref, we want to set that
                # seperatly so we need to do a little preprocess on the text to find
                # out if it has a ref. This script will only recognize references
                # at the end of the string that are enclosed in brackets. See the
                # findVerseRef() function for more details
                verseRef = self.findVerseRef(records[recCount]['Prayer'])
                if verseRef:
                    verseText = self.removeVerseRef(
                        self.fixText(records[recCount]['Prayer']))
                    scribus.setText(verseText, verseBox)
                else:
                    scribus.setText(self.fixText(records[recCount]['Prayer']),
                                    verseBox)
                # Can't find a way to set alignment to justified using setTextAlignment()
#                scribus.setTextAlignment(scribus.ALIGN_LEFT, verseBox)
# Because of this, we make a style which seems to work
                scribus.createParagraphStyle(name='vBoxStyle', alignment=3)
                scribus.setStyle('vBoxStyle', verseBox)
                scribus.setFont(self.fonts['verse']['regular'], verseBox)
                scribus.setFontSize(self.fonts['verse']['size'], verseBox)
                scribus.setLineSpacing(self.fonts['verse']['size'] + 1,
                                       verseBox)
                scribus.setTextDistances(4, 0, 4, 0, verseBox)
                if self.hyphenate:
                    scribus.hyphenateText(verseBox)
                # Get the height difference in case we need to set ref box
                verseHeightNew = self.resizeFrame(verseBox)
                verseHeightDiff = crds[row]['verseHeight'] - verseHeightNew
                if verseRef:
                    # Set coordinates for this box
                    vRefBoxX = crds[row]['verseXPos']
                    vRefBoxY = (verseYPosNew + verseHeightNew)
                    vRefBoxH = crds[row]['nameFirstHeight'] / 2
                    vRefBoxW = crds[row]['verseWidth']
                    verseRefBox = scribus.createText(vRefBoxX, vRefBoxY,
                                                     vRefBoxW, vRefBoxH)
                    scribus.setText(verseRef, verseRefBox)
                    scribus.setTextAlignment(scribus.ALIGN_RIGHT, verseRefBox)
                    scribus.setFont(self.fonts['verse']['italic'], verseRefBox)
                    scribus.setFontSize(self.fonts['verse']['size'] - 2,
                                        verseRefBox)
                    scribus.setLineSpacing(self.fonts['verse']['size'],
                                           verseRefBox)
                    scribus.setTextDistances(2, 0, 0, 0, verseRefBox)

                # Up our counts
                if row >= self.dimensions['rows']['count'] - 1:
                    row = 0
                    pageNumber += 1
                else:
                    row += 1

                recCount += 1

            # Create the index page here
            # Output a new page for the index
            if row == 0 and recCount != 0:
                scribus.newPage(-1)
                if pageSide == 'Odd':
                    pageSide = 'Even'
                else:
                    pageSide = 'Odd'

                self.setPageNumber(crds, pageSide, 0, pageNumber)

        # Outut the index entries at this point
#        for key in paIndex.keys() :

# Report we are done now before we loose focus
        scribus.statusMessage('Process Complete!')

        ###############################################################################
        ############################## Output Results #################################
        ###############################################################################

        # Now we will output the results to PDF if that is desired
        if self.makePdf:
            pdfExport = scribus.PDFfile()
            pdfExport.info = self.pdfFile
            pdfExport.file = self.pdfFile
            pdfExport.save()

        # View the output if set
        if self.makePdf and self.viewPdf:
            cmd = ['evince', self.pdfFile]
            try:
                subprocess.Popen(cmd)
            except Exception as e:
                result = scribus.messageBox(
                    'View PDF command failed with: ' + str(e),
                    scribus.BUTTON_OK)
Beispiel #22
0
def main():
    colstotal = get_multipl(WIDTH, CARDWIDTH, MARGINS[0], MARGINS[1])
    rowstotal = get_multipl(HEIGHT, CARDHEIGHT, MARGINS[2], MARGINS[3])

    # create a new document
    t = scribus.newDocument(
        (WIDTH, HEIGHT),
        MARGINS,
        scribus.PORTRAIT,
        1,
        scribus.UNIT_MILLIMETERS,
        scribus.FACINGPAGES,
        scribus.FIRSTPAGERIGHT,
        1,
    )
    cr = 1
    cc = 1
    nol = 0

    # ask for CSV infos
    tstr = scribus.valueDialog(
        'Cvs Delimiter, Quote and Column to process',
        'Type 1 delimiter, 1 quote character '
        'and the column number (Clear for default ,"0):',
        ';"0',
    )
    if len(tstr) > 0:
        delim = tstr[0]
    else:
        delim = ','
    if len(tstr) > 1:
        qc = tstr[1]
    else:
        qc = '"'
    if len(tstr) > 2:
        numcol = int(tstr[2])
    else:
        numcol = 0

    # select black or white cards
    color = scribus.valueDialog(
        'Color of the cards :',
        'black (b) or white (w)',
        'w',
    )
    if len(color) > 0 and 'b' == color[0]:
        is_black = True
    else:
        is_black = False

    # open CSV file
    data = getCSVdata(delim=delim, qc=qc)

    # Process data
    scribus.messagebarText("Processing " + str(nol) + " elements")
    scribus.progressTotal(len(data))
    for row in data:
        scribus.messagebarText("Processing " + str(nol) + " elements")
        celltext = row[numcol].strip()
        if len(celltext) != 0:
            createCell(
                celltext,
                cr,
                cc,
                CARDWIDTH,
                CARDHEIGHT,
                MARGINS[0],
                MARGINS[2],
                is_black,
            )
            nol = nol + 1
            if cr == colstotal and cc == rowstotal:
                #create new page
                scribus.newPage(-1)
                scribus.gotoPage(scribus.pageCount())
                cr = 1
                cc = 1
            else:
                if cr == colstotal:
                    cr = 1
                    cc = cc + 1
                else:
                    cr = cr + 1
            scribus.progressSet(nol)
    scribus.messagebarText("Processed " + str(nol) + " items. ")

    # open CSV file
    data = getCSVdata(delim=delim, qc=qc)

    # Process data
    scribus.messagebarText("Processing " + str(nol) + " elements")
    scribus.progressReset()
    scribus.progressTotal(len(data))
    nol = 0
    cr = 1
    cc = cc + 2
    for row in data:
        scribus.messagebarText("Processing " + str(nol) + " elements")
        celltext = row[numcol].strip()
        if len(celltext) != 0:
            createCell(
                celltext,
                cr,
                cc,
                CARDWIDTH,
                CARDHEIGHT,
                MARGINS[0],
                MARGINS[2],
                is_black=True,
            )
            nol = nol + 1
            if cr == colstotal and cc == rowstotal:
                #create new page
                scribus.newPage(-1)
                scribus.gotoPage(scribus.pageCount())
                cr = 1
                cc = 1
            else:
                if cr == colstotal:
                    cr = 1
                    cc = cc + 1
                else:
                    cr = cr + 1
            scribus.progressSet(nol)
    scribus.messagebarText("Processed " + str(nol) + " items. ")
    scribus.progressReset()
def importSocietes(filename, fileCat, iPro):
    arrLines=[]#liste de lignes du fichier csv, chaque ligne est une liste de champs 
    mapCol={}#table de correspondance entre les champs à importer et les numéros de colonne du fichier csv
    mapCat={}#table de correspondance entre numéro de catégorie et nom de catégorie
    nbCat=readSocietes(filename, fileCat, mapCat, arrLines, mapCol)
    (nbChg, nbPro)=(0,0)
    numPro=1
    while scribus.getTextLength("txtPros%d" % numPro)>0 and numPro<=NB_TXT:
        numPro+=1
    if iPro==1 and scribus.objectExists("txtBureauxChange"):
        scribus.deleteText("txtBureauxChange")

    scribus.progressTotal(len(arrLines))
    strPro="txtPros%d"%numPro
    scribus.statusMessage("Remplissage du cadre de texte %s..."%strPro)
    bFirstPro=True
    strCat="#"
    for record in arrLines:#Pour chaque pro
        # log("nbPro=%d\n"%nbPro)
        if strCat != record[mapCol["cat"]]:#nouvelle categorie
            strCat=record[mapCol["cat"]]
            bNewCat=True
        else:
            bNewCat=False

        nbPro+=1
        if nbPro<iPro:#déjà importé à l'exécution précédente
            continue
        try:
          scribus.progressSet(nbPro)
          if record[mapCol["chg"]]=="True" and scribus.objectExists("txtBureauxChange"):
            try:
                nbCarBureau=scribus.getTextLength("txtBureauxChange")
                appendText(u"● "+toUnicode(record[mapCol["nom"]])+"\n","styleChangeTitre","txtBureauxChange")
                appendText(toUnicode(record[mapCol["adr"]].replace("\\n"," - "))+"\n","styleChangeAdresse","txtBureauxChange")
                appendText(record[mapCol["post"]]+" "+toUnicode(record[mapCol["ville"]].upper()+"\n"),"styleChangeAdresse","txtBureauxChange")
                nbChg+=1
            except Exception as ex:
                scribus.messageBox( "Erreur","Une erreur est survenue sur ce bureau de change: \n%s\n\n%s" %(record, str(ex)))
                sys.exit()
          else :
            nbCarBureau=0

          nbCar=scribus.getTextLength(strPro)
          if bNewCat or bFirstPro:    
            if bFirstPro and not bNewCat:
                appendText(toUnicode(strCat+" (suite)")+"\n","styleProCatSuite",strPro)
            else:
                appendText(toUnicode(strCat)+"\n","styleProCat",strPro)

          bFirstPro=False
          appendText(u"● "+toUnicode(record[mapCol["nom"]])+"\n","styleProTitre",strPro)
          if record[mapCol["chg"]]=="True" :
            appendText(u"\n","styleProBureau",strPro) #icone du bureau de change en police FontAwesome
         
          appendText(processDesc(toUnicode(record[mapCol["desc"]]))+"\n","styleProDesc",strPro)
          if bLivret:
              strAdr=toUnicode(record[mapCol["adr"]].replace("\\n"," - "))+" - " + toUnicode(record[mapCol["post"]])+" "
              strAdr+=processDesc(toUnicode(record[mapCol["ville"]].upper()))
              if record[mapCol["tel"]].strip():
                  strAdr+=" ("+toUnicode(record[mapCol["tel"]].strip().replace(" ","\xC2\xA0"))+")\n" #numéro de téléphone insécable
              else:
                  strAdr+="\n"

              appendText(strAdr, "styleProAdresse", strPro)
          else:
            appendText(toUnicode(record[mapCol["adr"]].replace("\\n"," - "))+"\n","styleProAdresse",strPro)
            appendText(toUnicode(record[mapCol["post"]])+" "+processDesc(toUnicode(record[mapCol["ville"]]).upper())+"\n","styleProAdresse",strPro)
            if record[mapCol["tel"]].strip(): 
                appendText(processTelephone(record[mapCol["tel"]])+"\n","styleProAdresse",strPro)


          if scribus.textOverflows(strPro, nolinks=1): #effacement du paragraphe de pro tronqué et du bureau de change en double
            scribus.selectText(nbCar, scribus.getTextLength(strPro)-nbCar, strPro)
            scribus.deleteText(strPro)
            if nbCarBureau:
                scribus.selectText(nbCarBureau, scribus.getTextLength("txtBureauxChange")-nbCarBureau, "txtBureauxChange")
                scribus.deleteText("txtBureauxChange")

            #log("Cadre rempli : le cadre de texte %s est plein à la ligne %d\n" % (strPro, nbPro))
            break
        except Exception as exc:
                scribus.messageBox( "Erreur","Une erreur est survenue sur ce professionnel: \n%s\n\n%s" %(record, str(exc)))
                sys.exit()
    
        
    return (nbChg, nbPro, nbCat)
	scribus.setFont(latfont, lattextstring)
	scribus.setFontSize(latfonSize, lattextstring)
	scribus.setTextColor(lattextcolor, lattextstring)
	scribus.setTextShade(lattextshade, lattextstring)
	
	#Make a PDF of Edited Page
	pdfname = roseid+'. '+rosenameger+' ('+rosenamelat+')'
	pdf = scribus.PDFfile()
	pdf.info = pdfname
	pdf.pages = [1]
        pdf.file = os.path.join(baseDirName, pdfname+'.pdf')
        pdf.save()
        
        #Incarese Rowcount and update Progress
        i = i + 1;
        scribus.progressSet(i)
    
    #Done Close tmpfile and remove it
    scribus.closeDoc()
    os.remove(tmpFileName)
    
    scribus.progressReset()
    scribus.statusMessage("Done")
 
 
def main(argv):
    """The main() 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 create()
    function, making sure everything is sane before the script terminates."""
    currentDoc = scribus.getDocName()
Beispiel #25
0
def generateContent(string, window):

    #generates all the elements/only one element
    start = 0
    end = 0
    if string == "all":
        #dont include the first line to make the data sort work [1:]
        #sort the the elements by date
        data = sorted(getCSVdata()[1:],
                      key=lambda row: dateFun(str.strip(row[5])),
                      reverse=True)
        end = len(data)
        print(str(end) + "  " + str(start))
        print("generating elements from all lines")
        window.destroy()
    elif RepresentsInt(string):
        start = int(string) - 1  #index shifting
        end = int(string)
        print("only generating line " + string)
        data = getCSVdata()
        window.destroy()
    else:
        print(string + " is not a valid value")
        print("exiting")
        window.destroy()
        sys.exit()

    if not scribus.haveDoc() > 0:  #do we have a doc?
        scribus.messageBox("importcvs2table",
                           "No opened document.\nPlease open one first.")
        sys.exit()
    userdim = scribus.getUnit()  #get unit and change it to mm
    scribus.setUnit(scribus.UNIT_MILLIMETERS)

    lineWidth = 3.92  #aka 1.383mm, kp warum

    rowDate = ""
    for i in range(start, end):

        rowName = str.strip(data[i][0])
        rowCategory = str.strip(data[i][1])
        rowDescription = str.strip(data[i][2])
        rowPrice = str.strip(data[i][3])
        rowPlace = str.strip(data[i][4])
        rowDate = str.strip(data[i][5])
        rowTime = str.strip(data[i][6])

        if rowName == "":  #skip empty csv lines
            continue

        print("add element: " + rowName)

        #random values
        hpos = 120.0
        vpos = 200.0
        hposition = 120.0
        vposition = 200.0

        objectlist = []  #list for all boxes

        x = 0  #sets the progress
        #create the blue box
        print("create the blue line")
        blueBox = scribus.createLine(hposition + 1, vposition, hposition + 1,
                                     vposition + 5.863)
        scribus.setLineColor("Cyan", blueBox)
        scribus.setLineWidth(lineWidth, blueBox)
        objectlist.append(blueBox)
        scribus.progressSet(x)

        x = 1
        #create the data character box
        #these are the width values for the numbers
        zero = 4.608
        one = 2.839
        two = 4.724
        three = 4.393
        four = 4.625
        five = 4.261
        six = 4.278
        seven = 4.261
        eight = 4.625
        nine = 4.708

        lenArray = [zero, one, two, three, four, five, six, seven, eight, nine]

        marginleft = 1.3
        margintop = 0.519  #substract, cause the box is heigher that the blue line
        cellwidthright = 10.951
        cellHeight = 8.282
        hposition = hposition + marginleft + 1
        textbox = scribus.createText(hposition, vposition - margintop,
                                     cellwidthright, cellHeight)
        scribus.setFont("Quicksand Regular", textbox)
        scribus.setFontSize(20.0, textbox)
        finalDate = ""
        rowDateLength = 0
        #checks if the rowDate is from 01-09, in that case remove the zero
        if rowDate[0] == '0':
            finalDate = rowDate[1]
            rowDateLength = lenArray[int(rowDate[1])]

        else:
            finalDate = rowDate[:2]
            rowDateLength = lenArray[int(rowDate[0])] + lenArray[int(
                rowDate[1])]

        scribus.insertText(finalDate, 0, textbox)
        print("day: " + finalDate)
        objectlist.append(textbox)
        scribus.progressSet(x)

        x = 2
        #create the month/day box
        print("create the box with the day and month")
        width = 19.447
        height = 8.025
        marginleft = rowDateLength  #gain that from the calculations above, depends on the width of the rowDate characters

        monthBox = scribus.createText(hposition + marginleft + 0.7, vposition,
                                      width, height)
        scribus.setFont("Quicksand Regular", monthBox)
        scribus.setFontSize(8.5, monthBox)

        month = ""
        m = rowDate[3:5]
        if m == '01':
            month = "Januar"
        elif m == '02':
            month = "Februar"
        elif m == '03':
            month = "März"
        elif m == '04':
            month = "April"
        elif m == '05':
            month = "Mai"
        elif m == '06':
            month = "Juni"
        elif m == '07':
            month = "Juli"
        elif m == '08':
            month = "August"
        elif m == '09':
            month = "September"
        elif m == '10':
            month = "Oktober"
        elif m == '11':
            month = "November"
        elif m == '12':
            month = "Dezember"
        else:
            print("cant determine month!")

        day = datetime.date(int(rowDate[6:]), int(m),
                            int(rowDate[:2])).weekday()
        dayName = ""

        if day == 0:
            dayName = "Montag"
        elif day == 1:
            dayName = "Dienstag"
        elif day == 2:
            dayName = "Mittwoch"
        elif day == 3:
            dayName = "Donnerstag"
        elif day == 4:
            dayName = "Freitag"
        elif day == 5:
            dayName = "Samstag"
        elif day == 6:
            dayName = "Sonntag"
        else:
            print("cant determine day!")

        text = month + "\n" + dayName
        scribus.setStyle("Kalender_neu_Monat und Tag", monthBox)
        scribus.insertText(text, 0, monthBox)
        print("month: " + month + " day: " + dayName)
        objectlist.append(monthBox)
        scribus.progressSet(x)

        x = 3
        #create the main text box
        print("create the main text box")
        margintop = 5.5
        hpos = hpos - 0.383  #i dont know why but scribus always places the element 0.383 right than it should be :/
        mainTextBox = scribus.createText(
            hpos, vposition + margintop, 43.0,
            45.0)  #minus eins weil der blaue balken seinen kasten overflowed

        #insert category
        print("insert the category: " + rowCategory)
        scribus.insertText(rowCategory, 0, mainTextBox)
        endCategory = scribus.getTextLength(mainTextBox)
        scribus.selectText(0, endCategory, mainTextBox)
        scribus.setFontSize(10.5, mainTextBox)
        scribus.selectText(0, endCategory, mainTextBox)
        scribus.setStyle("Kalender_Eventname", mainTextBox)

        #insert main text
        print("insert the main text")
        scribus.insertText("\n" + rowDescription, endCategory, mainTextBox)
        endMainText = scribus.getTextLength(mainTextBox) - endCategory
        scribus.selectText(endCategory, endMainText, mainTextBox)
        scribus.setStyle("Kalender_Eventbeschreibung", mainTextBox)

        #get start length to color everything black and set font size
        startAll = scribus.getTextLength(mainTextBox)
        createPlaceTimePrice(mainTextBox, "\n| Ort: ", "",
                             "Kalender_Eventname")

        #insert value for place
        createPlaceTimePrice(mainTextBox, rowPlace, "Heuristica Regular", "")

        #insert time letters
        createPlaceTimePrice(mainTextBox, " | Zeit: ", "Quicksand Regular", "")

        #insert time value
        createPlaceTimePrice(mainTextBox, rowTime, "Heuristica Regular", "")

        #insert price letters
        createPlaceTimePrice(mainTextBox, " | Eintritt: ", "Quicksand Regular",
                             "")

        #insert price value
        createPlaceTimePrice(mainTextBox, rowPrice, "Heuristica Regular", "")

        #setFontSize and black color for the whole detail box
        endAll = scribus.getTextLength(mainTextBox) - startAll
        scribus.selectText(startAll, endAll, mainTextBox)
        scribus.setFontSize(8.5, mainTextBox)
        scribus.selectText(startAll, endAll, mainTextBox)
        scribus.setTextColor("Black", mainTextBox)

        objectlist.append(mainTextBox)
        scribus.progressSet(x)

        #do some generell stuff
        scribus.groupObjects(objectlist)
        scribus.progressReset()
        scribus.setUnit(userdim)  # reset unit to previous value
        scribus.docChanged(True)
        scribus.statusMessage("Done")
        scribus.setRedraw(True)

    print("done")
    return 0
Beispiel #26
0
def create_guide(gp):
    fh = FrameHandler()
    toc = TableOfContents(gp.numpagesforcontents)
    index = ClimbIndex()

    scribus.statusMessage("Creating document...")
    nchapters = len(gp.chapters)
    scribus.progressTotal(nchapters)
    scribus.progressReset()
    progress = 0

    currentregion = ""
    crag = ""

    for (xmlid, region) in gp.chapters:
        scribus.statusMessage("Parsing " + xmlid + "...")
        progress = progress + 1
        scribus.progressTotal(nchapters)
        scribus.progressSet(progress)

        p = xml.dom.minidom.parse(gp.path + os.sep + xmlid + os.sep + xmlid +
                                  ".xml")

        for g in p.getElementsByTagName("guide"):

            for n in g.childNodes:

                if n.nodeName == "header":

                    intro = n.getAttribute("intro")
                    name = n.getAttribute("name")
                    rock = n.getAttribute("rock")
                    sun = n.getAttribute("sun")
                    access = n.getAttribute("access")
                    acknow = n.getAttribute("acknowledgement")
                    walk = n.getAttribute("walk")
                    camping = n.getAttribute("camping")
                    history = n.getAttribute("history")
                    stars = g.getAttribute("guidestars").replace(
                        "*", GLYPH_STAR)

                    scribus.statusMessage("Parsing " + xmlid + " (" + name +
                                          ")...")
                    scribus.progressTotal(nchapters)
                    scribus.progressSet(progress)

                    fh.endFrame()
                    #fh.sidebar.setText("")
                    fh.sidebar.setText(name)
                    fh.newPage()
                    fh.setColumns(1)
                    #if scribus.currentPage() % 2 != 0:
                    #   fh.newPage()

                    fh.placeText(name,
                                 "Title",
                                 columns=1,
                                 keepwithnext=True,
                                 nosplit=True)
                    if region != currentregion:
                        toc.add(region, 1, scribus.currentPage())
                        currentregion = region
                    toc.add(name + " " + stars, 2, scribus.currentPage())
                    crag = name
                    #fh.sidebar.setText(crag)

                    graphpath = gp.path + os.sep + xmlid + os.sep + "graph.pdf"
                    fh.placeGuide(rock, sun, walk, graphpath, iconpath=gp.path)

                    if len(acknow) > 0:
                        fh.placeText("Contributors",
                                     "IntroTitle",
                                     nosplit=True,
                                     keepwithnext=True)
                        fh.placeText(acknow, "Intro", nosplit=True)

                    if len(intro) > 0:
                        fh.placeText("General Rave",
                                     "IntroTitle",
                                     nosplit=True,
                                     keepwithnext=True)
                        fh.placeText(intro, "Intro")

                    if len(history) > 0:
                        fh.placeText("History",
                                     "IntroTitle",
                                     nosplit=True,
                                     keepwithnext=True)
                        fh.placeText(history, "Intro")

                    if len(access) > 0:
                        fh.placeText("Access",
                                     "IntroTitle",
                                     nosplit=True,
                                     keepwithnext=True)
                        fh.placeText(access, "Intro")

                    if len(camping) > 0:
                        fh.placeText("Camping",
                                     "IntroTitle",
                                     nosplit=True,
                                     keepwithnext=True)
                        fh.placeText(camping, "Intro")

                    fh.endFrame()

                    fh.setColumns(2)

                elif n.nodeName == "climb" or n.nodeName == "problem":

                    extra = n.getAttribute("extra")
                    grade = n.getAttribute("grade")
                    length = n.getAttribute("length")
                    name = n.getAttribute("name")
                    fa = n.getAttribute("fa")
                    stars = n.getAttribute("stars").replace("*", GLYPH_STAR)
                    number = n.getAttribute("number")

                    scribus.statusMessage("Parsing " + xmlid + " (" + crag +
                                          ") " + name)
                    scribus.progressTotal(nchapters)
                    scribus.progressSet(progress)

                    # OK for now, but we will want to break this up later
                    routename = stars + "  " + name + "  " + length + "  " + grade + "  " + extra
                    if number != "":
                        routename = "(" + number + ")  " + routename

                    #routename = chr(TAB) + stars + chr(TAB) + name + chr(TAB) + length + chr(TAB) + grade + chr(TAB) + extra
                    #if number != "":
                    #   routename = "(" + number + ")" + routename

                    fh.placeText(routename,
                                 "Route Name",
                                 columns=2,
                                 nosplit=True,
                                 keepwithnext=True)

                    for t in n.childNodes:
                        if t.nodeType == 3:
                            txt = t.nodeValue
                            #fh.placeText(t.nodeValue, "Route Description", columns=2, nosplit=True, keepwithnext=(len(fa)>0))
                            fh.placeText(txt,
                                         "Route Description",
                                         columns=2,
                                         nosplit=(len(txt) < NOSPLIT_LIMIT),
                                         keepwithnext=(len(fa) > 0))

                    if len(fa) > 0:
                        fh.placeText(fa, "FA Details", columns=2, nosplit=True)

                    if n.nodeName == "climb":
                        index.add(name, grade, stars, crag,
                                  scribus.currentPage())
                        if name[:3] == "The":
                            index.add(name[4:] + ", The", grade, stars, crag,
                                      scribus.currentPage())
                        #if name in gp.aliases:
                        #   index.add(gp.aliases[name].decode("utf-8"), grade, stars, crag, scribus.currentPage())
                        #   print "Alias Match (via key): " + name + " matches " + route + " substitute " + alternatename
                        for (route, alternatename) in gp.aliases.iteritems():
                            if name == route:
                                #     print "Alias Match(via unrolled niceness): " + name + " matches " + route + " substitute " + alternatename
                                index.add(alternatename.decode("utf-8"), grade,
                                          stars, crag, scribus.currentPage())

                elif n.nodeName == "text":

                    # class can be one of...
                    #    text, heading1, heading2, heading3, intro, indentedHeader
                    #    Editor, Discussion, DiscussionNoIndents, noPrint
                    # assign Style to class name & control layout from Scribus Style Editor

                    clss = n.getAttribute("class")
                    if clss == "": clss = "text"

                    for t in n.childNodes:
                        if t.nodeType == 3:
                            txt = t.nodeValue

                            if clss == "indentedHeader":
                                firstline = txt.split("\n")[0]
                                rest = txt[len(firstline) + 1:]
                                if firstline[-1] == ":":
                                    fh.placeText(firstline[:-1],
                                                 "heading3",
                                                 nosplit=True,
                                                 keepwithnext=True)
                                    fh.placeText(rest, "Intro")
                                else:
                                    fh.placeText(txt, "Intro")

                            elif clss == "heading3":
                                fh.placeText(GLYPH_RIGHTPOINTER + " " + txt,
                                             clss,
                                             nosplit=True,
                                             keepwithnext=True)
                                #if txt != currentregion:
                                toc.add(txt, 4, scribus.currentPage())

                            elif clss == "heading2":
                                #fh.endFrame()
                                fh.placeText(txt,
                                             clss,
                                             columns=2,
                                             nosplit=True,
                                             keepwithnext=True)
                                #if txt != currentregion:
                                toc.add(txt, 3, scribus.currentPage())

                            elif clss == "heading1":
                                fh.endFrame()
                                fh.sidebar.setText("")
                                #fh.sidebar.setText(txt)
                                fh.newPage()
                                fh.placeText(txt,
                                             "Title",
                                             columns=1,
                                             nosplit=True,
                                             keepwithnext=True)
                                if region != currentregion:
                                    toc.add(region, 1, scribus.currentPage())
                                    currentregion = region
                                toc.add(txt, 2, scribus.currentPage())

                            elif clss == "intro":
                                fh.placeText(txt,
                                             "Intro",
                                             nosplit=True,
                                             keepwithnext=True)

                            elif clss == "text":
                                fh.placeText(txt,
                                             clss,
                                             columns=2,
                                             nosplit=True,
                                             keepwithnext=True)
                                #fh.placeText(txt, clss, nosplit=True, keepwithnext=False)

                elif n.nodeName == "image":
                    src = n.getAttribute("src")
                    legend = n.getAttribute("legend")
                    legendtitle = n.getAttribute("legendTitle")
                    legendfooter = n.getAttribute("legendFooter")
                    noprint = n.getAttribute("noPrint")

                    scribus.statusMessage("Parsing " + xmlid + " (" + crag +
                                          ") image=" + src)
                    scribus.progressTotal(nchapters)
                    scribus.progressSet(progress)

                    if src in gp.images:
                        attr = gp.images[src]
                    else:
                        attr = {}

                    if noprint != "true":
                        fullsrc = gp.path + os.sep + xmlid + os.sep + src
                        if not os.path.exists(fullsrc):
                            scribus.messageBox('Bummer, dude',
                                               'Image file missing: ' +
                                               fullsrc,
                                               icon=scribus.ICON_WARNING)
                        else:
                            try:
                                i = Image.open(fullsrc)
                                (width, height) = i.size
                                attr["width"] = width
                                attr["height"] = height
                                if legend == "true":
                                    if len(legendtitle.strip()) > 0:
                                        attr["title"] = legendtitle
                                    if len(legendfooter.strip()) > 0:
                                        attr["footer"] = legendfooter
                                fh.placeImage(fullsrc, attr)
                            except IOError:
                                scribus.messageBox(
                                    "Bummer, dude",
                                    "Image file corrupt: " + fullsrc)

        fh.expandFrame()
        fh.endGuide()

    if gp.includeindexbyname:
        scribus.statusMessage("Creating index by name...")
        scribus.progressReset()
        scribus.newPage(-1)
        if scribus.currentPage() % 2 == 0:  # even page
            scribus.newPage(-1)
        page = scribus.currentPage()
        index.drawIndexByName()
        toc.add("Index by Route Name", 1, page)
    if gp.includeindexbygrade:
        scribus.statusMessage("Creating index by grade...")
        scribus.progressReset()
        scribus.newPage(-1)
        page = scribus.currentPage()
        index.drawIndexByGrade()
        toc.add("Index by Grade", 1, page)
    if gp.levelsofcontents > 0:
        scribus.statusMessage("Creating table of contents...")
        scribus.progressReset()
        toc.draw(gp.levelsofcontents)
def main(argv):

    ###########################################

    info_text = '''
    Welcome to Auto-Photobook!
    
    1. Select the process mode:
        9f = creates a 9x9 layout on each page and fill them with images.
        4f = creates a 4x4 layout on each page and fill them with images.
        
        9e = creates an empty 9x9 layout on each page.
        4e = creates an empty 4x4 layout on each page.
        
        9f+4f = creates a filled 9x9 layout on odd pages and a filled 4x4 layout on even pages.
        9e+4e = creates an empty 9x9 layout on odd pages and an empty 4x4 layout on even pages.
        
        9f+4e = creates a filled 9x9 layout on odd pages and an empty 4x4 layout on even pages (default).
        9e+4f = creates an empty 9x9 layout on odd pages and a filled 4x4 layout on even pages.

    2. Select a document layout, the margins (they need to be equal) and the bleed (if needed). Ignore the number of pages.
    
    3. Define the space between the images (default: 6mm).
    
    4a. If "9f" or "4f" is in your mode, you can choose an image folder and an image filter will be prompted.
    4b. Otherwise, set the amount of pages you want to create (default: 10 pages).
    
    5. Wait until it is done...
    
    6. Adjust you layouts and move your images as you need.
    
    
    Process mode:'''

    # start dialog, choose mode

    #scribus.messageBox("Auto-Photobook", info_text)
    todo = scribus.valueDialog("Auto-Photobook", info_text, "9f+4e")
    todo = list(todo.split("+"))

    # wrong process mode
    if "9f" not in todo and "9e" not in todo and "4f" not in todo and "9e" not in todo:
        scribus.messageBox(
            "Error", "Wrong process mode. Auto-Photobook was cancelled.")
        sys.exit()

    # show new document dialog
    newdoc = scribus.newDocDialog()

    # exit if cancelled
    if newdoc == False:
        scribus.messageBox("Exit", "Auto-Photobook was cancelled.")
        sys.exit()

    if scribus.haveDoc:
        scribus.setUnit(scribus.UNIT_MILLIMETERS)
        (w, h) = scribus.getPageSize()

        ###################

        # delete all pages except the first:
        pageamount = scribus.pageCount()
        while pageamount > 1:
            scribus.deletePage(pageamount)
            pageamount = scribus.pageCount()

        # set image border and bleed
        border = int(
            scribus.valueDialog("Space between images",
                                "Define the space between the images (mm).",
                                "6"))
        #border = 6

        # reset image border for easier calculations
        border = border * 0.75

        if "9f" in todo or "4f" in todo:
            # ask for workdir
            workdir = scribus.fileDialog("Open directory with images",
                                         "",
                                         haspreview=False,
                                         issave=False,
                                         isdir=True)
            #workdir = "/media/sda7/Programming/Python/scribus_auto_photobook/pics"

            # file filter
            filefilter = scribus.valueDialog(
                "File filter",
                "File filter examples: \n\n* or *.* = add all files\n*.jpg = add .jpg files only\nIMG_*.* = add all files starting with IMG_\n\nThis filter is case sensitive!",
                "*.*")

            # get image paths
            filelist = sorted(glob.glob(os.path.join(workdir, filefilter)))
            #filelist = sorted(glob.glob(os.path.join(workdir, "*")))

            # count files
            filesinworkdir = len(filelist)
            scribus.messageBox(
                "Files in directory",
                "Images matched in folder: " + str(filesinworkdir))

            #error
            if filesinworkdir == 0:
                scribus.messageBox("Error", "This directory is empty.")
                sys.exit()

            #messagebar text
            scribus.messagebarText("Importing images...")

            #progressbar max
            scribus.progressTotal(filesinworkdir)

            # set maxpages (not needed here but needs to be assigned)
            maxpages = len(filelist)

        else:
            # ask for page amount
            maxpages = int(
                scribus.valueDialog("Set page amount",
                                    "How many pages you want to create?",
                                    "10"))

            #progressbar max
            scribus.progressTotal(maxpages)

        # get page size (without bleed)
        size = scribus.getPageSize()

        # get margins
        margins = scribus.getPageMargins()[0]

        # set page final size
        final_size = (size[0] - margins, size[1] - margins)

        # simplify calc for 9x9 layout
        guide_layout_x = final_size[0] / 3 - margins / 3
        guide_layout_y = final_size[1] / 3 - margins / 3

        # set indexes
        page = 1
        pic = 0

        #create pages, add and load images
        x = True
        while x == True:
            scribus.progressSet(page)
            scribus.gotoPage(page)

            # create 9x9 layout
            if "9f" in todo or "9e" in todo:

                #guides
                scribus.setVGuides([
                    margins + guide_layout_x - border,
                    margins + guide_layout_x + border / 2,
                    margins + guide_layout_x * 2 - border / 2,
                    margins + guide_layout_x * 2 + border
                ])
                scribus.setHGuides([
                    margins + guide_layout_y - border,
                    margins + guide_layout_y + border / 2,
                    margins + guide_layout_y * 2 - border / 2,
                    margins + guide_layout_y * 2 + border
                ])

                # create images
                scribus.createImage(margins, margins,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image1")
                scribus.createImage(margins + guide_layout_x + border / 2,
                                    margins,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image2")
                scribus.createImage(margins + guide_layout_x * 2 + border,
                                    margins,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image3")

                scribus.createImage(margins,
                                    margins + guide_layout_y + border / 2,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image4")
                scribus.createImage(margins + guide_layout_x + border / 2,
                                    margins + guide_layout_y + border / 2,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image5")
                scribus.createImage(margins + guide_layout_x * 2 + border,
                                    margins + guide_layout_y + border / 2,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image6")

                scribus.createImage(margins,
                                    margins + guide_layout_y * 2 + border,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image7")
                scribus.createImage(margins + guide_layout_x + border / 2,
                                    margins + guide_layout_y * 2 + border,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image8")
                scribus.createImage(margins + guide_layout_x * 2 + border,
                                    margins + guide_layout_y * 2 + border,
                                    guide_layout_x + border - border * 2,
                                    guide_layout_y - border,
                                    "page" + str(page) + "image9")

                #load and scale images
                if "9f" in todo:

                    try:
                        scribus.loadImage(filelist[pic],
                                          "page" + str(page) + "image1")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image1")

                        scribus.loadImage(filelist[pic + 1],
                                          "page" + str(page) + "image2")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image2")

                        scribus.loadImage(filelist[pic + 2],
                                          "page" + str(page) + "image3")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image3")

                        scribus.loadImage(filelist[pic + 3],
                                          "page" + str(page) + "image4")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image4")

                        scribus.loadImage(filelist[pic + 4],
                                          "page" + str(page) + "image5")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image5")

                        scribus.loadImage(filelist[pic + 5],
                                          "page" + str(page) + "image6")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image6")

                        scribus.loadImage(filelist[pic + 6],
                                          "page" + str(page) + "image7")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image7")

                        scribus.loadImage(filelist[pic + 7],
                                          "page" + str(page) + "image8")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image8")

                        scribus.loadImage(filelist[pic + 8],
                                          "page" + str(page) + "image9")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image9")

                    except:
                        x = False

                    # increase picture index
                    pic += 9

                # add page
                scribus.newPage(-1)
                page += 1

            # create 4x4 layout
            if "4f" in todo or "4e" in todo:

                #guides
                scribus.setVGuides(
                    [size[0] / 2 - border * 0.75, size[0] / 2 + border * 0.75])
                scribus.setHGuides(
                    [size[1] / 2 - border * 0.75, size[1] / 2 + border * 0.75])

                # create images
                scribus.createImage(margins, margins,
                                    size[0] / 2 - border * 0.75 - margins,
                                    size[1] / 2 - border * 0.75 - margins,
                                    "page" + str(page) + "image1")
                scribus.createImage(size[0] / 2 + border * 0.75, margins,
                                    size[0] / 2 - border * 0.75 - margins,
                                    size[1] / 2 - border * 0.75 - margins,
                                    "page" + str(page) + "image2")

                scribus.createImage(margins, size[1] / 2 + border * 0.75,
                                    size[0] / 2 - border * 0.75 - margins,
                                    size[1] / 2 - border * 0.75 - margins,
                                    "page" + str(page) + "image3")
                scribus.createImage(size[0] / 2 + border * 0.75,
                                    size[1] / 2 + border * 0.75,
                                    size[0] / 2 - border * 0.75 - margins,
                                    size[1] / 2 - border * 0.75 - margins,
                                    "page" + str(page) + "image4")

                #load and scale images
                if "4f" in todo:
                    try:

                        scribus.loadImage(filelist[pic],
                                          "page" + str(page) + "image1")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image1")

                        scribus.loadImage(filelist[pic + 1],
                                          "page" + str(page) + "image2")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image2")

                        scribus.loadImage(filelist[pic + 2],
                                          "page" + str(page) + "image3")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image3")

                        scribus.loadImage(filelist[pic + 3],
                                          "page" + str(page) + "image4")
                        scribus.setScaleImageToFrame(True,
                                                     proportional=True,
                                                     name="page" + str(page) +
                                                     "image4")

                    except:
                        x = False

                    # increase picture index
                    pic += 4

                # add page
                scribus.newPage(-1)
                page += 1

            #scribus.setImageOffset(0, 0, "imagename"+str(page))
            #scribus.setScaleFrameToImage(name="imagename"+str(page))

            # stop if maxpages reached
            if page > maxpages:
                x = False

        #delete last blank page
        scribus.deletePage(page)
Beispiel #28
0

# open CSV file
data = getCSVdata(delim=delim, qc=qc)

# Process data
scribus.messagebarText("Processing "+str(nol)+" elements")
scribus.progressTotal(len(data))
for row in data:
    scribus.messagebarText("Processing "+str(nol)+" elements")
    celltext = row[numcol].strip()
    if len(celltext)!=0:
        createCell(celltext, cr, cc, CARDWIDTH, CARDHEIGHT, MARGINS[0], MARGINS[2], isBlack)
        nol=nol+1
        if cr==colstotal and cc==rowstotal:
            #create new page
            scribus.newPage(-1)
            scribus.gotoPage(scribus.pageCount())
            cr=1
            cc=1
        else:
            if cr==colstotal:
                cr=1
                cc=cc+1
            else:
                cr=cr+1
        scribus.progressSet(nol)
scribus.messagebarText("Processed "+str(nol)+" items. ")
scribus.progressReset()

Beispiel #29
0
def main(argv):
    """This is a documentation string. Write a description of what your code
    does here. You should generally put documentation strings ("docstrings")
    on all your Python functions."""
    #########################
    #  YOUR CODE GOES HERE  #
    #########################
    userdim = scribus.getUnit()  #get unit and change it to mm
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
    cellwidthleft = 0
    cellwidthright = 0
    cellHeight = 0
    pos = getPosition()
    while cellwidthleft <= 0:
        cellwidthL = scribus.valueDialog(
            'Left Cell Width', 'How wide (mm) do you wish left cells to be?',
            '30.0')
        cellwidthleft = float(cellwidthL)
    while cellwidthright <= 0:
        cellwidthR = scribus.valueDialog(
            'Right Cell Width', 'How wide (mm) do you wish right cells to be?',
            '30.0')
        cellwidthright = float(cellwidthR)
    while cellHeight <= 0:
        cellheight = scribus.valueDialog(
            'Cell Height', 'How tall (mm) do you wish cells to be?', '10.0')
        cellHeight = float(cellheight)
    data = getCSVdata()
    di = getDataInformation(data)
    hposition = pos[1]
    vposition = pos[0]

    objectlist = [
    ]  # here we keep a record of all the created textboxes so we can group them later
    i = 0
    scribus.progressTotal(len(data))
    scribus.setRedraw(False)
    for row in data:
        c = 0
        for cell in row:
            cell = cell.strip()
            cellsize = cellwidthleft
            if c == 1: cellsize = cellwidthright
            textbox = scribus.createText(hposition, vposition, cellsize,
                                         cellHeight)  #create a textbox
            objectlist.append(textbox)
            scribus.insertText(cell, 0,
                               textbox)  #insert the text into the textbox
            hposition = hposition + cellwidthleft  #move the position for the next cell
            c = 1
        vposition = vposition + cellHeight  #set vertical position for next row
        hposition = pos[1]  #reset vertical position for next row
        i = i + 1
        scribus.progressSet(i)

    scribus.groupObjects(objectlist)
    scribus.progressReset()
    scribus.setUnit(userdim)  # reset unit to previous value
    scribus.docChanged(True)
    scribus.statusMessage("Done")
    scribus.setRedraw(True)
def main(argv):

    scribus.setUnit(scribus.UNIT_MILLIMETERS)

    # get page size and page count
    pagesize = scribus.getPageSize()
    pagenum = scribus.pageCount()

    #create on page
    selectedpage = scribus.valueDialog(
        "Select page", "Create arrows and annotation links on page (1-" +
        str(pagenum) + ") :", "1")

    # get active layer, create new layer for exit buttons, set it as active
    #activelayer = scribus.getActiveLayer()
    scribus.createLayer("Arrowlinks")
    scribus.setActiveLayer("Arrowlinks")

    #progressbar max
    scribus.progressTotal(pagenum)

    arrowinitxpos = 10
    arrowinitypos = 30

    scribus.gotoPage(int(selectedpage))

    page = 1
    ###########################################

    for i in range(pagenum):
        # create rectangle
        #exitrect = scribus.createRect(arrowinitxpos, 50, 30, 30, "exitrect")

        #messagebar text
        scribus.messagebarText(
            "Creating arrows and annotation links on page " + selectedpage +
            "...")

        #progress bar
        scribus.progressSet(page)

        #create and distribute arrow
        arrowpoly = [
            10, 30, 30, 10, 50, 30, 40, 30, 40, 50, 20, 50, 20, 30, 10, 30
        ]
        arrowup = scribus.createPolygon(arrowpoly)
        scribus.sizeObject(10, 10, arrowup)
        scribus.moveObjectAbs(arrowinitxpos, arrowinitypos, arrowup)
        scribus.setFillColor("White", arrowup)

        #create and distribute links
        arrowlink = scribus.createText(arrowinitxpos, arrowinitypos + 11, 10,
                                       10, "link_to_page_" + str(page))
        #setLinkAnnotation(page,x,y,["name"])
        scribus.setLinkAnnotation(int(page), 0, 0, arrowlink)

        arrowinitxpos += 11

        if arrowinitxpos > 250:
            arrowinitypos += 24
            arrowinitxpos = 10

        # add page number to iteration
        page += 1
Beispiel #31
0
def create_guide(gp):
   fh = FrameHandler()
   toc = TableOfContents(gp.numpagesforcontents)
   index = ClimbIndex()

   scribus.statusMessage("Creating document...")
   nchapters = len(gp.chapters)
   scribus.progressTotal(nchapters)
   scribus.progressReset()
   progress = 0
   
   currentregion = ""
   crag = ""
   
   
   for (xmlid,region) in gp.chapters:
      scribus.statusMessage("Parsing " + xmlid + "...")
      progress = progress + 1
      scribus.progressTotal(nchapters)
      scribus.progressSet(progress)
  
      p = xml.dom.minidom.parse(gp.path + os.sep + xmlid + os.sep + xmlid + ".xml")
               
      for g in p.getElementsByTagName("guide"):
         
         for n in g.childNodes:

            if n.nodeName == "header":
         
               intro = n.getAttribute("intro")
               name = n.getAttribute("name")
               rock = n.getAttribute("rock")
               sun = n.getAttribute("sun")
               access = n.getAttribute("access")
               acknow = n.getAttribute("acknowledgement")
               walk = n.getAttribute("walk")
               camping = n.getAttribute("camping")
               history = n.getAttribute("history")
               stars = g.getAttribute("guidestars").replace("*",GLYPH_STAR)
            
               scribus.statusMessage("Parsing " + xmlid + " (" + name + ")...")
               scribus.progressTotal(nchapters)
               scribus.progressSet(progress)
               
               fh.endFrame()
               #fh.sidebar.setText("")
               fh.sidebar.setText(name)
               fh.newPage()
               fh.setColumns(1)
               #if scribus.currentPage() % 2 != 0:
               #   fh.newPage()
            
               fh.placeText(name, "Title", columns=1, keepwithnext=True, nosplit=True)
               if region != currentregion:
                  toc.add(region, 1, scribus.currentPage())
                  currentregion = region
               toc.add(name + " " + stars,2,scribus.currentPage())
               crag = name
               #fh.sidebar.setText(crag)
                  
               graphpath = gp.path + os.sep + xmlid + os.sep + "graph.pdf"
               fh.placeGuide(rock, sun, walk, graphpath, iconpath=gp.path)
               
               if len(acknow) > 0:
                  fh.placeText("Contributors", "IntroTitle", nosplit=True, keepwithnext=True)
                  fh.placeText(acknow, "Intro", nosplit=True)
            
               if len(intro) > 0:
                  fh.placeText("General Rave", "IntroTitle", nosplit=True, keepwithnext=True)
                  fh.placeText(intro, "Intro")
                     
               if len(history) > 0:
                  fh.placeText("History", "IntroTitle", nosplit=True, keepwithnext=True)
                  fh.placeText(history, "Intro")
                     
               if len(access) > 0:
                  fh.placeText("Access", "IntroTitle", nosplit=True, keepwithnext=True)
                  fh.placeText(access, "Intro")
                     
               if len(camping) > 0:
                  fh.placeText("Camping", "IntroTitle", nosplit=True, keepwithnext=True)
                  fh.placeText(camping, "Intro")
            
               fh.endFrame()  
               
               fh.setColumns(2)        
            
  
            elif n.nodeName == "climb" or n.nodeName == "problem":

               
               extra = n.getAttribute("extra")
               grade = n.getAttribute("grade")
               length = n.getAttribute("length")
               name = n.getAttribute("name")
               fa = n.getAttribute("fa")
               stars = n.getAttribute("stars").replace("*",GLYPH_STAR)
               number = n.getAttribute("number")

               scribus.statusMessage("Parsing " + xmlid + " (" + crag + ") " + name)
               scribus.progressTotal(nchapters)
               scribus.progressSet(progress)
               
               # OK for now, but we will want to break this up later
               routename = stars + "  " + name + "  " + length + "  " + grade + "  " + extra
               if number != "": routename = "(" + number + ")  " + routename

               #routename = chr(TAB) + stars + chr(TAB) + name + chr(TAB) + length + chr(TAB) + grade + chr(TAB) + extra
               #if number != "":
               #   routename = "(" + number + ")" + routename
            
               fh.placeText(routename, "Route Name", columns=2, nosplit=True, keepwithnext=True)
            
               for t in n.childNodes:
                  if t.nodeType == 3:
                     txt = t.nodeValue
                     #fh.placeText(t.nodeValue, "Route Description", columns=2, nosplit=True, keepwithnext=(len(fa)>0))        
                     fh.placeText(txt, "Route Description", columns=2, nosplit=(len(txt)<NOSPLIT_LIMIT), keepwithnext=(len(fa)>0))        
            
               if len(fa) > 0:
                  fh.placeText(fa, "FA Details", columns=2, nosplit=True)
            
               if n.nodeName == "climb":
                  index.add(name, grade, stars, crag, scribus.currentPage())
                  if name[:3] == "The":
                     index.add(name[4:] + ", The", grade, stars, crag, scribus.currentPage())
                  #if name in gp.aliases:
                  #   index.add(gp.aliases[name].decode("utf-8"), grade, stars, crag, scribus.currentPage())
                  #   print "Alias Match (via key): " + name + " matches " + route + " substitute " + alternatename
                  for (route, alternatename) in gp.aliases.iteritems():
                     if name == route:
                  #     print "Alias Match(via unrolled niceness): " + name + " matches " + route + " substitute " + alternatename
                        index.add(alternatename.decode("utf-8"), grade, stars, crag, scribus.currentPage())




            elif n.nodeName == "text":
         
               # class can be one of...
               #    text, heading1, heading2, heading3, intro, indentedHeader
               #    Editor, Discussion, DiscussionNoIndents, noPrint
               # assign Style to class name & control layout from Scribus Style Editor 
       
               clss = n.getAttribute("class")
               if clss == "": clss = "text"

               for t in n.childNodes:
                  if t.nodeType == 3:
                     txt = t.nodeValue
                  
                     if clss == "indentedHeader":
                        firstline = txt.split("\n")[0]
                        rest = txt[len(firstline)+1:]
                        if firstline[-1] == ":":
                           fh.placeText(firstline[:-1], "heading3", nosplit=True, keepwithnext=True)
                           fh.placeText(rest, "Intro")
                        else:
                           fh.placeText(txt, "Intro")
                     
                     elif clss == "heading3":
                        fh.placeText(GLYPH_RIGHTPOINTER + " " + txt, clss, nosplit=True, keepwithnext=True)
                        #if txt != currentregion:
                        toc.add(txt,4,scribus.currentPage())
                     
                     elif clss == "heading2":
                        #fh.endFrame()
                        fh.placeText(txt, clss, columns=2, nosplit=True, keepwithnext=True)
                        #if txt != currentregion:
                        toc.add(txt,3,scribus.currentPage())
                     
                     elif clss == "heading1":
                        fh.endFrame()
                        fh.sidebar.setText("")
                        #fh.sidebar.setText(txt)
                        fh.newPage()
                        fh.placeText(txt, "Title", columns=1, nosplit=True, keepwithnext=True)
                        if region != currentregion:
                           toc.add(region, 1, scribus.currentPage())
                           currentregion = region
                        toc.add(txt,2,scribus.currentPage())
             
                     elif clss == "intro":
                        fh.placeText(txt, "Intro", nosplit=True, keepwithnext=True)
                        
                     elif clss == "text":
                        fh.placeText(txt, clss, columns=2, nosplit=True, keepwithnext=True)
                        #fh.placeText(txt, clss, nosplit=True, keepwithnext=False)
                     
                     
            elif n.nodeName == "image":
               src = n.getAttribute("src")
               legend = n.getAttribute("legend")
               legendtitle = n.getAttribute("legendTitle")
               legendfooter = n.getAttribute("legendFooter")
               noprint = n.getAttribute("noPrint")

               scribus.statusMessage("Parsing " + xmlid + " (" + crag + ") image=" + src)
               scribus.progressTotal(nchapters)
               scribus.progressSet(progress)
                
               if src in gp.images:
                  attr = gp.images[src]
               else:
                  attr = {}
               
               if noprint != "true":
                  fullsrc = gp.path + os.sep + xmlid + os.sep + src
                  if not os.path.exists(fullsrc):
                     scribus.messageBox('Bummer, dude', 'Image file missing: ' + fullsrc, icon=scribus.ICON_WARNING)
                  else:
                     try:
                        i = Image.open(fullsrc)
                        (width,height) = i.size
                        attr["width"] = width
                        attr["height"] = height
                        if legend == "true":
                           if len(legendtitle.strip()) > 0:
                              attr["title"] = legendtitle
                           if len(legendfooter.strip()) > 0:
                              attr["footer"] = legendfooter
                        fh.placeImage(fullsrc, attr)
                     except IOError:
                        scribus.messageBox("Bummer, dude", "Image file corrupt: " + fullsrc)
                     
      fh.expandFrame()
      fh.endGuide()

      
   if gp.includeindexbyname:
      scribus.statusMessage("Creating index by name...")
      scribus.progressReset()
      scribus.newPage(-1)
      if scribus.currentPage() % 2 == 0:    # even page
         scribus.newPage(-1)
      page = scribus.currentPage()
      index.drawIndexByName()
      toc.add("Index by Route Name",1,page)
   if gp.includeindexbygrade:
      scribus.statusMessage("Creating index by grade...")
      scribus.progressReset()
      scribus.newPage(-1)
      page = scribus.currentPage()
      index.drawIndexByGrade()
      toc.add("Index by Grade",1,page)
   if gp.levelsofcontents > 0:
      scribus.statusMessage("Creating table of contents...")
      scribus.progressReset()
      toc.draw(gp.levelsofcontents)