def add_page_number():
    page_num = scribus.pageCount()
    page_width, page_height, margin_top, margin_left, margin_right, margin_bottom = page_size_margin(page_num)
    textbox = scribus.createText(margin_left, page_height-margin_bottom, page_width-margin_left-margin_right, PAGE_NUM_HEIGHT)
    scribus.setStyle("pagenumber_{}".format(get_style_suffix()), textbox)
    scribus.insertText(str(page_num), 0, textbox)
    scribus.deselectAll()
Exemplo n.º 2
0
def importData(filename, idxPro):
    (nbLogo, nbImg, nbChange, nbPro, nbCol, nbCat) =(0,0,0,0,0,0)

    global filParam
    strDir = os.path.dirname(filename)
    if os.path.isfile(filParam):
            nbCol=importParametres(filParam, idxPro)

    if idxPro==1: 
        if os.path.isfile(strDir+LOGO) and scribus.objectExists("imgLogo"): #Logo de la première page lorsque le document est entièrement plié en huit
            scribus.loadImage(strDir+LOGO, "imgLogo")
            nbLogo+=1

        if os.path.isfile(strDir+LOGO) and scribus.objectExists("imgSmallLogo"): #Petit logo de la dernière page lorsque le document est entièrement plié en huit
            scribus.loadImage(strDir+SMALL_LOGO, "imgSmallLogo")
            nbLogo+=1

        if os.path.isfile(strDir+QRCODE) and scribus.objectExists("imgQrcode"): #QR code de la dernière page
            scribus.loadImage(strDir+QRCODE, "imgQrcode")
            nbImg=1

        for img in range(1,5):
            if os.path.isfile(strDir+("/image%d.png"%img)): #images facultatives
                scribus.loadImage(strDir+("/image%d.png"%img), "img%d"%img)
                nbImg+=1
                
            
    datJ=datetime.date.today() # Date de l'importation comme date de l'annuaire
    scribus.setText(datJ.strftime("%B %Y"), "txtDate")
    scribus.setStyle("styleDate","txtDate")
    if os.path.isfile(filename):  #Sociétés de l'annuaire et les noms des catégories
        (nbChange, nbPro, nbCat)=importSocietes(filename, strDir+CATEGORIE, idxPro)

    return (nbLogo, nbImg, nbCol, nbChange, nbPro, nbCat)
Exemplo n.º 3
0
def getColorsFromCsv(filename, idxPro):
    csvreader=csv.reader(file(filename))
    csvcolors=[]
    for row in csvreader:
        if len(row)>1 and idxPro==1:
          name=row[0].strip()
          if len(row)>4 and name[0:7]=='couleur': 
            c=int(row[1] )* 2.55
            c=int(c)
            m=int(row[2] )* 2.55
            m=int(m)
            y=int(row[3] )* 2.55
            y=int(y)
            k=int(row[4] )* 2.55
            k=int(k)        
            if checkValue(c, m, y, k) ==False:
                scribus.messageBox("importerPros", "At least one CMYK value in your csv file is not correct \n(must be between 0 and 100)\nAborting script - nothing imported.",  icon=scribus.ICON_WARNING)
                sys.exit()

            color=(name, c, m, y, k)
            csvcolors.append(color)
          elif name[0:3]=='txt':
            if scribus.objectExists(name):
                scribus.setText(row[1].replace("\\n","\n"), name)
                nbContent=scribus.getTextLength(name)
                scribus.selectText(0, nbContent, name)
                scribus.setStyle("style"+name[3:], name)
            else:
                scribus.messageBox("Objet non trouvé","Aucun objet correspondant au paramètre %s n'a été trouvé dans le document vierge"%name)

        readGlobalParameter(row)

    return csvcolors
Exemplo n.º 4
0
def insertTextWithStyle(txt, style, frame):
    start = scribus.getTextLength(frame)
    scribus.insertText(txt, -1, frame)
    scribus.selectText(start, len(txt), frame)
    try:
        scribus.setStyle(style, frame)
    except scribus.NotFoundError:
        scribus.createParagraphStyle(style)
        scribus.setStyle(style, frame)
    scribus.insertText("\n", -1, frame)
Exemplo n.º 5
0
def insertTextWithStyle(txt,style,frame):
   start = scribus.getTextLength(frame)
   scribus.insertText(txt, -1, frame)
   scribus.selectText(start, len(txt), frame)
   try:
      scribus.setStyle(style, frame)
   except scribus.NotFoundError:
      scribus.createParagraphStyle(style)
      scribus.setStyle(style, frame)
   scribus.insertText("\n", -1, frame)
def add_page_number():
    page_num = scribus.pageCount()
    page_width, page_height, margin_top, margin_left, margin_right, margin_bottom = page_size_margin(
        page_num)
    textbox = scribus.createText(margin_left, page_height - margin_bottom,
                                 page_width - margin_left - margin_right,
                                 PAGE_NUM_HEIGHT)
    scribus.setStyle("pagenumber_{}".format(get_style_suffix()), textbox)
    scribus.insertText(str(page_num), 0, textbox)
    scribus.deselectAll()
def drawNameTag(xOff, yOff, participant):
    firstNamePos = {"x": xOff+5.0, "y": yOff+12.5}
    lastNamePos = {"x": xOff+5.0, "y": yOff+20.5}

    drawNameTagBox(xOff, yOff)

    firstName = scribus.createText(firstNamePos["x"], firstNamePos["y"], 70, 9)
    scribus.setText(participant["Vorname"], firstName)
    scribus.setStyle(STYLE_FIRST_NAME, firstName)

    lastName = scribus.createText(lastNamePos["x"], lastNamePos["y"], 70, 9)
    scribus.setText(participant["Nachname"], lastName)
    scribus.setStyle(STYLE_LAST_NAME, lastName)
Exemplo n.º 8
0
def createPlaceTimePrice(box, string, font, style):

    startLength = scribus.getTextLength(box)
    scribus.insertText(string, startLength, box)
    endLength = scribus.getTextLength(box) - startLength

    if style != "":
        scribus.selectText(startLength, endLength, box)
        scribus.setStyle(style, box)
    if font != "":
        scribus.selectText(startLength, endLength, box)
        scribus.setFont(font, box)
    return endLength
Exemplo n.º 9
0
 def characters(self, content):
     """place text, apply style"""
     start = scribus.getTextLength(self.name)
     go_ahead = self.shouldSetStyle()
     scribus.insertText (content, -1, self.name)
     scribus.selectText(start, len(content), self.name)
     if self.styles[-1] != None and go_ahead:
         try:
             scribus.setStyle(self.styles[-1], self.name)
         except scribus.NotFoundError:
             scribus.createParagraphStyle(self.styles[-1])
             scribus.setStyle(self.styles[-1], self.name)
     if self.overrides[-1] != None:
         try:
             scribus.setFont(self.overrides[-1], self.name)
         except ValueError:
             pass
     self.first = False
Exemplo n.º 10
0
def drawNameTagBox(xOff, yOff):
    logoPos = {"x": xOff+75.0-LOGO_WIDTH, "y": yOff+10.5}
    metaEventPos = {"x": xOff+5.0, "y": yOff+39.795}
    metaLocationPos = {"x": xOff+5.0, "y": yOff+43.6}

    #swkLogo = scribus.createImage(xOff+5.0, yOff+5.0, 70, 40)
    #scribus.loadImage("softwerkskammer.png", swkLogo)
    #scribus.setScaleImageToFrame(scaletoframe=1, proportional=1, name=swkLogo)
    #scribus.setProperty(swkLogo, "fillTransparency", 0.9)

    metaEvent = scribus.createText(metaEventPos["x"], metaEventPos["y"], 70, 9)
    scribus.setText(EVENT_NAME, metaEvent)
    scribus.setStyle(STYLE_META, metaEvent)

    metaLocation = scribus.createText(metaLocationPos["x"], metaLocationPos["y"], 70, 9)
    scribus.setText(EVENT_LOCATION, metaLocation)
    scribus.setStyle(STYLE_META, metaLocation)

    metaLogo = scribus.createImage(logoPos["x"], logoPos["y"], LOGO_WIDTH, LOGO_HEIGHT)
    scribus.loadImage("logo.png", metaLogo)
    scribus.setScaleImageToFrame(scaletoframe=1, proportional=1, name=metaLogo)
Exemplo n.º 11
0
 def draw(self):
    if self.txt != "":
       if scribus.currentPage() % 2 == 0:   
          r = scribus.createRect(-1,self.y,8,self.height)
          t = scribus.createText(2,self.y + self.height,self.height,6)
       else:   
          (pagewidth, pageheight) = scribus.getPageSize()
          r = scribus.createRect(pagewidth-7,self.y,8,self.height)
          t = scribus.createText(pagewidth-5,self.y + self.height,self.height,6)
       scribus.setFillColor("Black",r)
       scribus.setFillShade(20,r)
       scribus.setLineColor("None",r)
       scribus.setCornerRadius(ROUNDS,r)
       scribus.insertText(self.txt, -1, t)
       scribus.deselectAll()
       scribus.selectObject(t)
       scribus.selectText(0, len(self.txt), t)
       scribus.setStyle("Sidebar", t)
       scribus.rotateObject(90,t)
       self.frames.append(r)
       self.frames.append(t)
Exemplo n.º 12
0
 def draw(self):
     if self.txt != "":
         if scribus.currentPage() % 2 == 0:
             r = scribus.createRect(-1, self.y, 8, self.height)
             t = scribus.createText(2, self.y + self.height, self.height, 6)
         else:
             (pagewidth, pageheight) = scribus.getPageSize()
             r = scribus.createRect(pagewidth - 7, self.y, 8, self.height)
             t = scribus.createText(pagewidth - 5, self.y + self.height,
                                    self.height, 6)
         scribus.setFillColor("Black", r)
         scribus.setFillShade(20, r)
         scribus.setLineColor("None", r)
         scribus.setCornerRadius(ROUNDS, r)
         scribus.insertText(self.txt, -1, t)
         scribus.deselectAll()
         scribus.selectObject(t)
         scribus.selectText(0, len(self.txt), t)
         scribus.setStyle("Sidebar", t)
         scribus.rotateObject(90, t)
         self.frames.append(r)
         self.frames.append(t)
    # 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)

    while scribus.textOverflows(descriptionFrame) != 0 :
        fontSize = scribus.getFontSize(descriptionFrame)
        scribus.setFontSize(fontSize - 1, descriptionFrame)
Exemplo n.º 14
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)
def load_song(data, offset, settings):
    page_num = scribus.pageCount()
    page_width, page_height, margin_top, margin_left, margin_right, margin_bottom = page_size_margin(page_num)
    start_point = margin_top + offset

    new_width = page_width - margin_left - margin_right
    if not FAST:
        scribus.placeEPS(os.path.join(FILES, data["filename"]), 0, 0)
        eps = scribus.getSelectedObject()
        eps_width, eps_height = scribus.getSize(eps)
        #scribus.scaleGroup(new_width/eps_width) # slow on scribus 1.4; does something else on scribus 1.5
        scribus.sizeObject(eps_width*0.86, eps_height*0.86, eps)
        scribus.moveObjectAbs(margin_left, start_point+SPACING_HEADLINE_SONG, eps)
        eps_width, eps_height = scribus.getSize(eps)
    else:
        eps_height = 0

    scribus.deselectAll()
    textbox = scribus.createText(margin_left, start_point, new_width, 20)

    style_suffix = get_style_suffix()

    if data["composer"]:
        scribus.deselectAll()
        scribus.insertText(u"{}\n".format(data["composer"]), 0, textbox)
        scribus.selectText(0, 1, textbox)
        scribus.setStyle("subline_{}".format(style_suffix), textbox)

    if data["poet"]:
        scribus.deselectAll()
        scribus.insertText(u"{}\n".format(data["poet"]), 0, textbox)
        scribus.selectText(0, 1, textbox)
        scribus.setStyle("subline_{}".format(style_suffix), textbox)

    scribus.deselectAll()
    scribus.insertText(u"{}\n".format(data["name"]), 0, textbox)
    scribus.selectText(0, 1, textbox)
    scribus.setStyle("headline_{}".format(style_suffix), textbox)

    text = data["text"]
    text = [t.strip() for t in text if t.strip() != ""]

    # TODO: exit if text == []

    textbox = scribus.createText(margin_left, start_point + eps_height + SPACING_HEADLINE_SONG + SPACING_SONG_TEXT, new_width, 50)
    scribus.setStyle("text", textbox)
    # let's see how many digits are in there:
    num_verses = len([l for l in text if l.isdigit()])
    num_chars = 0
    num_line_total = len(text)
    num_line_actually = 0
    no_new_line = False
    verse_counter = 0
    text_columns_height = 0 # TODO: should be None
    for num_line, line in enumerate(text):
        if line.strip == "":
            continue
        num_line_actually += 1
        if line.isdigit():

            print "#", verse_counter, math.ceil(num_verses * 0.5), num_verses, data["filename"]
            if verse_counter == math.ceil(num_verses*0.5): # this is the first verse that should be in the new column, so let's see what's the height
                print text_columns_height, num_line_actually
                text_columns_height = BASELINE_GRID * (num_line_actually -1)

            first_char = "\n"
            if num_line == 0:
                first_char = ""
            no_new_line = True
            line = u"{}{}.\t".format(first_char, line)
            scribus.insertText(line, -1, textbox)
            scribus.deselectAll()
            scribus.selectText(num_chars, len(line), textbox)
            #scribus.setStyle("num", textbox) # no character styles available
            #scribus.setFontSize(5, textbox)  # TODO: testing only # BUG?
            scribus.setFont("Linux Libertine O Bold", textbox)
            num_chars += len(line)
            verse_counter += 1
        else:
            if no_new_line:
                first_char = ""
            else:
                first_char = chr(28)
            no_new_line = False
            line = u"{}{}".format(first_char, line)
            scribus.insertText(line, -1, textbox)
            #scribus.deselectAll()
            #scribus.selectText(num_chars, len(line), textbox)
            #scribus.setStyle("text", textbox)
            num_chars += len(line)

    scribus.setColumnGap(5, textbox)
    columns = settings.get("columns", 2)
    scribus.setColumns(columns, textbox)
    if columns != 2:
        fit_height(textbox)
    else:
        scribus.sizeObject(new_width, text_columns_height, textbox)
        l, t = scribus.getPosition(textbox)
        scribus.moveObjectAbs(l, round(t/BASELINE_GRID)*BASELINE_GRID, textbox)
        if scribus.textOverflows(textbox):
            fit_height(textbox) # there are some cases,.. 
    text_width, text_height = scribus.getSize(textbox)
    text_left, text_top = scribus.getPosition(textbox)
    return text_top + text_height - start_point + SPACING_SONGS, page_num
Exemplo n.º 16
0
def appendText(strTxt, strStyle, strName):
    #log(strName+"<- "+strTxt) 
    scribus.setStyle(strStyle, strName)
    scribus.insertText(strTxt, -1, strName)
Exemplo n.º 17
0
def generateContent(string, window):

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

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

    lineWidth = 3.92  #aka 1.383mm, kp warum

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

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

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

        print("add element: " + rowName)

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

        objectlist = []  #list for all boxes

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    print("done")
    return 0
Exemplo n.º 18
0
import scribus

n = scribus.selectionCount()
list = []
for i in range(0,n):
	list.append(scribus.getSelectedObject(i))

print(list)

#deselectAll()
for selected in list:
	size = len(scribus.getAllText(selected))
	scribus.selectText(0, size , selected)
	scribus.setStyle("WASTE dialog", selected)
Exemplo n.º 19
0
Arquivo: eotizer.py Projeto: pa3/eot
    headerText = scribus.createText(x, 80, 750, 30)
    headerUnderline = scribus.createLine(x, 110, 160, 110)
    bodyText = scribus.createText(x, 120, 750, 1030)
    scribus.setColumns(4, bodyText)
    scribus.setColumnGap(10, bodyText)

    if scribus.getObjectType(bodyText) == "TextFrame":
        fileName = scribus.fileDialog("Open odt file", 'ODT files (*.odt)')
        text = removeEmptyStrings(parse(fileName))
        header = detag(header(text))
        body = body(text)

        scribus.deleteText(bodyText)
        scribus.insertText(lines(detag(body))[0], -1, bodyText)
        scribus.setStyle("first_paragraph", bodyText)

        for p in lines(detag(body))[1:]:
            scribus.insertText("\n" + p, -1, bodyText)
            scribus.setStyle("eot", bodyText)
        for tag in extractModifiers(body):
            scribus.selectText(tag['start'], tag['length'], bodyText)
            if tag['tag'] == "bold":
                scribus.setFont("Mysl Bold Cyrillic", bodyText)
            elif tag['tag'] == "italic":
                scribus.setFont("Mysl Italic Cyrillic", bodyText)
            else:
                scribus.setFont("Mysl BoldItalic Cyrillic", bodyText)

        scribus.insertText("\n" + authorName(detag(text)), -1, bodyText)
        scribus.setStyle("author name", bodyText)
def load_song(data, offset, settings):
    page_num = scribus.pageCount()
    page_width, page_height, margin_top, margin_left, margin_right, margin_bottom = page_size_margin(
        page_num)
    start_point = margin_top + offset

    new_width = page_width - margin_left - margin_right
    if not FAST:
        scribus.placeEPS(os.path.join(FILES, data["filename"]), 0, 0)
        eps = scribus.getSelectedObject()
        eps_width, eps_height = scribus.getSize(eps)
        #scribus.scaleGroup(new_width/eps_width) # slow on scribus 1.4; does something else on scribus 1.5
        scribus.sizeObject(eps_width * 0.86, eps_height * 0.86, eps)
        scribus.moveObjectAbs(margin_left, start_point + SPACING_HEADLINE_SONG,
                              eps)
        eps_width, eps_height = scribus.getSize(eps)
    else:
        eps_height = 0

    scribus.deselectAll()
    textbox = scribus.createText(margin_left, start_point, new_width, 20)

    style_suffix = get_style_suffix()

    if data["composer"]:
        scribus.deselectAll()
        scribus.insertText(u"{}\n".format(data["composer"]), 0, textbox)
        scribus.selectText(0, 1, textbox)
        scribus.setStyle("subline_{}".format(style_suffix), textbox)

    if data["poet"]:
        scribus.deselectAll()
        scribus.insertText(u"{}\n".format(data["poet"]), 0, textbox)
        scribus.selectText(0, 1, textbox)
        scribus.setStyle("subline_{}".format(style_suffix), textbox)

    scribus.deselectAll()
    scribus.insertText(u"{}\n".format(data["name"]), 0, textbox)
    scribus.selectText(0, 1, textbox)
    scribus.setStyle("headline_{}".format(style_suffix), textbox)

    text = data["text"]
    text = [t.strip() for t in text if t.strip() != ""]

    # TODO: exit if text == []

    textbox = scribus.createText(
        margin_left,
        start_point + eps_height + SPACING_HEADLINE_SONG + SPACING_SONG_TEXT,
        new_width, 50)
    scribus.setStyle("text", textbox)
    # let's see how many digits are in there:
    num_verses = len([l for l in text if l.isdigit()])
    num_chars = 0
    num_line_total = len(text)
    num_line_actually = 0
    no_new_line = False
    verse_counter = 0
    text_columns_height = 0  # TODO: should be None
    for num_line, line in enumerate(text):
        if line.strip == "":
            continue
        num_line_actually += 1
        if line.isdigit():

            print "#", verse_counter, math.ceil(
                num_verses * 0.5), num_verses, data["filename"]
            if verse_counter == math.ceil(
                    num_verses * 0.5
            ):  # this is the first verse that should be in the new column, so let's see what's the height
                print text_columns_height, num_line_actually
                text_columns_height = BASELINE_GRID * (num_line_actually - 1)

            first_char = "\n"
            if num_line == 0:
                first_char = ""
            no_new_line = True
            line = u"{}{}.\t".format(first_char, line)
            scribus.insertText(line, -1, textbox)
            scribus.deselectAll()
            scribus.selectText(num_chars, len(line), textbox)
            #scribus.setStyle("num", textbox) # no character styles available
            #scribus.setFontSize(5, textbox)  # TODO: testing only # BUG?
            scribus.setFont("Linux Libertine O Bold", textbox)
            num_chars += len(line)
            verse_counter += 1
        else:
            if no_new_line:
                first_char = ""
            else:
                first_char = chr(28)
            no_new_line = False
            line = u"{}{}".format(first_char, line)
            scribus.insertText(line, -1, textbox)
            #scribus.deselectAll()
            #scribus.selectText(num_chars, len(line), textbox)
            #scribus.setStyle("text", textbox)
            num_chars += len(line)

    scribus.setColumnGap(5, textbox)
    columns = settings.get("columns", 2)
    scribus.setColumns(columns, textbox)
    if columns != 2:
        fit_height(textbox)
    else:
        scribus.sizeObject(new_width, text_columns_height, textbox)
        l, t = scribus.getPosition(textbox)
        scribus.moveObjectAbs(l,
                              round(t / BASELINE_GRID) * BASELINE_GRID,
                              textbox)
        if scribus.textOverflows(textbox):
            fit_height(textbox)  # there are some cases,..
    text_width, text_height = scribus.getSize(textbox)
    text_left, text_top = scribus.getPosition(textbox)
    return text_top + text_height - start_point + SPACING_SONGS, page_num
# check opened document
if not scribus.haveDoc():
       scribus.messageBox('Scribus - Script Error', "No document open", scribus.ICON_WARNING, scribus.BUTTON_OK)
       sys.exit(1)

scribus.setRedraw(False)

selectionCount = scribus.selectionCount()
# str('Selected: ' + str(selectionCount))

selected = []

# remember all selected objects
for index in range(0, selectionCount):
  # str(index)
  selectedObject = scribus.getSelectedObject(index)
  # str(selectedObject)
  selected.append(selectedObject)

scribus.deselectAll()
 
# change style for each selected object
for obj in selected:
   # str(obj)
   scribus.selectObject(obj)
   scribus.selectText(0, scribus.getTextLength(obj), obj)
   scribus.setStyle(style, obj)
   scribus.deselectAll()
 
scribus.setRedraw(True)
scribus.docChanged(True)
Exemplo n.º 22
0
    def pageFn(left, right):
        page = scribus.newPage(-1, 'planner')
        i = 0
        sizeDate = (20, 15)
        sizeMonth = (20, 7)
        sizeName = (290, 7)
        for xend, y in iterDayLines():
            try:
                tLeftDate = left[i]
                posLeftDate = (xstart, y - sizeDate[1])
                posLeftMonth = (xstart + sizeDate[0], y - sizeDate[1])
                posLeftName = (xstart + sizeDate[0], y - sizeName[1])
                tLeftName = ', '.join(d[tLeftDate.month][tLeftDate.day])
                objLeftDate = scribus.createText(*posLeftDate + sizeDate)
                objLeftMonth = scribus.createText(*posLeftMonth + sizeMonth)
                objLeftName = scribus.createText(*posLeftName + sizeName)
                scribus.setText(tLeftDate.strftime('%d'), objLeftDate)
                scribus.setText(mm(tLeftDate), objLeftMonth)
                scribus.setText(tLeftName, objLeftName)
                scribus.setStyle('dateL', objLeftDate)
                scribus.setStyle('monthL', objLeftMonth)
                scribus.setStyle('nameL', objLeftName)
            except IndexError:
                pass

            try:
                posRightDate = (xend - sizeDate[0], y - sizeDate[1])
                posRightMonth = (xend - sizeDate[0] - sizeMonth[0],
                                 y - sizeDate[1])
                posRightName = (xend - sizeDate[0] - sizeName[0],
                                y - sizeName[1])
                tRightDate = right[i]
                tRightName = ', '.join(d[tRightDate.month][tRightDate.day])
                objRightDate = scribus.createText(*posRightDate + sizeDate)
                objRightMonth = scribus.createText(*posRightMonth + sizeMonth)
                objRightName = scribus.createText(*posRightName + sizeName)
                scribus.setText(tRightDate.strftime('%d'), objRightDate)
                scribus.setText(mm(tRightDate), objRightMonth)
                scribus.setText(tRightName, objRightName)
                scribus.setStyle('dateR', objRightDate)
                scribus.setStyle('monthR', objRightMonth)
                scribus.setStyle('nameR', objRightName)
            except IndexError:
                pass
            i += 1
Exemplo n.º 23
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")
Exemplo n.º 24
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)
Exemplo n.º 25
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)