Exemple #1
0
    def draw(self, tolevel):
        contents = []
        for (label, level, page) in self.sections:
            if level <= tolevel:
                text = label + chr(TAB) + str(page)
                style = "Contents" + str(level)
                contents.append((text, style))

        page = self.contentspage
        scribus.gotoPage(page)
        (width, height) = scribus.getPageSize()
        (top, left, right, bottom) = getCurrentPageMargins()
        frame = scribus.createText(left, top, width - right - left, TITLESIZE)
        insertTextWithStyle("Contents", "Title", frame)

        frame = scribus.createText(left, top + TITLESIZE, width - right - left,
                                   height - top - bottom - TITLESIZE)
        scribus.setColumns(2, frame)
        scribus.setColumnGap(COLUMNGAP, frame)
        for (text, style) in contents:
            insertTextWithStyle(text, style, frame)
            if scribus.textOverflows(frame):
                oldframe = frame
                page = page + 1
                scribus.gotoPage(page)
                (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)
def newWikiTextBlock(cont,x,y,w):
  h = 0
  #title
  title = scribus.createText(x, y, w, 1)
  scribus.setText(cont["wp"].title, title)
  scribus.setTextAlignment(scribus.ALIGN_LEFT, title)
  scribus.setFont("Open Sans Bold", title)
  scribus.setFontSize(14, title)
  scribus.setLineSpacing(14, title)

  tw,th = scribus.getSize(title)
  while scribus.textOverflows(title):
    scribus.sizeObject(tw, th+1, title)
    tw,th = scribus.getSize(title)

  h = th

  #content
  content = scribus.createText(x, y+h+1, w, 1)
  scribus.setText(cont["summary"], content)
  scribus.setTextAlignment(scribus.ALIGN_LEFT, content)
  scribus.setFont("Open Sans Regular", content)
  scribus.setFontSize(10, content)

  tw,th = scribus.getSize(content)
  while scribus.textOverflows(content):
    scribus.sizeObject(tw, th+1, content)
    tw,th = scribus.getSize(content)
    if h+th > bH:
      break

  h = h+th

  return h
Exemple #3
0
 def draw(self, tolevel):
    contents = []
    for (label,level,page) in self.sections:
       if level <= tolevel:
          text = label + chr(TAB) + str(page)
          style = "Contents" + str(level)
          contents.append((text,style))
    
    page = self.contentspage
    scribus.gotoPage(page)
    (width,height) = scribus.getPageSize()
    (top,left,right,bottom) = getCurrentPageMargins()
    frame = scribus.createText(left, top, width-right-left, TITLESIZE)
    insertTextWithStyle("Contents","Title",frame)
    
    frame = scribus.createText(left, top+TITLESIZE, width-right-left, height-top-bottom-TITLESIZE)
    scribus.setColumns(2,frame)
    scribus.setColumnGap(COLUMNGAP,frame)
    for (text,style) in contents:
       insertTextWithStyle(text,style,frame)
       if scribus.textOverflows(frame):
          oldframe = frame
          page = page + 1
          scribus.gotoPage(page)
          (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)
Exemple #4
0
def drawHeaderFooter(pagetitle):
    """draw some info on the pages"""
    # get page size
    pageSize=scribus.getPageSize()
    pageWidth=pageSize[0]
    pageHeight=pageSize[1]
    #pageMargins
    pageMargins=scribus.getPageMargins()
    topMargin=pageMargins[0]
    leftMargin=pageMargins[1]
    rightMargin=pageMargins[2]
    bottomMargin=pageMargins[3]

    #create textbox and insert text for header
    textbox=scribus.createText(leftMargin, topMargin,  pageWidth-leftMargin-rightMargin, HEADERSIZE)
    #set proper font size and alignment
    scribus.setFontSize(18, textbox)
    scribus.setTextAlignment(scribus.ALIGN_CENTERED, textbox)
    #load the string into the textbox
    headerstring=pagetitle
    scribus.insertText(headerstring, 0, textbox)
    scribus.setTextColor("Black", textbox)

    #create textbox and insert text for footer
    textbox=scribus.createText(leftMargin, pageHeight-bottomMargin-FOOTERSIZE,  pageWidth-leftMargin-rightMargin, FOOTERSIZE)
    #set proper font size and alignment
    scribus.setFontSize(9, textbox)
    scribus.setTextAlignment(scribus.ALIGN_LEFT, textbox)
    #load the string into the textbox
    footerstring="Created using ColorChart.py V %s script for Scribus by Sebastian Stetter - http://www.sebastianstetter.de" % str(__version__)
    scribus.insertText(footerstring, 0, textbox)
    scribus.setTextColor("Black", textbox)
Exemple #5
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)
Exemple #6
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)
Exemple #7
0
def newWikiTextBlock(cont, x, y, w):
    h = 0
    #title
    title = scribus.createText(x, y, w, 1)
    scribus.setText(cont["wp"].title, title)
    scribus.setTextAlignment(scribus.ALIGN_LEFT, title)
    scribus.setFont("Open Sans Bold", title)
    scribus.setFontSize(14, title)
    scribus.setLineSpacing(14, title)

    tw, th = scribus.getSize(title)
    while scribus.textOverflows(title):
        scribus.sizeObject(tw, th + 1, title)
        tw, th = scribus.getSize(title)

    h = th

    #content
    content = scribus.createText(x, y + h + 1, w, 1)
    scribus.setText(cont["summary"], content)
    scribus.setTextAlignment(scribus.ALIGN_LEFT, content)
    scribus.setFont("Open Sans Regular", content)
    scribus.setFontSize(10, content)

    tw, th = scribus.getSize(content)
    while scribus.textOverflows(content):
        scribus.sizeObject(tw, th + 1, content)
        tw, th = scribus.getSize(content)
        if h + th > bH:
            break

    h = h + th

    return h
Exemple #8
0
def textframes(text_id, x, y, width, height, bg_colour, text_colour, fontsize, font, spacing, parsedtext, layer, linespacing=0, resize=0):
	scribus.createText(x, y, width, height, text_id)
#scribus.text_id = scribus.createText(120, 10, 200, 20)
	scribus.setText(parsedtext, text_id)
	scribus.setFont(font, text_id)
	scribus.setTextColor(text_colour, text_id)
	scribus.setTextDistances(3*spacing, spacing, 0, spacing, text_id)
	scribus.sentToLayer(layer, text_id)
	scribus.setFontSize(fontsize, text_id)
Exemple #9
0
    def placeGuide(self, rock, sun, walk, graph, iconpath):
        """Build the header section of a guide"""
        if self.frame != None:
            (w, h) = scribus.getSize(self.frame)
            scribus.sizeObject(w, h + HEADERSIZE, self.frame)

            if os.path.exists(graph):
                img = scribus.createImage(self.leftmargin + 5,
                                          self.topmargin + 10, GRAPHSIZE,
                                          GRAPHSIZE)
                scribus.loadImage(graph, img)
                scribus.setScaleImageToFrame(True, True, img)

            offset = 13
            iconleft = self.leftmargin + 10 + GRAPHSIZE + 3
            txtleft = iconleft + ICONSIZE + 3
            framewidth = self.pagewidth - self.leftmargin - self.rightmargin
            if sun != "":
                img = scribus.createImage(iconleft, self.topmargin + offset,
                                          ICONSIZE, ICONSIZE)
                scribus.loadImage(iconpath + os.sep + "sun1.png", img)
                scribus.setScaleImageToFrame(True, True, img)
                #scribus.setCornerRadius(ROUNDS,img)
                icontxtframe = scribus.createText(txtleft,
                                                  self.topmargin + offset + 2,
                                                  framewidth - txtleft,
                                                  ICONSIZE)
                self.styleText(sun, "IconText", icontxtframe)
                offset = offset + ICONSIZE + 3

            if walk != "":
                img = scribus.createImage(iconleft, self.topmargin + offset,
                                          ICONSIZE, ICONSIZE)
                scribus.loadImage(iconpath + os.sep + "walk1.png", img)
                scribus.setScaleImageToFrame(True, True, img)
                #scribus.setCornerRadius(ROUNDS,img)
                icontxtframe = scribus.createText(txtleft,
                                                  self.topmargin + offset + 2,
                                                  framewidth - txtleft,
                                                  ICONSIZE)
                self.styleText(walk, "IconText", icontxtframe)
                offset = offset + ICONSIZE + 3

            if rock != "":
                img = scribus.createImage(iconleft, self.topmargin + offset,
                                          ICONSIZE, ICONSIZE)
                scribus.loadImage(iconpath + os.sep + "rock1.png", img)
                scribus.setScaleImageToFrame(True, True, img)
                #scribus.setCornerRadius(ROUNDS,img)
                icontxtframe = scribus.createText(txtleft,
                                                  self.topmargin + offset + 2,
                                                  framewidth - txtleft,
                                                  ICONSIZE)
                self.styleText(rock, "IconText", icontxtframe)
                offset = offset + ICONSIZE + 3
        self.endFrame()
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)
Exemple #11
0
def createCell(text, roffset, coffset, w, h, marginl, margint, isBlack):
    #Create textbox
    box=scribus.createRect(marginl+(roffset-1)*w,margint+(coffset-1)*h, w, h)
    textBox=scribus.createText(marginl+(roffset-1)*w,margint+(coffset-1)*h, w, h)
    #insert the text into textbox
    scribus.setFont("Arial Bold", textBox)
    
    
    
    #Default  font size
    fontSize=12
    if len(text) < 50: fontSize=14
    if len(text) < 20: fontSize=16
    scribus.setFontSize(fontSize, textBox)
    scribus.setTextDistances(3, 3, 3, 3, textBox)
    scribus.insertText(text, 0, textBox)

    #black card
    if isBlack==True:
        scribus.setFillColor("Black", box)
        scribus.setTextColor("White", textBox)
        scribus.setLineColor("White", box)


    #add Logo
    hOffset=37
    wOffset=5
    addLogo(marginl+(roffset-1)*w+wOffset,margint+(coffset-1)*h+hOffset, isBlack)
    return
Exemple #12
0
    def addWatermark(self):
        '''Create a Draft watermark layer. This was taken from:
			http://wiki.scribus.net/canvas/Adding_%27DRAFT%27_to_a_document'''

        L = len(self.watermark)  # The length of the word
        # will determine the font size
        scribus.defineColor("gray", 11, 11, 11, 11)  # Set your own color here

        u = scribus.getUnit()  # Get the units of the document
        al = scribus.getActiveLayer()  # Identify the working layer
        scribus.setUnit(
            scribus.UNIT_MILLIMETERS)  # Set the document units to mm,
        (w, h) = scribus.getPageSize()  # needed to set the text box size

        scribus.createLayer("c")
        scribus.setActiveLayer("c")

        T = scribus.createText(w / 6, 6 * h / 10, h,
                               w / 2)  # Create the text box
        scribus.setText(self.watermark, T)  # Insert the text
        scribus.setTextColor("gray", T)  # Set the color of the text
        scribus.setFontSize(
            (w / 210) * (180 - 10 * L),
            T)  # Set the font size according to length and width

        scribus.rotateObject(45, T)  # Turn it round antclockwise 45 degrees
        scribus.setUnit(u)  # return to original document units
        # FIXME: It would be nice if we could move the watermark box down to the lowest layer so
        # that it is under all the page text. Have not found a method to do this. For now we just
        # plop the watermark on top of everything else.
        scribus.setActiveLayer(al)  # return to the original active layer
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()
Exemple #14
0
 def pasteCaption(self, xpos, ypos, text, width, imgheight=0, footer=False):
     height = 5
     rect = scribus.createRect(xpos, ypos, width, height)
     scribus.setFillColor("Black", rect)
     scribus.setFillTransparency(0.60, rect)
     scribus.setCornerRadius(ROUNDS, rect)
     scribus.setLineColor("White", rect)
     scribus.setLineWidth(0.4, rect)
     frame = scribus.createText(xpos + 2, ypos + 1, width, height)
     self.styleText(text, "imageCaption", frame)
     scribus.setTextColor("White", frame)
     scribus.setFillColor("None", frame)
     # there are probably some performance issues in the following section of code
     if scribus.textOverflows(frame) == 0:
         # its a one liner, so shrink width
         while scribus.textOverflows(frame) == 0 and width > 5:
             width = width - 1
             scribus.sizeObject(width, height, frame)
         scribus.sizeObject(width + 2, height, frame)
         scribus.sizeObject(width + 4, height, rect)
     else:
         # its a multi liner, expand vertically
         while scribus.textOverflows(frame) > 0:
             height = height + 1
             scribus.sizeObject(width, height, frame)
         scribus.sizeObject(width, height + 1, rect)
     if footer:
         scribus.moveObject(0, imgheight - height - 1, rect)
         scribus.moveObject(0, imgheight - height - 1, frame)
     self.imageframes.append(rect)
     self.imageframes.append(frame)
Exemple #15
0
    def addWatermark (self) :
        '''Create a Draft watermark layer. This was taken from:
            http://wiki.scribus.net/canvas/Adding_%27DRAFT%27_to_a_document'''

        L = len(self.watermark)                         # The length of the word 
                                                        # will determine the font size
        scribus.defineColor("gray", 11, 11, 11, 11)     # Set your own color here

        u  = scribus.getUnit()                          # Get the units of the document
        al = scribus.getActiveLayer()                   # Identify the working layer
        scribus.setUnit(scribus.UNIT_MILLIMETERS)       # Set the document units to mm,
        (w,h) = scribus.getPageSize()                   # needed to set the text box size

        scribus.createLayer("c")
        scribus.setActiveLayer("c")

        T = scribus.createText(w/6, 6*h/10 , h, w/2)    # Create the text box
        scribus.setText(self.watermark, T)              # Insert the text
        scribus.setTextColor("gray", T)                 # Set the color of the text
        scribus.setFontSize((w/210)*(180 - 10*L), T)    # Set the font size according to length and width

        scribus.rotateObject(45, T)                     # Turn it round antclockwise 45 degrees
        scribus.setUnit(u)                              # return to original document units
# FIXME: It would be nice if we could move the watermark box down to the lowest layer so 
# that it is under all the page text. Have not found a method to do this. For now we just
# plop the watermark on top of everything else.
        scribus.setActiveLayer(al)                      # return to the original active layer
Exemple #16
0
 def pasteCaption(self, xpos, ypos, text, width, imgheight=0, footer=False):
    height = 5 
    rect = scribus.createRect(xpos, ypos, width, height)
    scribus.setFillColor("Black",rect)
    scribus.setFillTransparency(0.60,rect)
    scribus.setCornerRadius(ROUNDS,rect)
    scribus.setLineColor("White",rect)
    scribus.setLineWidth(0.4,rect)
    frame = scribus.createText(xpos+2, ypos+1, width, height)
    self.styleText(text, "imageCaption", frame)
    scribus.setTextColor("White",frame)
    scribus.setFillColor("None",frame)
    # there are probably some performance issues in the following section of code
    if scribus.textOverflows(frame) == 0:
       # its a one liner, so shrink width
       while scribus.textOverflows(frame) == 0 and width > 5:
          width = width - 1
          scribus.sizeObject(width, height, frame)
       scribus.sizeObject(width+2, height, frame)
       scribus.sizeObject(width+4, height, rect)
    else:
       # its a multi liner, expand vertically
       while scribus.textOverflows(frame) > 0:
          height = height + 1
          scribus.sizeObject(width, height, frame)
       scribus.sizeObject(width, height+1, rect)
    if footer:
       scribus.moveObject(0,imgheight - height - 1,rect)
       scribus.moveObject(0,imgheight - height - 1,frame)
    self.imageframes.append(rect)
    self.imageframes.append(frame)
Exemple #17
0
def createCell(text, roffset, coffset, w, h, marginl, margint, isBlack):
    #Create textbox
    box=scribus.createRect(marginl+(roffset-1)*w,margint+(coffset-1)*h, w, h)
    textBox=scribus.createText(marginl+(roffset-1)*w,margint+(coffset-1)*h, w, h)
    #insert the text into textbox
    scribus.setFont("Arial Bold", textBox)
    
    
    
    #Default  font size
    fontSize=12
    if len(text) < 50: fontSize=14
    if len(text) < 20: fontSize=16
    scribus.setFontSize(fontSize, textBox)
    scribus.setTextDistances(3, 3, 3, 3, textBox)
    scribus.insertText(text, 0, textBox)

    #black card
    if isBlack==True:
        scribus.setFillColor("Black", box)
        scribus.setTextColor("White", textBox)
        scribus.setLineColor("White", box)


    #add Logo
    hOffset=37
    wOffset=5
    addLogo(marginl+(roffset-1)*w+wOffset,margint+(coffset-1)*h+hOffset, isBlack)
    return
Exemple #18
0
def fill_page(contacts):
    #where contacts is an array or at most max_contact contacts
    assert(len(contacts) < MAX_PAGE_CONTACTS)
    
    nb_lines = (len(contacts) / (CONST_COL_NUMBER))  
    if((len(contacts) % CONST_COL_NUMBER) != 0):
        nb_lines = nb_lines+1
    for curline in range (0, nb_lines):
        nb_col = min(len(contacts) - (curline * CONST_COL_NUMBER), CONST_COL_NUMBER) 
        for curcol in range (0, nb_col):
            x = CONST_TOP_MARGIN + CONST_COL_SIZE * curline
            y = CONST_LEFT_MARGIN + CONST_LINE_SIZE * curcol
            txtFrameName= "etiketo"+str(curline)+str(curcol)
            scribus.createText(y, x, CONST_LINE_SIZE, CONST_COL_SIZE, txtFrameName)
            contact_idx=curline*CONST_COL_NUMBER+curcol
            scribus.setText(contacts[contact_idx].print_contact(), txtFrameName)
            scribus.setTextDistances(6, 0, 3, 0, txtFrameName) 
            scribus.setFontSize(10, txtFrameName)
            scribus.setFont("Liberation Serif Regular", txtFrameName)
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 create_toc(data):
    if not scribus.objectExists("TOC"):
        new_page()
        page_width, page_height, margin_top, margin_left, margin_right, margin_bottom = page_size_margin(1)
        toc = scribus.createText(margin_left, margin_top, page_width-margin_right-margin_left, page_height-margin_top-margin_bottom)
        scribus.setNewName("TOC", toc)
        scribus.insertText("provide a textframe with name 'TOC' in front_matter.sla and i will not create the toc at the end of the document", 0, "TOC")

    text = "\n".join(("{}\t{}".format(title, pagenum) for (title, pagenum) in data))
    scribus.insertText(text, -1, "TOC")
Exemple #21
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)
Exemple #22
0
 def placeGuide(self, rock, sun, walk, graph, iconpath):
    """Build the header section of a guide"""
    if self.frame != None:
       (w,h) = scribus.getSize(self.frame)
       scribus.sizeObject(w, h + HEADERSIZE, self.frame)
          
       if os.path.exists(graph):
          img = scribus.createImage(self.leftmargin + 5, self.topmargin + 10, GRAPHSIZE, GRAPHSIZE)
          scribus.loadImage(graph, img)
          scribus.setScaleImageToFrame(True,True,img)    
                   
       offset = 13
       iconleft = self.leftmargin + 10 + GRAPHSIZE + 3
       txtleft = iconleft + ICONSIZE + 3
       framewidth = self.pagewidth - self.leftmargin - self.rightmargin
       if sun != "":
          img = scribus.createImage(iconleft, self.topmargin + offset, ICONSIZE, ICONSIZE)
          scribus.loadImage(iconpath + os.sep + "sun1.png", img)
          scribus.setScaleImageToFrame(True,True,img)
          #scribus.setCornerRadius(ROUNDS,img)
          icontxtframe = scribus.createText(txtleft, self.topmargin + offset + 2, framewidth - txtleft, ICONSIZE)
          self.styleText(sun, "IconText", icontxtframe)
          offset = offset + ICONSIZE + 3
             
       if walk != "":
          img = scribus.createImage(iconleft, self.topmargin + offset, ICONSIZE, ICONSIZE)
          scribus.loadImage(iconpath + os.sep + "walk1.png", img)
          scribus.setScaleImageToFrame(True,True,img)    
          #scribus.setCornerRadius(ROUNDS,img)
          icontxtframe = scribus.createText(txtleft, self.topmargin + offset + 2, framewidth - txtleft, ICONSIZE)
          self.styleText(walk, "IconText", icontxtframe)
          offset = offset + ICONSIZE + 3
                
       if rock != "":
          img = scribus.createImage(iconleft, self.topmargin + offset, ICONSIZE, ICONSIZE)
          scribus.loadImage(iconpath + os.sep + "rock1.png", img)
          scribus.setScaleImageToFrame(True,True,img)    
          #scribus.setCornerRadius(ROUNDS,img)
          icontxtframe = scribus.createText(txtleft, self.topmargin + offset + 2, framewidth - txtleft, ICONSIZE)
          self.styleText(rock, "IconText", icontxtframe)
          offset = offset + ICONSIZE + 3
    self.endFrame()
Exemple #23
0
def addLogo(x, y, isBlack):
    #square side
    a=5
    #line
    line=0.01
    #angle
    angle=15
    #LightGrey
    scribus.defineColor("LightGrey",0,0,0,128)
    #DarkGrey
    scribus.defineColor("DarkGrey",0,0,0,192)
    
    # White cards colors
    squareColor1="Black"
    lineColor1="White"
    squareColor2="DarkGrey"
    lineColor2="White"
    squareColor3="LightGrey"
    lineColor3="White"
    titleColor="Black"
    
    # Black cards colors
    if isBlack==True:
        squareColor1="DarkGrey"
        lineColor1="DarkGrey"
        squareColor2="LightGrey"
        lineColor2="LightGrey"
        squareColor3="White"
        lineColor3="White"
        titleColor="White"
    
    square1=scribus.createRect(x, y+a/10, a, a)
    scribus.setLineWidth(1, square1)
    scribus.setFillColor(squareColor1, square1)
    scribus.setLineColor(lineColor1, square1)
    scribus.rotateObject(angle, square1)
    
    square2=scribus.createRect(x+a/2, y, a, a)
    scribus.setLineWidth(1, square2)
    scribus.setFillColor(squareColor2, square2)
    scribus.setLineColor(lineColor2, square2)
    
    square3=scribus.createRect(x+a, y, a, a)
    scribus.setLineWidth(1, square3)
    scribus.setFillColor(squareColor3, square3)
    scribus.setLineColor(lineColor3, square3)
    scribus.rotateObject(-angle, square3)
    
    title=scribus.createText(x+10,y+2, 50, 5)
    scribus.setFont("Arial Bold", title)
    scribus.setFontSize(8, title)
    scribus.insertText("Game of Filth", 0, title)
    scribus.setTextColor(titleColor, title)
    return
Exemple #24
0
def addLogo(x, y, isBlack):
    #square side
    a=5
    #line
    line=0.01
    #angle
    angle=15
    #LightGrey
    scribus.defineColor("LightGrey",0,0,0,128)
    #DarkGrey
    scribus.defineColor("DarkGrey",0,0,0,192)
    
    # White cards colors
    squareColor1="Black"
    lineColor1="White"
    squareColor2="DarkGrey"
    lineColor2="White"
    squareColor3="LightGrey"
    lineColor3="White"
    titleColor="Black"
    
    # Black cards colors
    if isBlack==True:
        squareColor1="DarkGrey"
        lineColor1="DarkGrey"
        squareColor2="LightGrey"
        lineColor2="LightGrey"
        squareColor3="White"
        lineColor3="White"
        titleColor="White"
    
    square1=scribus.createRect(x, y+a/10, a, a)
    scribus.setLineWidth(1, square1)
    scribus.setFillColor(squareColor1, square1)
    scribus.setLineColor(lineColor1, square1)
    scribus.rotateObject(angle, square1)
    
    square2=scribus.createRect(x+a/2, y, a, a)
    scribus.setLineWidth(1, square2)
    scribus.setFillColor(squareColor2, square2)
    scribus.setLineColor(lineColor2, square2)
    
    square3=scribus.createRect(x+a, y, a, a)
    scribus.setLineWidth(1, square3)
    scribus.setFillColor(squareColor3, square3)
    scribus.setLineColor(lineColor3, square3)
    scribus.rotateObject(-angle, square3)
    
    title=scribus.createText(x+10,y+2, 50, 5)
    scribus.setFont("Arial Bold", title)
    scribus.setFontSize(8, title)
    scribus.insertText("Cards Against Humanity", 0, title)
    scribus.setTextColor(titleColor, title)
    return
Exemple #25
0
def main(argv):
    """This is a documentation string. Write a description of what your code
    does here. You should generally put documentation strings ("docstrings")
    on all your Python functions."""
    #########################
    #  YOUR CODE GOES HERE  #
    #########################
    userdim = scribus.getUnit()  # get unit and change it to mm
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
    cellwidthleft = 0
    cellwidthright = 0
    cellHeight = 0
    pos = getPosition()
    while cellwidthleft <= 0:
        cellwidthL = scribus.valueDialog("Left Cell Width", "How wide (mm) do you wish left cells to be?", "30.0")
        cellwidthleft = float(cellwidthL)
    while cellwidthright <= 0:
        cellwidthR = scribus.valueDialog("Right Cell Width", "How wide (mm) do you wish right cells to be?", "30.0")
        cellwidthright = float(cellwidthR)
    while cellHeight <= 0:
        cellheight = scribus.valueDialog("Cell Height", "How tall (mm) do you wish cells to be?", "10.0")
        cellHeight = float(cellheight)
    data = getCSVdata()
    di = getDataInformation(data)
    hposition = pos[1]
    vposition = pos[0]

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

    scribus.groupObjects(objectlist)
    scribus.progressReset()
    scribus.setUnit(userdim)  # reset unit to previous value
    scribus.docChanged(True)
    scribus.statusMessage("Done")
    scribus.setRedraw(True)
def insert_text_frame():
    page_size = scribus.getPageSize()

    page_margins_right = scribus.getPageMargins()
    page_margins_left = (page_margins_right[0], page_margins_right[2], page_margins_right[1], page_margins_right[3])

    if (scribus.currentPage() % 2) == 1:
        page_margins = page_margins_right
    else:
        page_margins = page_margins_left

    name = 'test%d' % random.randint(100, 999)

    # x, y, width, height
    scribus.createText(page_margins[0],
                       page_margins[1],
                       page_size[0] - (page_margins[0] + page_margins[2]),
                       page_size[1] - (page_margins[1] + page_margins[3]),
                       name)
    scribus.setText("test", name)
Exemple #27
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)
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)
Exemple #29
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)
Exemple #30
0
def fill_page(contacts):
    #where contacts is an array or at most max_contact contacts
    assert (len(contacts) < MAX_PAGE_CONTACTS)

    nb_lines = (len(contacts) / (CONST_COL_NUMBER))
    if ((len(contacts) % CONST_COL_NUMBER) != 0):
        nb_lines = nb_lines + 1
    for curline in range(0, nb_lines):
        nb_col = min(
            len(contacts) - (curline * CONST_COL_NUMBER), CONST_COL_NUMBER)
        for curcol in range(0, nb_col):
            x = CONST_TOP_MARGIN + CONST_COL_SIZE * curline
            y = CONST_LEFT_MARGIN + CONST_LINE_SIZE * curcol
            txtFrameName = "etiketo" + str(curline) + str(curcol)
            scribus.createText(y, x, CONST_LINE_SIZE, CONST_COL_SIZE,
                               txtFrameName)
            contact_idx = curline * CONST_COL_NUMBER + curcol
            scribus.setText(contacts[contact_idx].print_contact(),
                            txtFrameName)
            scribus.setTextDistances(6, 0, 3, 0, txtFrameName)
            scribus.setFontSize(10, txtFrameName)
            scribus.setFont("Liberation Serif Regular", txtFrameName)
Exemple #31
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)
Exemple #32
0
    def setPageNumber (self, crds, pageSide, row, pageNumber) :
        '''Place the page number on the page if called for.'''

        if self.pageNumbers :
            # Make the page number box
            pNumBox = scribus.createText(crds[row]['pageNumXPos' + pageSide], crds[row]['pageNumYPos'], crds[row]['pageNumWidth'], crds[row]['pageNumHeight'])
            # Put the page number in it and format according to the page we are on
            scribus.setText(`pageNumber`, pNumBox)
            if pageSide == 'Odd' :
                scribus.setTextAlignment(scribus.ALIGN_RIGHT, pNumBox)
            else:
                scribus.setTextAlignment(scribus.ALIGN_LEFT, pNumBox)

            scribus.setFont(self.fonts['pageNum']['bold'], pNumBox)
            scribus.setFontSize(self.fonts['pageNum']['size'], pNumBox)
def create_toc(data):
    if not scribus.objectExists("TOC"):
        new_page()
        page_width, page_height, margin_top, margin_left, margin_right, margin_bottom = page_size_margin(
            1)
        toc = scribus.createText(margin_left, margin_top,
                                 page_width - margin_right - margin_left,
                                 page_height - margin_top - margin_bottom)
        scribus.setNewName("TOC", toc)
        scribus.insertText(
            "provide a textframe with name 'TOC' in front_matter.sla and i will not create the toc at the end of the document",
            0, "TOC")

    text = "\n".join(
        ("{}\t{}".format(title, pagenum) for (title, pagenum) in data))
    scribus.insertText(text, -1, "TOC")
Exemple #34
0
def drawColor(colorname, h, v, width, height):  # h horizontal position, v vertical position
    """draws a color chart field with its caption for the given colorname at the h and v position
    """
    # get cmyk values and convert them to 0 - 255 values
    color = scribus.getColor(colorname)
    c = int(round(color[0] / 2.55))
    m = int(round(color[1] / 2.55))
    y = int(round(color[2] / 2.55))
    k = int(round(color[3] / 2.55))
    # get rgb color
    rgbcolor = scribus.getColorAsRGB(colorname)
    r = rgbcolor[0]
    g = rgbcolor[1]
    b = rgbcolor[2]
    # get webcolor
    webcolor = rgbhex(r, g, b)
    # but String for Textbox together
    colorDisplay = colorname
    if scribus.isSpotColor(colorname):
        colorDisplay += " (Spot Color)"
    colorstring = "%s\nC %i, M %i, Y %i, K %i, \nR %i, G %i, B %i \nRGB: %s" % (
        colorDisplay,
        c,
        m,
        y,
        k,
        r,
        g,
        b,
        webcolor,
    )

    # draw rectangle and set colors
    rect = scribus.createRect(h, v, width, height)
    scribus.setFillColor(colorname, rect)
    # if total amount of color is < 20 draw outline in Black for rectangle, else in same color
    if c + m + y + k < 20:
        scribus.setLineColor("Black", rect)
    else:
        scribus.setLineColor(colorname, rect)
    # create textbox and insert text
    textbox = scribus.createText(h + width + 5, v, 50, height)
    # set proper font size
    scribus.setFontSize(11, textbox)
    scribus.setTextAlignment(scribus.ALIGN_LEFT, textbox)
    # load the string into the textbox
    scribus.insertText(colorstring, 0, textbox)
Exemple #35
0
    def setPageNumber(self, crds, pageSide, row, pageNumber):
        '''Place the page number on the page if called for.'''

        if self.pageNumbers:
            # Make the page number box
            pNumBox = scribus.createText(crds[row]['pageNumXPos' + pageSide],
                                         crds[row]['pageNumYPos'],
                                         crds[row]['pageNumWidth'],
                                         crds[row]['pageNumHeight'])
            # Put the page number in it and format according to the page we are on
            scribus.setText( ` pageNumber `, pNumBox)
            if pageSide == 'Odd':
                scribus.setTextAlignment(scribus.ALIGN_RIGHT, pNumBox)
            else:
                scribus.setTextAlignment(scribus.ALIGN_LEFT, pNumBox)

            scribus.setFont(self.fonts['pageNum']['bold'], pNumBox)
            scribus.setFontSize(self.fonts['pageNum']['size'], pNumBox)
Exemple #36
0
   def newFrame(self, height=MINFRAMESIZE, columns=2):
      """Start a new text frame.
         If we are working with 2 columns, we build each column as a seperate frame.
         Scribus does support multi column text frames, but with no keep-with-next
         functionality its of no use."""

      self.flushImages()
      if columns == 2 and self.frame != None and self.currentcolumn == 1:
         # Start the second column.
         (x,y) = scribus.getPosition(self.frame)
         (w,h) = scribus.getSize(self.frame)
         width = w
         xpos = x + w + COLUMNGAP
         ypos = y
         self.currentcolumn = 2
      else:
         # First column or full width frame
         while True:
            ypos = self.topmargin
            for obj in scribus.getAllObjects():
               if obj in self.textframes:
                  (x,y) = scribus.getPosition(obj)
                  (w,h) = scribus.getSize(obj)
                  if y + h > ypos: 
                     ypos = y + h + FRAMEGAP
            if ypos + height > self.pageheight - self.bottommargin:
               self.newPage()
               self.flushImages()
            else:
               break
         xpos = self.leftmargin
         if columns == 1: 
            width = self.pagewidth - self.leftmargin - self.rightmargin
            self.currentcolumn = 0
         else:            
            width = self.columnwidth
            self.currentcolumn = 1
                                
      self.frame = scribus.createText(xpos, ypos, width, height)
      self.contents = []
      self.buffer = []
      self.columns = columns
      self.framelinked = False
      self.textframes.append(self.frame)
Exemple #37
0
    def newFrame(self, height=MINFRAMESIZE, columns=2):
        """Start a new text frame.
         If we are working with 2 columns, we build each column as a seperate frame.
         Scribus does support multi column text frames, but with no keep-with-next
         functionality its of no use."""

        self.flushImages()
        if columns == 2 and self.frame != None and self.currentcolumn == 1:
            # Start the second column.
            (x, y) = scribus.getPosition(self.frame)
            (w, h) = scribus.getSize(self.frame)
            width = w
            xpos = x + w + COLUMNGAP
            ypos = y
            self.currentcolumn = 2
        else:
            # First column or full width frame
            while True:
                ypos = self.topmargin
                for obj in scribus.getAllObjects():
                    if obj in self.textframes:
                        (x, y) = scribus.getPosition(obj)
                        (w, h) = scribus.getSize(obj)
                        if y + h > ypos:
                            ypos = y + h + FRAMEGAP
                if ypos + height > self.pageheight - self.bottommargin:
                    self.newPage()
                    self.flushImages()
                else:
                    break
            xpos = self.leftmargin
            if columns == 1:
                width = self.pagewidth - self.leftmargin - self.rightmargin
                self.currentcolumn = 0
            else:
                width = self.columnwidth
                self.currentcolumn = 1

        self.frame = scribus.createText(xpos, ypos, width, height)
        self.contents = []
        self.buffer = []
        self.columns = columns
        self.framelinked = False
        self.textframes.append(self.frame)
Exemple #38
0
 def createNewPage(self, tbox):
     curPage = scribus.currentPage()
     if curPage < scribus.pageCount() - 1:
         where = curPage + 1
     else:
         where = -1
     logger.debug("cur=%d name=%s pc=%d wh=%d", curPage, tbox,
                  scribus.pageCount(), where)
     cols = scribus.getColumns(tbox)
     colgap = scribus.getColumnGap(tbox)
     x, y = scribus.getPosition(tbox)
     w, h = scribus.getSize(tbox)
     mp = scribus.getMasterPage(curPage)
     scribus.newPage(where, mp)  # return val?
     scribus.gotoPage(curPage + 1)
     newBox = scribus.createText(x, y, w, h)
     scribus.setColumns(cols, newBox)
     scribus.setColumnGap(colgap, newBox)
     scribus.linkTextFrames(tbox, newBox)
     logger.debug("link from %s to %s", tbox, newBox)
     return newBox
Exemple #39
0
def drawColor(colorname, h, v, width,
              height):  #h horizontal position, v vertical position
    """draws a color chart field with its caption for the given colorname at the h and v position
    """
    #get cmyk values and convert them to 0 - 255 values
    color = scribus.getColor(colorname)
    c = int(round(color[0] / 2.55))
    m = int(round(color[1] / 2.55))
    y = int(round(color[2] / 2.55))
    k = int(round(color[3] / 2.55))
    #get rgb color
    rgbcolor = scribus.getColorAsRGB(colorname)
    r = rgbcolor[0]
    g = rgbcolor[1]
    b = rgbcolor[2]
    #get webcolor
    webcolor = rgbhex(r, g, b)
    #but String for Textbox together
    colorDisplay = colorname
    if scribus.isSpotColor(colorname):
        colorDisplay += " (Spot Color)"
    colorstring = "%s\nC %i, M %i, Y %i, K %i, \nR %i, G %i, B %i \nRGB: %s" % (
        colorDisplay, c, m, y, k, r, g, b, webcolor)

    #draw rectangle and set colors
    rect = scribus.createRect(h, v, width, height)
    scribus.setFillColor(colorname, rect)
    #if total amount of color is < 20 draw outline in Black for rectangle, else in same color
    if c + m + y + k < 20:
        scribus.setLineColor("Black", rect)
    else:
        scribus.setLineColor(colorname, rect)
    #create textbox and insert text
    textbox = scribus.createText(h + width + 5, v, 50, height)
    #set proper font size
    scribus.setFontSize(11, textbox)
    scribus.setTextAlignment(scribus.ALIGN_LEFT, textbox)
    #load the string into the textbox
    scribus.insertText(colorstring, 0, textbox)
    scribus.setTextColor("Black", textbox)
    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
Exemple #41
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)
offsetX = 0.3
offsetXX = 0.2
offsetY = 0.15
minResultA = 0
maxResultA = 14
minResultB = 1
maxResultB = 3
rx = [[0 for col in range(100)] for row in range(100)]
ry = [[0 for col in range(100)] for row in range(100)]

scribus.newDocument((pageX, pageY), (0.0, 0.0, 0.0, 0.0), scribus.PORTRAIT, 1, scribus.UNIT_INCHES, scribus.PAGE_1, 0, 1)
scribus.defineColor("gray",21,21,21,21)

for x in range(0,maxX):
	for y in range(0,maxY):
		q = scribus.createText((x*((pageX*0.9)/maxX))+offsetX, (y*(pageY/maxY))+offsetY, (pageX*0.9)/maxX, pageY/maxY)
		scribus.setFont('Arial Regular',q)
		scribus.setFontSize(48, q)
		if random.randint(0, 1) == 0:
			rx[x][y] = random.randint(minResultB, maxResultB) 
			ry[x][y] = random.randint(minResultA, maxResultA)
		else:
			rx[x][y] = random.randint(minResultA, maxResultA)
			ry[x][y] = random.randint(minResultB, maxResultB)
		rxx = rx[x][y]
		ryy = ry[x][y]
		scribus.insertText('%(rxx)d + %(ryy)d =__' % locals(), 0, q)
scribus.newPage(-1)
xx = 0
for x in range(maxX-1,-1,-1):
	for y in range(0,maxY):
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")
Exemple #44
0
def main(argv):
    """This is a documentation string. Write a description of what your code
    does here. You should generally put documentation strings ("docstrings")
    on all your Python functions."""
    #########################
    #  YOUR CODE GOES HERE  #
    #########################
    userdim = scribus.getUnit()  #get unit and change it to mm
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
    cellwidthleft = 0
    cellwidthright = 0
    cellHeight = 0
    pos = getPosition()
    while cellwidthleft <= 0:
        cellwidthL = scribus.valueDialog(
            'Left Cell Width', 'How wide (mm) do you wish left cells to be?',
            '30.0')
        cellwidthleft = float(cellwidthL)
    while cellwidthright <= 0:
        cellwidthR = scribus.valueDialog(
            'Right Cell Width', 'How wide (mm) do you wish right cells to be?',
            '30.0')
        cellwidthright = float(cellwidthR)
    while cellHeight <= 0:
        cellheight = scribus.valueDialog(
            'Cell Height', 'How tall (mm) do you wish cells to be?', '10.0')
        cellHeight = float(cellheight)
    data = getCSVdata()
    di = getDataInformation(data)
    hposition = pos[1]
    vposition = pos[0]

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

    scribus.groupObjects(objectlist)
    scribus.progressReset()
    scribus.setUnit(userdim)  # reset unit to previous value
    scribus.docChanged(True)
    scribus.statusMessage("Done")
    scribus.setRedraw(True)
def 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
 def make_textframe (self):
     margins = scribus.getPageMargins()
     size = scribus.getPageSize()
     w = size[0] - margins[1] - margins[3]
     h = size[1] - margins[0] - margins[2]
     return scribus.createText (margins[1], margins[0], w, h)
Exemple #47
0
def main(argv):
    unit = scribus.getUnit()
    units = [' pts','mm',' inches',' picas','cm',' ciceros']
    unitlabel = units[unit]
    if scribus.selectionCount() == 0:
        scribus.messageBox('Scribus - Script Error',
            "There is no object selected.\nPlease select a text frame and try again.",
            scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(2)
    if scribus.selectionCount() > 1:
        scribus.messageBox('Scribus - Script Error',
            "You have more than one object selected.\nPlease select one text frame and try again.",
            scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(2)
    textbox = scribus.getSelectedObject()
    pageitems = scribus.getPageItems()
    boxcount = 1
    for item in pageitems:
        if (item[0] == textbox):
            if (item[1] != 4):
                scribus.messageBox('Scribus - Script Error', 
                          "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK)
                sys.exit(2)

# While we're finding out what kind of frame is selected, we'll also make sure we
# will come up with a unique name for our infobox frame - it's possible we may want
# more than one for a multicolumn frame.
        if (item[0] == ("infobox" + str(boxcount) + textbox)):
                boxcount += 1
    left, top = scribus.getPosition(textbox)
    o_width, o_height = scribus.getSize(textbox)
    o_cols = int(scribus.getColumns(textbox))
    o_gap = scribus.getColumnGap(textbox)
            
    columns_width = 0
    column_pos = 0
    o_colwidth = (o_width - ((o_cols - 1) * o_gap)) / o_cols
    if (o_cols > 1):
        while (columns_width > o_cols or columns_width < 1):
            columns_width = scribus.valueDialog('Width',
                                            'How many columns width shall the '+
                                            'box be (max ' + str(o_cols) + ')?','1')
            columns_width = int(columns_width)
        if (columns_width < o_cols):
            max = o_cols - columns_width
            while (column_pos <= max and column_pos <= 1):
                column_pos = scribus.valueDialog('Placement',
                                         'In which column do you want '
                                         'to place the box (1 to ' +
                                         str(o_cols) + ')?','1')
            column_pos = int(column_pos) - 1 
    if (o_cols == 1):
	columns_width = 1
    new_height = 0
    while (new_height == 0):
        new_height = scribus.valueDialog('Height','Your frame height is '+ str(o_height) +
                                                 unitlabel +'. How tall\n do you want your ' +
                                                 'infobox to be in '+ unitlabel +'?\n If you load an image, height will be\n calculated, so the value here does not\n matter.', str(o_height))
    new_top = -1
    while (new_top < 0):
        new_top = scribus.valueDialog('Y-Pos','The top of your infobox is currently\n'+ str(top) +
                                                 unitlabel +'. Where do you want \n' +
                                                 'the top to be in '+ unitlabel +'?', str(top))
    framename = scribus.valueDialog('Name of Frame','Name your frame or use this default name',"infobox" + str(boxcount) + textbox)
    frametype = 'text'
    frametype = scribus.valueDialog('Frame Type','Change to anything other\n than "text" for image frame.\nEnter "imageL" to also load an image',frametype)
    new_width = columns_width * o_colwidth + (columns_width-1) * o_gap
    new_left = left + ((column_pos) * o_colwidth) + ((column_pos) * o_gap)
    if (frametype == 'text'):
        new_textbox = scribus.createText(new_left, float(new_top), new_width, float(new_height),framename)
        scribus.setColumnGap(0, new_textbox)
        scribus.setColumns(1, new_textbox)
        scribus.textFlowMode(new_textbox, 1)
    else:
        if (frametype == 'imageL'):
	    imageload = scribus.fileDialog('Load image','Images(*.jpg *.png *.tif *.JPG *.PNG *.jpeg *.JPEG *.TIF)',haspreview=1)
	    new_image = scribus.createImage(new_left, float(new_top), new_width, float(new_height),framename)
	    scribus.loadImage(imageload, new_image)
            scribus.messageBox('Please Note',"Your frame will be created once you click OK.\n\nUse the Context Menu to Adjust Frame to Image.\n\nIf your image does not fill the width completely,\nstretch the frame vertically first.",scribus.BUTTON_OK)
        else:
	    new_image = scribus.createImage(new_left, float(new_top), new_width, float(new_height),framename)
        scribus.textFlowMode(new_image, 1)
        scribus.setScaleImageToFrame(scaletoframe=1, proportional=1, name=new_image)
Exemple #48
0
# Database related issues
try:
    conn = MySQLdb.connect(passwd=password,
                           db=dbname,
                           host=hostname,
                           user=username)
except:
    scribus.messageBox(
        'DB connection example',
        'Connection error. You should specify your login in the script')
    sys.exit(1)

cur = conn.cursor()
# get the list of the databases
# it's like 'select * from dba_tables' in Oracle
count = cur.execute('show tables')
# formating the output
result = str(count) + ' table(s) in the ' + dbname + ' database.\n\n'
for i in cur.fetchall():
    result = result + i[0] + '\n'

# Scribus presentation part
scribus.newDoc(scribus.PAPER_A5, (10, 10, 20, 20), scribus.PORTRAIT, 1,
               scribus.UNIT_POINTS, scribus.NOFACINGPAGES,
               scribus.FIRSTPAGERIGHT)
txtName = scribus.createText(10, 10, 200, 200)
scribus.setText(result, txtName)

scribus.statusMessage('Script done.')
                      unit=scribus.UNIT_INCHES,
                      pagesType=scribus.FACINGPAGES,
                      firstPageOrder=scribus.FIRSTPAGERIGHT,
                      numPages=1
                      )

create_document()

if COVER_PHOTO:
    frame = scribus.createImage(-0.4723, 0, 12.5788, 8.3681) # après essai, cf F2
    scribus.loadImage(COVER_PHOTO, frame)
    scribus.setScaleImageToFrame(scaletoframe=1, proportional=1, name=frame)

scribus.createText(0,
                   0,
                   cover_width,
                   cover_height,
                   "total")

# x, y, width, height
scribus.createText((bleed + margin_out),
                   (bleed + margin_out),
                   frame_width,
                   frame_height,
                   "back")
scribus.createText((bleed + interior_width),
                   0,
                   spine_width,
                   cover_height,
                   "spine")
scribus.createText((bleed + interior_width + spine_width + margin_in),
Exemple #50
0
def main(argv):

    scribus.setUnit(scribus.UNIT_MILLIMETERS)

    # get page size
    pagesize = scribus.getPageSize()

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

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

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

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

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

    #progressbar max
    scribus.progressTotal(pagenum)

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

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

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

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

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

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

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

        # add page number to iteration
        page += 1

    # go back to active layer
    scribus.setActiveLayer(activelayer)
Exemple #51
0
def main(argv):
    unit = scribus.getUnit()
    units = [' pts', 'mm', ' inches', ' picas', 'cm', ' ciceros']
    unitlabel = units[unit]
    if scribus.selectionCount() == 0:
        scribus.messageBox(
            'Scribus - Script Error',
            "There is no object selected.\nPlease select a text frame and try again.",
            scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(2)
    if scribus.selectionCount() > 1:
        scribus.messageBox(
            'Scribus - Script Error',
            "You have more than one object selected.\nPlease select one text frame and try again.",
            scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(2)
    textbox = scribus.getSelectedObject()
    pageitems = scribus.getPageItems()
    boxcount = 1
    for item in pageitems:
        if (item[0] == textbox):
            if (item[1] != 4):
                scribus.messageBox('Scribus - Script Error',
                                   "This is not a textframe. Try again.",
                                   scribus.ICON_WARNING, scribus.BUTTON_OK)
                sys.exit(2)


# While we're finding out what kind of frame is selected, we'll also make sure we
# will come up with a unique name for our infobox frame - it's possible we may want
# more than one for a multicolumn frame.
        if (item[0] == ("infobox" + str(boxcount) + textbox)):
            boxcount += 1
    left, top = scribus.getPosition(textbox)
    o_width, o_height = scribus.getSize(textbox)
    o_cols = int(scribus.getColumns(textbox))
    o_gap = scribus.getColumnGap(textbox)

    columns_width = 0
    column_pos = 0
    o_colwidth = (o_width - ((o_cols - 1) * o_gap)) / o_cols
    if (o_cols > 1):
        while (columns_width > o_cols or columns_width < 1):
            columns_width = scribus.valueDialog(
                'Width', 'How many columns width shall the ' + 'box be (max ' +
                str(o_cols) + ')?', '1')
            columns_width = int(columns_width)
        if (columns_width < o_cols):
            max = o_cols - columns_width
            while (column_pos <= max and column_pos <= 1):
                column_pos = scribus.valueDialog(
                    'Placement', 'In which column do you want '
                    'to place the box (1 to ' + str(o_cols) + ')?', '1')
            column_pos = int(column_pos) - 1
    if (o_cols == 1):
        columns_width = 1
    new_height = 0
    while (new_height <= 0):
        new_height = scribus.valueDialog(
            'Height', 'Your frame height is ' + str(o_height) + unitlabel +
            '. How tall\n do you want your ' + 'infobox to be in ' +
            unitlabel +
            '?\n If you load an image with the script, height will be\n calculated, so the value here will not\n matter in that case.',
            str(o_height))
        if (not new_height):
            sys.exit(0)
        new_height = float(new_height)
    new_top = -1
    while (new_top < 0):
        new_top = scribus.valueDialog(
            'Y-Pos',
            'The top of your infobox is currently\n' + str(top) + unitlabel +
            '. Where do you want \n' + 'the top to be in ' + unitlabel + '?',
            str(top))
        if (not new_top):
            sys.exit(0)
        new_top = float(new_top)
    framename = scribus.valueDialog(
        'Name of Frame', 'Name your frame or use this default name',
        "infobox" + str(boxcount) + textbox)
    if (not framename):
        sys.exit(0)
    frametype = 'text'
    frametype = scribus.valueDialog(
        'Frame Type',
        'Change to anything other\n than "text" for image frame.\nEnter "imageL" to also load an image',
        frametype)
    if (not frametype):
        sys.exit(0)
    new_width = columns_width * o_colwidth + (columns_width - 1) * o_gap
    new_left = left + ((column_pos) * o_colwidth) + ((column_pos) * o_gap)
    if (frametype == 'text'):
        new_textbox = scribus.createText(new_left, float(new_top), new_width,
                                         float(new_height), framename)
        scribus.setColumnGap(0, new_textbox)
        scribus.setColumns(1, new_textbox)
        scribus.textFlowMode(new_textbox, 1)
    else:
        if (frametype == 'imageL'):
            imageload = scribus.fileDialog(
                'Load image',
                'Images(*.jpg *.png *.tif *.JPG *.PNG *.jpeg *.JPEG *.TIF)',
                haspreview=1)
            new_image = scribus.createImage(new_left,
                                            float(new_top), new_width,
                                            float(new_height), framename)
            scribus.textFlowMode(new_image, 1)
            scribus.loadImage(imageload, new_image)
            scribus.setScaleImageToFrame(1, 0, new_image)
            currwidth, currheight = scribus.getSize(new_image)
            Xscale, Yscale = scribus.getImageScale(new_image)
            if (Xscale != Yscale):
                scribus.sizeObject(currwidth, currheight * Xscale / Yscale,
                                   new_image)
            scribus.setScaleImageToFrame(1, 1, new_image)
        else:
            new_image = scribus.createImage(new_left,
                                            float(new_top), new_width,
                                            float(new_height), framename)
            scribus.textFlowMode(new_image, 1)
            scribus.setScaleImageToFrame(1, 1, new_image)
Exemple #52
0
    scribus.messageBox('Selection Count', "You must have at least one object selected",
                       scribus.ICON_WARNING, scribus.BUTTON_OK)
    sys.exit(2)

captionloc = scribus.valueDialog("Caption Location","Where to put the caption(s) -\n B/T/R/L?", "b")
captionloc = captionloc[0]
location = captionloc.upper()

pageunits = scribus.getUnit()
scribus.setUnit(scribus.UNIT_POINTS)

while count < numselect:
    frames.append(scribus.getSelectedObject(count))
    count += 1
    
for frame in frames:
    fwidth, fheight = scribus.getSize(frame)
    fx, fy = scribus.getPosition(frame)
    if location == "B":
        textf = scribus.createText(fx, fy+fheight, fwidth, 24)
    elif location == "T":
        textf = scribus.createText(fx, fy-24, fwidth, 24)
    elif location == "R":
        textf = scribus.createText(fx + fwidth, fy, 150, 40)
    elif location == "L":
        textf = scribus.createText(fx-150, fy + fheight - 40, 150, 40)
scribus.setUnit(pageunits)

scribus.setRedraw(True)

Exemple #53
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
hostname = 'server.foo.org'
dbname = 'name'
username = '******'
password = '******'

# connection to the network wide server would be time consuming. So get the hint to the user.
scribus.statusMessage('Connecting to the ' + hostname + ' server. Be patient, please...')

# Database related issues
try:
    conn = MySQLdb.connect(passwd=password, db=dbname, host=hostname, user=username)
except:
	scribus.messageBox('DB connection example', 'Connection error. You should specify your login in the script')
	sys.exit(1)

cur = conn.cursor()
# get the list of the databases
# it's like 'select * from dba_tables' in Oracle
count = cur.execute('show tables')
# formating the output
result = str(count) + ' table(s) in the ' + dbname + ' database.\n\n'
for i in cur.fetchall():
    result = result + i[0] + '\n'

# Scribus presentation part
scribus.newDoc(scribus.PAPER_A5, (10, 10, 20, 20), scribus.PORTRAIT, 1, scribus.UNIT_POINTS, scribus.NOFACINGPAGES, scribus.FIRSTPAGERIGHT)
txtName = scribus.createText(10, 10, 200, 200)
scribus.setText(result, txtName)

scribus.statusMessage('Script done.')
Exemple #56
0
	scribus.createLayer("randombars")
	scribus.createLayer("randomcircles")
	scribus.createLayer("textlayer")


distros.keys().sort()

for distro in sorted(distros.iterkeys()):
	# extract the dictionary content
	description = distros[distro][0]
	filesizeiso = distros[distro][1]
	md5sum = distros[distro][2]
	modified = distros[distro][3]

	# create page title/header
	B = scribus.createText(left_page_x, 10, 100, 10)
	scribus.setText(distro, B)
	scribus.setFont("Gentium Plus Compact Regular", B)
	scribus.setTextAlignment(scribus.ALIGN_LEFT, B)
	scribus.setFontSize(18, B)
	
	# load small-logo into page
	imagedir = "./logos/"
	f = scribus.createImage(left_page_x, 23, 65, 65)
	scribus.loadImage(imagedir + distro + ".png", f)
	scribus.setScaleImageToFrame(1,1,f)
	scribus.sentToLayer("textlayer", f)

	# get description text for each distro
	scribus.createText(left_page_x, 92, 120, 80,distro)
	scribus.setText(description, distro)
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,
        )
    # 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)