def run(self):
        selCount = scribus.selectionCount()
        if selCount == 0:
            scribus.messageBox('Scribus Data Merger- Usage Error',
                               "There is no objects selected.\nPlease try again.",
                               scribus.ICON_WARNING, scribus.BUTTON_OK)
            sys.exit(2)

        csvData = self.loadCsvData()

        # Create a list with the names of the selected objects:
        selectedObjects = []

        # Loop through the selected objects and put their names into the list selectedObjects
        o = 0 
        while (o < selCount):
            selectedObjects.append(scribus.getSelectedObject(o))
            o = o + 1

        startingPage = scribus.currentPage()
        lastRow = len(csvData)
        if(self.__dataObject.getNumberOfLinesToMerge() != 'All'):
            lastRow = int(self.__dataObject.getNumberOfLinesToMerge())
        lastRow = min(lastRow, len(csvData)) # This will prevent the script from trying to merge data from non-existing rows in the data file
        currentPage = scribus.currentPage()
        rowNumber = 0
        insertPageBeforeThis = -1
        while (rowNumber < lastRow):
            if(scribus.pageCount() > currentPage):
                insertPageBeforeThis = currentPage + 1
            scribus.newPage(insertPageBeforeThis) # Inserts a page before the page given as an argument
            currentPage = currentPage + 1

            for selectedObject in selectedObjects: # Loop through the names of all the selected objects
                scribus.gotoPage(startingPage) # Set the working page to the one we want to copy objects from 
                scribus.copyObject(selectedObject)
                scribus.gotoPage(currentPage)
                scribus.pasteObject() # Paste the copied object on the new page

            scribus.docChanged(1)
            scribus.gotoPage(currentPage) # Make sure ware are on the current page before we call getAllObjects()
            newPageObejcts = scribus.getAllObjects()

            for pastedObject in newPageObejcts: # Loop through all the items on the current page
                objType = scribus.getObjectType(pastedObject)
                text = CONST.EMPTY
                if(objType == 'TextFrame'):
                    text = scribus.getAllText(pastedObject) # This should have used getText but getText does not return the text values of just pasted objects
                    text = self.replaceText(csvData[rowNumber], text)
                    scribus.setText(text, pastedObject)
                if(objType == 'ImageFrame'):
                    text = scribus.getImageFile(pastedObject)
                    # self.info("Image text", text)
                    # Todo: Find out if it is possible to replace text in the ImageFile property
                          
            rowNumber = rowNumber + 1
     
        scribus.setRedraw(1)
        scribus.docChanged(1)
        scribus.messageBox("Merge Completed", "Merge Completed", icon=scribus.ICON_INFORMATION, button1=scribus.BUTTON_OK)
Пример #2
0
 def drawIndexByName(self):
    contents = {}
    climbnames = []
    for (route, grade, stars, crag, page) in self.climbs:
       text = route + chr(TAB) + str(page)
       contents[route] = (text,"Index")
       climbnames.append(route)
    climbnames.sort() 
    
    (width,height) = scribus.getPageSize()
    (top,left,right,bottom) = getCurrentPageMargins()
    frame = scribus.createText(left, top, width-right-left, TITLESIZE)
    insertTextWithStyle("Index by Route Name","Title",frame)
    
    frame = scribus.createText(left, top+TITLESIZE, width-right-left, height-top-bottom-TITLESIZE)
    scribus.setColumns(2,frame)
    scribus.setColumnGap(COLUMNGAP,frame)
    for route in climbnames:
       (text,style) = contents[route]
       insertTextWithStyle(text,style,frame)
       if scribus.textOverflows(frame):
          oldframe = frame
          scribus.newPage(-1)
          (top,left,right,bottom) = getCurrentPageMargins()
          frame = scribus.createText(left, top+TITLESIZE, width-right-left, height-top-bottom-TITLESIZE)
          scribus.setColumns(2,frame)
          scribus.setColumnGap(COLUMNGAP,frame)
          scribus.linkTextFrames(oldframe,frame)
Пример #3
0
 def flow(self):
     while(scribus.textOverflows(self.name) > 0 and scribus.getTextLines(self.name)):
         current = self.name
         scribus.newPage(-1)
         scribus.gotoPage( scribus.pageCount() )
         self.name = self.make_textframe()
         scribus.linkTextFrames(current, self.name)
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)
Пример #5
0
def fill_addresses(contacts):
    #on a page, we can put MAX_PAGE_CONTACTS contacts.
    nb_pages = (len(contacts) / MAX_PAGE_CONTACTS) + 1
    for curPage in range(0, nb_pages):
        start_contact = curPage * MAX_PAGE_CONTACTS
        end_contact = start_contact + (MAX_PAGE_CONTACTS -1)
        fill_page(contacts[start_contact:end_contact])
        if(end_contact < len(contacts)):
            scribus.newPage(-1)
            scribus.gotoPage(scribus.pageCount()-1)
Пример #6
0
 def drawIndexByGrade(self):
    grades = []
    climbsatgrade = {}
    for (route, gradestr, stars, crag, page) in self.climbs:
       grade = (" " + gradestr.replace("?","")).center(3," ")
       if grade != "   " and route[-5:] != ", The":
          if not grade in grades: grades.append(grade)
          routename = route + " " + stars
          if not grade in climbsatgrade: 
             climbsatgrade[grade] = [(routename,page)]
          else:
             climbsatgrade[grade] = climbsatgrade[grade] + [(routename,page)]
    grades.sort() 
    
    (width,height) = scribus.getPageSize()
    (top,left,right,bottom) = getCurrentPageMargins()
    frame = scribus.createText(left, top, width-right-left, TITLESIZE)
    insertTextWithStyle("Index by Grade","Title",frame)
    
    frame = scribus.createText(left, top+TITLESIZE, width-right-left, height-top-bottom-TITLESIZE)
    scribus.setColumns(2,frame)
    scribus.setColumnGap(COLUMNGAP,frame)
    for grade in grades:
       insertTextWithStyle("Grade " + grade,"IndexGrade",frame)
    
       for climb in climbsatgrade[grade]:
          (route,page) = climb
          text = route + chr(TAB) + str(page)
          insertTextWithStyle(text,"Index",frame)
       if scribus.textOverflows(frame):
          oldframe = frame
          scribus.newPage(-1)
          (top,left,right,bottom) = getCurrentPageMargins()
          frame = scribus.createText(left, top+TITLESIZE, width-right-left, height-top-bottom-TITLESIZE)
          scribus.setColumns(2,frame)
          scribus.setColumnGap(COLUMNGAP,frame)
          scribus.linkTextFrames(oldframe,frame)
Пример #7
0
	def run(self):
		sourceDir = scribus.fileDialog("Comic Directory", isdir=True)
		scribus.newDoc( self.pageSize, self.margins, scribus.PORTRAIT, 0, scribus.UNIT_MILLIMETERS, scribus.FACINGPAGES, scribus.FIRSTPAGERIGHT)

		for resource in os.walk(sourceDir):
			self.clean_up_and_queue(resource[0], resource[1], resource[2])

		scribus.gotoPage(1)

		test = re.compile("[0-9]{1,}\.(%s)$" % self.formats, re.IGNORECASE)
		files = filter(test.search, self.images)
		files.sort()

		nImages = len(files)

		if nImages % 4 > 0:
			print "not"
			numPages = ( ((nImages / 4) +1 ) * 4 )
		else:
			print ":p"
			numPages = nImages
		print numPages

		for page in range(1, numPages):
			scribus.newPage(-1)
		i = 1
		for file in files:
			scribus.gotoPage(i)
			self.createImagePage(file, "image_%s" % i)
			i = i + 1

		if os.path.isfile("%s/front_cover.jpg" % sourceDir):
			file = "%s/front_cover.jpg" % sourceDir
			scribus.newPage(1)
			scribus.gotoPage(1)
			self.createImagePage(file, "front_cover")

		if os.path.isfile("%s/back_cover.jpg" % sourceDir):
			file = "%s/back_cover.jpg" % sourceDir
			scribus.newPage(-1)
			scribus.gotoPage(scribus.pageCount())
			self.createImagePage(file, "back_cover")

		if os.path.isfile("%s/logo_cover.svg" % sourceDir):
			file = "%s/logo_cover.svg" % sourceDir
			scribus.gotoPage(1)
			scribus.placeSVG(file, 0, 0)

#		result = scribus.messageBox('Debug', "%s" % self._comicInfo)

		scribus.setInfo("Fernando Michelotti", "Comics", "description")
		scribus.zoomDocument(-100)
		scribus.saveDoc()
Пример #8
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()
# add the projects to a scribus doc, one project per A6 page. for each section there is a specific master page with a logo.

if (not scribus.haveDoc()) :
    # TODO: how to open a file in the script's directory?
    # scribus.openDoc(os.path.dirname(os.path.realpath(__file__)) + '/cards.sla')
    # scribus.openDoc(os.path.dirname(os.path.realpath(sys.argv[0])) + '/cards.sla')
    scribus.messageBox("Error", "You should first open the cards.sla file", ICON_WARNING, BUTTON_OK)
    sys.exit(1)

# for page in range(2, scribus.pageCount()) :
# scribus.messageBox("Error", str(scribus.pageCount()), ICON_WARNING, BUTTON_OK)
for page in range(scribus.pageCount(), 1, -1) :
    scribus.deletePage(page)

for project in projects :
    scribus.newPage(-1, project['section'])

    # title: x=10 y=10 w=85mm h=20
    # description: x=10 y=40 w=85mm h=80
    titleFrame = scribus.createText(10, 10, 85, 20)
    scribus.setText(project['title'], titleFrame)
    scribus.setStyle('title', titleFrame)
    descriptionFrame = scribus.createText(10, 40, 85, 80)
    scribus.setText(project['description'], descriptionFrame)
    scribus.setStyle('description', descriptionFrame)

    # shrink the title and text size if it does not fit in the frame
    while scribus.textOverflows(titleFrame) != 0 :
        fontSize = scribus.getFontSize(titleFrame)
        scribus.setFontSize(fontSize - 1, titleFrame)
def new_page():
    scribus.newPage(-1)
    scribus.gotoPage(scribus.pageCount())
    add_page_number()
Пример #11
0
def createPage():
    """appends a new page"""
    scribus.newPage(-1) #append new page
    #new page - new header and footer
    drawHeaderFooter(pageTitle)
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)
Пример #13
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)
Пример #14
0
def funzioneprincipale(csvData):  # def funzioneprincipale(row,headerRow):
    # scribus.messageBox('Scribus - Messaggio di test', str(row), scribus.ICON_WARNING, scribus.BUTTON_OK)
    # scribus.messageBox('Scribus - Messaggio di test', str(headerRow), scribus.ICON_WARNING, scribus.BUTTON_OK)
    # scribus.messageBox('Scribus - Messaggio di test', str(csvData), scribus.ICON_WARNING, scribus.BUTTON_OK)
    if scribus.haveDoc():
        # scribus.newDoc(scribus.PAPER_LETTER,  (20,20,20,20),scribus.PORTRAIT, 1, scribus.UNIT_POINTS,  scribus.NOFACINGPAGES, scribus.FIRSTPAGERIGHT)
        # Dichiaro variabili e costanti
        # le COSTANTI sono quelle in maiuscolo
        POS_X_FOOTER = 43
        WIDTH1 = 330
        WIDTH2 = 90
        HEIGHT = 26
        MAX_HEIGHT = 710
        # max_width = 520
        INTERLINEA = 12.5
        MARGIN_SX = 3.5
        MARGIN_DX = 3.5
        MARGIN_UP = 3.5
        MARGIN_DOWN = 2
        FONT_SIZE = 8
        NUM_COL = 3
        # primo numero da inserire dopo %VAR_F
        # n = 6

        # Riga di partenza del csv, da cui inizio a creare la tabella
        ROW_START = 1
        # Colonna di partenza, da cui creare la tabella
        COL_START = 3

        # variabili in minuscolo
        pos_y = 521

        # ciclo tutte le righe del csv
        for i in range(ROW_START, len(csvData)):
            # creo la variabile pos_footer, che contiene la nuova posizione della y
            # che verrà assegnata alla cornice di testo chiamata 'footer'
            pos_x = 43
            for j in range(COL_START, len(csvData[i])):
                # i è la riga attuale del csv
                # j è la colonna attuale del csv
                # cur_col è la colonna attuale nella pagina
                cur_col = j % NUM_COL
                cur_width = WIDTH1
                if cur_col == 0:  # and pos_x <= pos_x:
                    # a capo ogni num_col celle
                    # pos_y = pos_y + height
                    pos_x = 43
                    if pos_y >= MAX_HEIGHT:
                        # crea una nuova pagina se la variabile pos_y raggiunge la dimensione
                        # massima prestabilita
                        scribus.newPage(-1)
                        pos_y = HEIGHT + 20
                    else:
                        pos_y = pos_y + HEIGHT
                if cur_col == 1 or cur_col == 2:
                    cur_width = WIDTH2
                nometxtbox = "Cella: csvrow=%d, row=%d, col=%d" % (i, pos_y, pos_x)
                # cell_label = "%VAR_F" + str(n) + "%"
                cell_label = csvData[i][j]
                scribus.createText(pos_x, pos_y, cur_width, HEIGHT, nometxtbox)
                scribus.createRect(pos_x, pos_y, cur_width, HEIGHT)
                scribus.setText(cell_label, nometxtbox)
                # modifico la dimensione del testo
                scribus.setFontSize(FONT_SIZE, nometxtbox)
                # modifico i margini (sx, dx, alto, basso)
                scribus.setTextDistances(MARGIN_SX, MARGIN_DX, MARGIN_UP, MARGIN_DOWN, nometxtbox)
                # modifico l’interlinea
                scribus.setLineSpacing(INTERLINEA, nometxtbox)
                pos_x = pos_x + cur_width
                # n=n+1
                pos_footer = pos_y + HEIGHT + 5
                scribus.moveObjectAbs(POS_X_FOOTER, pos_footer, "footer")
        # Salvo il documento attivo altrimenti
        # lo script ScribusGenerator non inserisce la tabella appena creata
        # scribus.messageBox('Scribus - Messaggio di test', str(cell_label), scribus.ICON_WARNING, scribus.BUTTON_OK)
        scribus.saveDoc()
    else:
        scribus.messageBox(
            "Alert di errore", "Devi avere una pagina Scribus aperta!!!", scribus.ICON_WARNING, scribus.BUTTON_OK
        )
        scribus.newDoc(
            scribus.PAPER_LETTER,
            (20, 20, 20, 20),
            scribus.PORTRAIT,
            1,
            scribus.UNIT_POINTS,
            scribus.NOFACINGPAGES,
            scribus.FIRSTPAGERIGHT,
        )
Пример #15
0
def main(argv):
    userdim = scribus.getUnit()  # get unit and change it to mm
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
    cellwidthleft = 0
    cellwidthright = 0
    # Set starting position
    hposition = 28
    vposition = 20
    data = getCSVdata()
    di = getDataInformation(data)
    ncol = len(data[0])
    nrow = len(data)
    scribus.messageBox("Table", "   " + str(ncol) + " columns,    " +
                       str(nrow) + " rows   ")  #jpg
    ColWidthList = []
    TableWidth = 0
    RowHeightList = []
    TableHeight = 0
    i = 0
    for row in data:
        if i == 0:
            c = 0
            for cell in row:
                ColWidth = 40
                ColWidthList.append(ColWidth)
        TableWidth = TableWidth + ColWidth
        c = c + 1
        RowHeight = 15
        RowHeightList.append(RowHeight)
        TableHeight = TableHeight + RowHeight
        i = i + 1
    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)
    rowindex = 0
    new_row_indication = 1
    new_page_indication = 1
    firstorigin_indicator = 1
    while rowindex < len(data):
        c = 0
        origin_cd = data[rowindex][0].strip()
        origin = data[rowindex][1].strip()
        origin_complete = origin + ' (' + origin_cd + ")"
        headerorigin = origin_complete
        origin_added = 0
        destination_cd = data[rowindex][2].strip()
        destination = data[rowindex][3].strip()
        destination_complete = destination + ' (' + destination_cd + ")"
        fareplan = data[rowindex][4].strip()
        fareplan_type = data[rowindex][5].strip()
        fareplan_complete = fareplan + ' ' + fareplan_type[:1]
        fare = data[rowindex][6].strip()
        fare = float(fare)
        fare = "{0:.2f}".format(fare)
        fare_onboard = data[rowindex][7].strip()
        fare_onboard = float(fare_onboard)
        fare_onboard = "{0:.2f}".format(fare_onboard)
        cellheight_market = 5
        cellheight_market_dos = 5

        try:
            last_origin = data[rowindex - 1][1].strip()
        except:
            last_origin = origin

        try:
            last_destination = data[rowindex - 1][3].strip()
        except:
            last_destination = destination

        cellsize = ColWidthList[c]
        cellHeight = RowHeightList[i]

        # Check to see if near bottom of the page, if so wrap it over
        if (vposition > 227):
            hposition = hposition + cellsize
            vposition = 20
            new_row_indication = 1
        # If at end, reset and create new page
        if (hposition > 174):
            scribus.newPage(-1)
            hposition = 28
            vposition = 20
            new_page_indication = 1
            firstorigin_indicator = 0

        if new_row_indication == 1:
            textbox = scribus.createText(hposition, 16, cellsize / 2,
                                         4)  # create a textbox.
            objectlist.append(textbox)
            scribus.setStyle('FareplanHeader', textbox)
            scribus.insertText('Fareplan', 0, textbox)
            c = c + 1

            textbox = scribus.createText(hposition + (cellsize / 2), 16,
                                         cellsize / 2, 4)  # create a textbox.
            objectlist.append(textbox)
            scribus.setStyle('FareplanHeader', textbox)
            scribus.insertText('Amount', 0, textbox)
            c = c + 1


#			if (firstorigin_indicator == 1):
#				headerorigin = origin_complete
#				textbox = scribus.createText(20, 10, cellsize*4, 4) # create a textbox.
#				objectlist.append(textbox)
#				scribus.setStyle('HeaderOrigin', textbox)
#				scribus.insertText(headerorigin, 0, textbox)
#				c = c + 1

# Origin textbox
        if (rowindex < len(data)):
            if ((origin != last_origin) or (rowindex == 0)):
                # Add 'btwn' text
                textbox = scribus.createText(hposition, vposition, cellsize,
                                             4)  # create a textbox.
                objectlist.append(textbox)
                scribus.setStyle(
                    'Headings', textbox
                )  # set it in the style 'Headings' as defined in Scribus.
                scribus.insertText(
                    'btwn', 0, textbox)  # insert the origin into the textbox.
                # scribus.setDistances(1,1,1,1) # set the distances.
                vposition = vposition + 4  # Shift position of cell down.
                c = c + 1

                textbox = scribus.createText(
                    hposition, vposition, cellsize,
                    cellheight_market_dos)  # create a textbox.
                objectlist.append(textbox)
                scribus.setStyle(
                    'Headings', textbox
                )  # set it in the style 'Headings' as defined in Scribus.
                scribus.insertText(
                    origin_complete, 0,
                    textbox)  # insert the origin into the textbox.
                while (scribus.textOverflows(textbox) > 0):
                    cellheight_market_dos += 1
                    scribus.sizeObject(cellsize, cellheight_market_dos,
                                       textbox)
                vposition = vposition + cellheight_market_dos  # Shift position of cell down.
                c = c + 1

                # Add 'and' text
                textbox = scribus.createText(hposition, vposition, cellsize,
                                             4)  # create a textbox.
                objectlist.append(textbox)
                scribus.setStyle(
                    'andStyle', textbox
                )  # set it in the style 'andStyle' as defined in Scribus.
                scribus.insertText(
                    'and', 0, textbox)  # insert the origin into the textbox.
                vposition = vposition + 4  # Shift position of cell down.
                c = c + 1

                origin_added = 1
                firstorigin_indicator = firstorigin_indicator + 1

                # Insert the origin at the top margin
                if (firstorigin_indicator == 1 or rowindex == 0):
                    headerorigin = origin_complete
                    textbox = scribus.createText(28, 10, cellsize * 4,
                                                 4)  # create a textbox.
                    objectlist.append(textbox)
                    scribus.setStyle('HeaderOrigin', textbox)
                    scribus.insertText(headerorigin, 0, textbox)
                    c = c + 1

        # Destination textbox
        if ((destination != last_destination) or (rowindex == 0)
                or (origin_added == 1)):
            textbox = scribus.createText(
                hposition, vposition, cellsize,
                cellheight_market)  # create a textbox.
            objectlist.append(textbox)
            scribus.setStyle(
                'Headings', textbox
            )  # set it in the style 'Headings' as defined in Scribus.
            scribus.insertText(
                destination_complete, 0,
                textbox)  # insert the destination into the textbox.
            while (scribus.textOverflows(textbox) > 0):
                cellheight_market += 1
                scribus.sizeObject(cellsize, cellheight_market, textbox)

            vposition = vposition + cellheight_market  # Shift position of cell down.
            c = c + 1
        rowindex = rowindex + 1

        # Fareplan textbox
        fareplan_box_height = 5
        if fare_onboard != '0.00':
            fareplan_box_height = 10
        textbox = scribus.createText(hposition, vposition, cellsize / 2,
                                     fareplan_box_height)  # create a textbox.
        objectlist.append(textbox)
        scribus.insertText(fareplan_complete, 0,
                           textbox)  # insert the fareplan into the textbox.
        hposition = hposition + (cellsize / 2)  # Shift position of cell right.
        c = c + 1

        # Fare textbox
        textbox = scribus.createText(hposition, vposition, cellsize / 2,
                                     5)  # create a textbox.
        objectlist.append(textbox)
        scribus.insertText(fare, 0,
                           textbox)  # insert the fare into the textbox.
        c = c + 1

        if fare_onboard != '0.00':
            vposition = vposition + 5  # Shift position of cell down.
            textbox = scribus.createText(hposition, vposition, cellsize / 2,
                                         5)  # create a textbox.
            objectlist.append(textbox)
            scribus.setStyle('OnBoard', textbox)
            scribus.insertText(fare_onboard, 0,
                               textbox)  # insert the fare into the textbox.
            hposition = hposition - (cellsize / 2
                                     )  # Shift position of cell back.
            vposition = vposition + 5  # Shift position of cell down.
            c = c + 1
        else:
            hposition = hposition - (cellsize / 2
                                     )  # Shift position of cell back.
            vposition = vposition + 5  # Shift position of cell down.
        i = i + 1
        new_row_indication = 0
        new_page_indication = 0

    scribus.deselectAll()
    scribus.groupObjects(objectlist)
    scribus.progressReset()
    scribus.setUnit(userdim)  # reset unit to previous value
    scribus.docChanged(True)
    scribus.statusMessage("Done")
    scribus.setRedraw(True)
Пример #16
0
def funzioneprincipale(csvData):

    for line in csvData:
        i = 0
        listacompleta=[]
        while i < len(line):
            listacompleta.append(line[i])
            #scribus.messageBox('Scribus - Messaggio di test', str(line[i]), scribus.ICON_WARNING, scribus.BUTTON_OK)
            i = i + 1

    if scribus.haveDoc():
        #scribus.messageBox('Scribus - Messaggio di test', str(listacompleta), scribus.ICON_WARNING, scribus.BUTTON_OK)
        #scribus.newDoc(scribus.PAPER_LETTER,  (20,20,20,20),scribus.PORTRAIT, 1, scribus.UNIT_POINTS,  scribus.NOFACINGPAGES, scribus.FIRSTPAGERIGHT)
        #variabili
        pos_footer_x = 43
        pos_y = 521
        width1 = 330
        width2 = 90
        height = 26
        max_height = 710
        max_width = 520
        interlinea = 12.5
        margin_sx = 3.5
        margin_dx = 3.5
        margin_up = 3.5
        margin_down = 2
        font_size = 8
        # primo numero da inserire dopo %VAR_F
        n = 6
        num_col = 3
        width3 = width1 + width2
        #ciclo tutte le righe del csv
        for i in range(1, len(csvData)):
            #scribus.messageBox('Scribus - Messaggio di test', str(len(csvData[i])), scribus.ICON_WARNING, scribus.BUTTON_OK)
            pos_x = 43
            #colonne
            for j in range(3, len(csvData[i])):
            #creo la variabile pos_footer, che contiene la nuova posizione della y
            #che verrà assegnata alla cornice di testo chiamata 'footer'
             while (pos_x <= max_width):
                #creazione di 3 colonne con dimensioni diverse
                # la prima ha larghezza pari a variabile width1
                # la seconda e la terza hanno la larghezza pari a width2
                if (pos_x <= width1):
                    nometxtbox = "Cella: I=%d, Pos_x=%d, Pos_y=%d" % (i, pos_x, pos_y)
                    cell_label = csvData[i][j]
                    scribus.createText(pos_x, pos_y, width1, height, nometxtbox)
                    scribus.createRect(pos_x, pos_y, width1, height)
                    scribus.setText(cell_label, nometxtbox)
                    #scribus.setText("Testo di pcsvDataa","Testo1")
                    #comando per creare una cornice di testo
                    #modifico la dimensione del testo
                    scribus.setFontSize(font_size, nometxtbox)
                    #modifico i margini (sx, dx, alto, basso)
                    scribus.setTextDistances(margin_sx, margin_dx, margin_up, margin_down, nometxtbox)
                    #modifico l’interlinea
                    scribus.setLineSpacing(interlinea,nometxtbox)
                    j = j + 1
                    pos_x = pos_x + width1
                    #n = n + 1
                elif (pos_x <= width3):
                    nometxtbox = "Cella: I=%d, Pos_x=%d, Pos_y=%d" % (i, pos_x, pos_y)
                    cell_label = csvData[i][j]
                    scribus.createText(pos_x, pos_y, width2, height, nometxtbox)
                    scribus.createRect(pos_x, pos_y, width2, height)
                    scribus.setText(cell_label, nometxtbox)
                    #Allineo il testo al centro
                    scribus.setTextAlignment(scribus.ALIGN_CENTERED, nometxtbox)
                    scribus.setFontSize(font_size, nometxtbox)
                    scribus.setTextDistances(margin_sx, margin_dx, margin_up, margin_down, nometxtbox)
                    scribus.setLineSpacing(interlinea,nometxtbox)
                    j = j + 1
                    pos_x = pos_x + width2
                    #n = n + 1
                else:
                    nometxtbox = "Cella: I=%d, Pos_x=%d, Pos_y=%d" % (i, pos_x, pos_y)
                    cell_label = csvData[i][j]
                    scribus.createText(pos_x, pos_y, width2, height, nometxtbox)
                    scribus.createRect(pos_x, pos_y, width2, height)
                    scribus.setText(cell_label, nometxtbox)
                    #Allineo il testo al centro
                    scribus.setTextAlignment(scribus.ALIGN_CENTERED, nometxtbox)
                    scribus.setFontSize(font_size, nometxtbox)
                    scribus.setTextDistances(margin_sx, margin_dx, margin_up, margin_down, nometxtbox)
                    scribus.setLineSpacing(interlinea,nometxtbox)
                    j = j + 1
                    pos_x = pos_x + width2
                    #n = n + 1

            if pos_y >= max_height:
            #crea una nuova pagina se la variabile pos_y raggiunge la dimensione
            #massima prestabilita
                scribus.newPage(-1)
                pos_y = height + 20
            else:
                pos_y = pos_y + height
        #Salvo il documento attivo altrimenti
        #lo script ScribusGenerator non inserisce la tabella appena creata
        pos_footer_y = pos_y + height + 5
        scribus.moveObjectAbs(pos_footer_x, pos_footer_y,"footer")
        scribus.saveDoc()

    else:
        scribus.messageBox('Alert di errore',  "Devi avere una pagina Scribus aperta!!!", scribus.ICON_WARNING,  scribus.BUTTON_OK)
        scribus.newDoc(scribus.PAPER_LETTER,  (20,20,20,20),scribus.PORTRAIT, 1, scribus.UNIT_POINTS,  scribus.NOFACINGPAGES, scribus.FIRSTPAGERIGHT)

#per importare uno script copiarlo nella cartella: C:\Python27\Lib\site-packages
#Ottenere testo da textbox
#a=scribus.getText(nometextbox)
#mostrare msgbox
#scribus.messageBox('Scribus - Messaggio di test', a, scribus.ICON_WARNING, scribus.BUTTON_OK)
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)
Пример #18
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)
Пример #19
0
 def newPage(self):
    scribus.newPage(-1)
    (self.topmargin, self.leftmargin, self.rightmargin, self.bottommargin) = getCurrentPageMargins()
    self.columnwidth = (self.pagewidth - self.leftmargin - self.rightmargin - COLUMNGAP) / 2
    self.sidebar.draw()
    self.frame = None
Пример #20
0
# if nrimages == '4':
#     xpos = [15, 310, 15, 310]
#     ypos = [42, 187, 388, 533]
# if nrimages == '6':
#     xpos = [15, 310, 15, 310, 15, 310]
#     ypos = [42, 42, 290, 290, 533, 533]
# This proportion is right for photographs from my digital camera
pwidth = 69.35
pheight = 94.35
imagecount = 0
# framecount = 0
if len(D) > 0:
    if scribus.newDocument((69.35, 94.35), (0, 0, 0, 0), scribus.PORTRAIT, 1, scribus.UNIT_MM, scribus.PAGE_1, 0, 1):
        while imagecount < len(D):
            if imagecount > 0:
                scribus.newPage(-1)
                framecount = 0
            # L is the frame at the top of each page showing the directory name
            # L = scribus.createText(15, 20, 200, 20)
            # scribus.setText("Dir: " + imagedir, L)
            # scribus.setTextAlignment(scribus.ALIGN_LEFT, L)
            # scribus.setFont(labelFont, L)
            # scribus.setFontSize(10, L)
            # Here is where we're loading images into the page, four at a time, then go back up for a newPage
            if imagecount < len(D):
                f = scribus.createImage(0, 0, pwidth, pheight)
                scribus.loadImage(imagedir + '/' + D[imagecount], f)
                scribus.setScaleImageToFrame(scaletoframe=1, proportional=0, name=f)
                lenfilename = len(D[imagecount])
                Lpiclen = int(5.3 * lenfilename)
                # Lpic is the label for each picture, with position and length adjusted
Пример #21
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  #
    #########################
    script = "Aufschlussdoku.py"
    version = "20140107"
    csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
    fname_ext = csvfile[csvfile.rfind("/") + 1:]
    fname_noext = fname_ext[:fname_ext.rfind(".")]
    reader = csv.reader(open(csvfile, "rb"), delimiter=";")
    boxes = [["strat_d", 2.25], ["strat_n", 2.25], ["strat_b", 6.5], ["strat_p", 2.3], ["strat_a", 3.9]]
    start_x = float(1.9075)
    start_y = float(10.5)
    strats = []
    strat_ct = int(0)
    strat_ok = float(0.0)
    print getpass.getuser()

    for line in reader:
        if line[0].find("Tiefe bis [m]") <> 0:
            start_x_0 = start_x
            strat_ct = strat_ct + 1
            strat_d = line[0].replace(",", ".");
            strat_uk = float(strat_d) + float(strat_ok)
            strat_draw = float(strat_d) * 2.0
            strat_uk_draw = start_y + strat_draw

            if strat_uk_draw > 26.4:
                nPage = scribus.currentPage() + 1
                pageendtext = "Fortsetzung nächste Seite"
                #print nPage
                scribus.createText(start_x_0 + 0.1, start_y + 0.1, 17, 0.5, "box_txt_pageend")
                scribus.sentToLayer("profil_txt", "box_txt_pageend")
                scribus.setText(pageendtext, "box_txt_pageend")
                scribus.setStyle("Buchner_sehrklein", "box_txt_pageend")
                scribus.newPage(-1,"Buchner_Standard")
                scribus.gotoPage(nPage)
                start_y = float(5.5)
                strat_uk_draw = start_y + strat_draw
                
            box_nr = int(0)
            #print strat_uk
            #print "aktuelle Seite:", scribus.currentPage()

            #print strat_uk
            strat_uk_txt = str(strat_uk).replace(".", ",");
            #print strat_uk_txt
            strat_h = line[0]
            strat_n = line[1]
            strat_b = line[2]
            strat_p = line[3]
            strat_a = line[4]
            strat = [strat_d, strat_uk, strat_h, strat_n, strat_b, strat_p, strat_a]
            #print strat
            strats.append(strat)

            for box in boxes:
                box_n = box[0] + str(strat_ct)
                box_txt = strat[box_nr + 2]
                box_txt_n = box_n + "txt"
                
                #print box_nr
                #print box_txt
                #print box_n, box_txt_n, dimensions[1], position
                scribus.createRect(start_x_0, start_y, float(box[1]), strat_draw, box_n)
                scribus.setLineWidth(0.567, box_n)
                scribus.sentToLayer("profil_rahmen", box_n)
                if box_nr == 0:
                    scribus.createText(start_x_0 + 0.1, start_y + (strat_draw) - 0.4, float(box[1]) - 0.2, 0.4, box_txt_n)
                    #print strat_uk_txt
                    scribus.setText(strat_uk_txt, box_txt_n)
                else:
                    scribus.createText(start_x_0 + 0.1, start_y + 0.1, float(box[1]) - 0.2, (strat_draw) - 0.1, box_txt_n)
                    scribus.setText(box_txt, box_txt_n)
                scribus.setStyle("Buchner_Standard schmal", box_txt_n)
                scribus.sentToLayer("profil_txt", box_txt_n)
                start_x_0 = start_x_0 + float(box[1])
                box_nr = box_nr + 1
            #print "end: strat count:", strat_ct
            start_y = strat_uk_draw
            start_x_0 = start_x
            strat_ok = strat_ok + float(strat_d)
    print "end: all"
    scribus.createText(start_x_0 + 0.1, start_y + 0.1, 17, 0.5, "box_txt_end")
    scribus.sentToLayer("profil_txt", "box_txt_end")
    endtext = "Erstellt von " + getpass.getuser() + " mit " + fname_ext + ", " + script + " (V" + version + ")"
    scribus.setText(endtext, "box_txt_end")
    scribus.setStyle("Buchner_sehrklein", "box_txt_end")
    scribus.saveDocAs(fname_noext + ".sla")
Пример #22
0
def createPage():
    """appends a new page"""
    scribus.newPage(-1) #append new page
    #new page - new header and footer
    drawHeaderFooter(pageTitle)
Пример #23
0
 def __init__(self,page):
    scribus.newPage(-1)
    self.contentspage = scribus.currentPage()
    for i in range(1,page):
       scribus.newPage(-1)
    self.sections = []
Пример #24
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()

Пример #25
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)