Esempio n. 1
0
def main_wrapper(argv):
    try:
        if(scribus.haveDoc()):
            scribus.setRedraw(False)
        scribus.statusMessage(CONST.APP_NAME)
        scribus.progressReset()
        main(argv)
    finally:
        # Exit neatly even if the script terminated with an exception,
        # so we leave the progress bar and status bar blank and make sure
        # drawing is enabled.
        if(scribus.haveDoc()):
            scribus.setRedraw(True)
        scribus.statusMessage('')
        scribus.progressReset()
Esempio n. 2
0
def main(argv):
    """Main method - here we check if we have a doc - else we open one. we get all the colors and write them to a csv file."""
    if scribus.haveDoc() > 0:  #DOC OPEN
    #get colors, get filename, write stuff
        cols = getColorsFromDoc()
        filename = scribus.fileDialog("color2csv: Save csv color file", defaultname="colors.csv",  issave=True ,  haspreview=False)
        
        #@TODO: optimize path checking
        if filename !="":
            if os.path.exists(filename): #make sure we don't accidentally overwrite existing files
                answer= scribus.messageBox("color2csv", "File already exists! \n do you want to overwrite it?",  icon=scribus.ICON_WARNING,  button1=scribus.BUTTON_YES,  button2=scribus.BUTTON_ABORT)
                if answer == scribus.BUTTON_YES:
                    writeColorCsvFile(filename,  cols)
                else:
                    sys.exit()
            else:
                writeColorCsvFile(filename,  cols)
        else:
            sys.exit()
    else: # NO DOC OPEN - open one!
        scribusfile = scribus.fileDialog("color2csv: Open scribus file",  "Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)")
        if scribusfile !="":
            try:
                scribus.openDoc(scribusfile)
            except:
                scribus.messageBox("color2csv", "Could not open file!")
                sys.exit()
            #get colors, get filename, write stuff
            cols = getColorsFromDoc()
            filename = scribus.fileDialog("color2csv: Save csv color file", defaultname="colors.csv",  issave=True )
            writeColorCsvFile(filename,  cols)
        else:
            sys.exit()
def main_wrapper(argv):
    try:
        if(scribus.haveDoc()):
            scribus.setRedraw(False)
            scribus.statusMessage(CONST.APP_NAME)
            scribus.progressReset()
            main(argv)
        else:
            scribus.messageBox('Usage Error', 'You need a Document open', icon=scribus.ICON_WARNING, button1=scribus.BUTTON_OK)
            sys.exit(2)
    finally:
        # Exit neatly even if the script terminated with an exception,
        # so we leave the progress bar and status bar blank and make sure
        # drawing is enabled.
        if scribus.haveDoc():
            scribus.setRedraw(True)
        scribus.statusMessage("")
        scribus.progressReset()
def main():
    """ Application/Dialog loop with Scribus sauce around """
    try:
        root = Tk()
        app = TkImageAlignmentWizard(root)
        root.mainloop()
    finally:
        if scribus.haveDoc():
            scribus.redrawAll()
Esempio n. 5
0
def main_wrapper(argv):
  try:
		scribus.statusMessage("Running script...")
		scribus.progressReset()
		main(argv)
  finally:
		if scribus.haveDoc():
		    scribus.setRedraw(True)
		scribus.statusMessage("")
		scribus.progressReset()
def main():
    cache = defaultdict(dict)
    try:
        with open(CACHE_FILE, "rb") as cache_file:
            cache = defaultdict(dict, json.load(cache_file))
    except:
        pass

    with open(DATA_FILE, "rb") as data_file:
        songs_data = json.load(data_file)

    with open(MANUEL_PROCESSING_FILE, "rb") as manual_file:
        manual_processing = defaultdict(dict, json.load(manual_file))

    scribus.statusMessage("Running script...")
    scribus.progressReset()
    scribus.progressTotal(len(songs_data))

    init()
    front_matter()
    add_page_number()

    # trying to get the best sorting
    # setting all songs to the max height
    all_songs = dict(zip(songs_data.keys(), [EFFECTIVE_PAGE_HEIGHT] * len(songs_data)))
    # update according to cache
    for song_name, data in cache.iteritems():
        all_songs[song_name] = min(data.get("height", EFFECTIVE_PAGE_HEIGHT), EFFECTIVE_PAGE_HEIGHT)
    # let's see which songs should be set on a double sided page:
    songs_double_page = filter(lambda x: manual_processing[x].get("double_page", False), manual_processing)
    for double_page in songs_double_page:
        all_songs[double_page] = EFFECTIVE_PAGE_HEIGHT # all double page songs should get a whole page despite their height

    appendix_filter = lambda a_s, boolean : {k:v for k,v in a_s.iteritems() if manual_processing[k].get("appendix", False) == boolean}

    main_songs = appendix_filter(all_songs, False)
    add_songs(main_songs, songs_double_page, manual_processing, songs_data, cache)

    appendix_songs = appendix_filter(all_songs, True)
    add_songs(appendix_songs, songs_double_page, manual_processing, songs_data, cache)


    toc = []
    for filename in filter(lambda s: manual_processing[s].get("show", True), all_songs.keys()):
        toc.append((songs_data[filename]["name"], cache[filename].get("page", "XX")))
    toc.sort(key=lambda (x,y): x)
    create_toc(toc)

    if scribus.haveDoc():
        scribus.setRedraw(True)
        scribus.statusMessage("")
        scribus.progressReset()

    with open(CACHE_FILE, "wb") as cache_file:
        json.dump(cache, cache_file, indent=2)
Esempio n. 7
0
def main_wrapper():
   """The main_wrapper() function disables redrawing, sets a sensible generic
   status bar message, and optionally sets up the progress bar. It then runs
   the main() function. Once everything finishes it cleans up after the main()
   function, making sure everything is sane before the script terminates."""
   scribus.messageBox("Version",SCRIPT_VERSION)
   if not scribus.haveDoc():
      scribus.messageBox("Bwaaaahaha","Need a base document open")
   else:
      scribus.setRedraw(False)
      try:
          scribus.statusMessage("Running script...")
          scribus.progressReset()
          main()
      finally:
          # Exit neatly even if the script terminated with an exception,
          # so we leave the progress bar and status bar blank and make sure
          # drawing is enabled.
          if scribus.haveDoc():
              scribus.setRedraw(True)
              scribus.docChanged(True)
          scribus.statusMessage("")
          scribus.progressReset()
def main(argv):
    """The main() function disables redrawing, sets a sensible generic
    status bar message, and optionally sets up the progress bar. It then runs
    the main() function. Once everything finishes it cleans up after the create()
    function, making sure everything is sane before the script terminates."""
    currentDoc = scribus.getDocName()
    try:
        scribus.statusMessage("Importing .csv table...")
        scribus.progressReset()
        create(argv)
        if scribus.haveDoc():
	  scribus.closeDoc()
	scribus.openDoc(currentDoc)
    finally:
        # Exit neatly even if the script terminated with an exception,
        # so we leave the progress bar and status bar blank and make sure
        # drawing is enabled.
        if scribus.haveDoc():
            scribus.setRedraw(True)
            scribus.closeDoc()
	scribus.openDoc(currentDoc)
        scribus.statusMessage("")
        scribus.progressReset()
def checkForOneFrameSelected() :
    if not scribus.haveDoc():
        scribus.messageBox('Usage Error', 'You need a Document open', icon=0, button1=1)
        sys.exit(2)

    if scribus.selectionCount() == 0:
        scribus.messageBox('Scribus - Usage Error',
            "There is no frame selected.\nPlease select a text frame and try again.",
            scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(2)

    if scribus.selectionCount() > 1:
        scribus.messageBox('Scribus - Usage Error',
            "You have more than one frame selected.\nPlease select one text frame and try again.", scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(2)
Esempio n. 10
0
def main_wrapper(argv):
    """The main_wrapper() function disables redrawing, sets a sensible generic
    status bar message, and optionally sets up the progress bar. It then runs
    the main() function. Once everything finishes it cleans up after the main()
    function, making sure everything is sane before the script terminates."""
    try:
        #scribus.statusMessage("Running script...")
        scribus.progressReset()
        main(argv)
    finally:
        # Exit neatly even if the script terminated with an exception,
        # so we leave the progress bar and status bar blank and make sure
        # drawing is enabled.
        if scribus.haveDoc():
            scribus.setRedraw(True)
        scribus.statusMessage("")
        scribus.progressReset()
Esempio n. 11
0
    def alignImage(self):
        if scribus.haveDoc():
	    restore_units = scribus.getUnit()   # since there is an issue with units other than points,
	    scribus.setUnit(0)			# we switch to points then restore later.
            nbrSelected = scribus.selectionCount()
            objList = []
            for i in range(nbrSelected):
                objList.append(scribus.getSelectedObject(i))
            scribus.deselectAll()
            for i in range(nbrSelected):
                try:
                    obj = objList[i]
                    scribus.selectObject(obj)
                    frameW, frameH = scribus.getSize(obj)
                    saveScaleX, saveScaleY = scribus.getImageScale(obj)
                    scribus.setScaleImageToFrame(1, 0, obj)
                    fullScaleX, fullScaleY = scribus.getImageScale(obj)
                    scribus.setScaleImageToFrame(0, 0, obj)
                    scribus.setImageScale(saveScaleX, saveScaleY, obj)
                    imageW = frameW * (saveScaleX / fullScaleX)
                    imageH = frameH * (saveScaleY / fullScaleY)
                    imageX = 0.0
                    imageY = 0.0
 
                    if self.alignVar.get()[0] == "T":
                        imageY = 0.0
                    elif self.alignVar.get()[0] == "M":
                        imageY = (frameH - imageH) / 2.0
                    elif self.alignVar.get()[0] == "B":
                        imageY = (frameH - imageH)
                    if self.alignVar.get()[1] == "L":
                        imageX = 0.0
                    elif self.alignVar.get()[1] == "C":
                        imageX = (frameW - imageW) / 2.0
                    elif self.alignVar.get()[1] == "R":
                        imageX = (frameW - imageW)
 
                    scribus.setImageOffset(imageX, imageY, obj)
                    scribus.docChanged(1)
                    scribus.setRedraw(True)
                    scribus.deselectAll()
                except:
                    nothing = "nothing"
	    scribus.setUnit(restore_units)
	    
	    self.master.destroy()
Esempio n. 12
0
def extract(chart):
    """
    Extract the graphic chart of the current document.
    """
    if not scribus.haveDoc():
        return  
    
    try:
        scribus.saveDoc()
        if not scribus.getDocName():
            raise IOError('Could not save document.')
    except:
        scribus.messageBox('Script failed',
                           'This script only works if you saved the document.')
        return

    colors = extract_colors()
    fonts = extract_fonts()
    for color in colors:
        chart.add_color(color)
    for font in fonts:
        chart.add_font(font)
    return chart
Esempio n. 13
0
def main(argv):
    """Main method for importing colors."""
    if not scribus.haveDoc() > 0: #do we have a doc?
        scribus.messageBox("csv2color", "No document to import colors \n Please open one, first.")
        sys.exit()
    else:
        filename=scribus.fileDialog("csv2color",  "CSV files(*.csv *.CSV *.txt *.TXT)")
        while os.path.isdir(filename):
            filename=scribus.fileDialog("csv2color",  "CSV files(*.csv *.CSV *.txt *.TXT)") #proper filename?
        else:
            try:
                colorlist=getColorsFromCsv(filename)
                messagestring = "You are going to import %i colors \n This may take a while" % len(colorlist)
                answer = scribus.messageBox("csv2color", messagestring, button1=scribus.BUTTON_OK,  button2=scribus.BUTTON_CANCEL)
                if answer != scribus.BUTTON_OK:
                    sys.exit()
                else:
                    importColors(colorlist)
                    scribus.docChanged(True)
                    scribus.messageBox("csv2color", "Colors imported! \n Thank you for using csv2color and Scribus!")
            except:
                scribus.messageBox("csv2color", "Could not import file!", icon=scribus.ICON_WARNING)
                sys.exit()
Esempio n. 14
0
def main(argv):
    if not scribus.haveDoc():
        sys.exit(1)

    thecommand=""
    infile=os.getcwd()+"/this-is-a-temporary-file.sla"
    reimposed=os.getcwd()+"/reimposed-from-laidout.sla"

    thecommand="laidout --command 'Import(filename=\"" \
                +infile+"\", keepmystery=2)" \
                         +" Reimpose(orientation=landscape, paper=\"Tabloid\", imposition=\"Booklet\") " \
                         +" Export(filter=ScribusExportConfig(filename=\"" \
                +reimposed+"\", layout=\"Papers\"))' "
    #print "command:\n", thecommand

    try:
        print "Creating temporary file ",infile,"..."
        scribus.saveDocAs(infile)
    except:
        print "Could not save as ",infile
        sys.exit(1)


    try:
        os.system(path_to_laidout)
        #os.system(thecommand)

    except:
        print "An error occured trying to run the system command:\n",thecommand
        sys.exit(1)

    scribus.closeDoc() #closes the "original" document, which has been rename to infile upon saveDocAs()
    scribus.openDoc(reimposed) #open the brand spanking new reimposed document

    #if (os.path.isfile(reimposed)): os.remove(reimposed) <-- keep this around
    print "Removing temporary file ",infile,"..."
    os.remove(infile)
Esempio n. 15
0
def getColorsFromDocument():
    """gets colors from opend document. if there is no document, display dialog to chose a file. returns a list[name,c,m,y,k]"""

    def getColors():
        """gets the colors and returns a list[name,c,m,y,k]"""
        colorNames = scribus.getColorNames()
        list = []
        scribus.statusMessage("Reading Colors...")
        stepsTotal = len(colorNames)
        scribus.progressTotal(stepsTotal)
        steps = 0
        for name in colorNames:
            color = scribus.getColor(name)
            listitem = [name, color[0], color[1], color[2], color[3]]
            list.append(listitem)
            # update progress bar
            steps = steps + 1
            scribus.progressSet(steps)
        return list

    # check if we have a document - otherwise display open file dialog
    if scribus.haveDoc() > 0:
        pass
        list = getColors()
        return list
    else:
        pass
        # display file open dialog
        file = scribus.fileDialog("ColorChart by Sebastian Stetter", "Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)")
        # open file
        try:
            scribus.openDoc(file)
        except:
            scribus.messageBox("ColorChart by Sebastian Stetter", "could not open file")
            sys.exit()
        list = getColors()
        return list
Esempio n. 16
0
def main(argv):
    """Main method for importing colors."""
    if not scribus.haveDoc() > 0:  #do we have a doc?
        scribus.messageBox(
            "csv2color",
            "No document to import colors \n Please open one, first.")
        sys.exit()
    else:
        filename = scribus.fileDialog("csv2color",
                                      "CSV files(*.csv *.CSV *.txt *.TXT)")
        while os.path.isdir(filename):
            filename = scribus.fileDialog(
                "csv2color",
                "CSV files(*.csv *.CSV *.txt *.TXT)")  #proper filename?
        else:
            try:
                colorlist = getColorsFromCsv(filename)
                messagestring = "You are going to import %i colors \n This may take a while" % len(
                    colorlist)
                answer = scribus.messageBox("csv2color",
                                            messagestring,
                                            button1=scribus.BUTTON_OK,
                                            button2=scribus.BUTTON_CANCEL)
                if answer != scribus.BUTTON_OK:
                    sys.exit()
                else:
                    importColors(colorlist)
                    scribus.docChanged(True)
                    scribus.messageBox(
                        "csv2color",
                        "Colors imported! \n Thank you for using csv2color and Scribus!"
                    )
            except:
                scribus.messageBox("csv2color",
                                   "Could not import file!",
                                   icon=scribus.ICON_WARNING)
                sys.exit()
def main(argv):
    if not scribus.haveDoc():
        sys.exit(1)

    thecommand=""
    infile=os.getcwd()+"/this-is-a-temporary-file.sla"
    reimposed=os.getcwd()+"/reimposed-from-laidout.sla"

    thecommand="laidout --command 'Import(filename=\"" \
                +infile+"\", keepmystery=2)" \
                         +" Reimpose(orientation=landscape, paper=\"Tabloid\", imposition=\"Booklet\") " \
                         +" Export(filter=ScribusExportConfig(filename=\"" \
                +reimposed+"\", layout=\"Papers\"))' "
    #print "command:\n", thecommand

    try:
        print "Creating temporary file ",infile,"..."
        scribus.saveDocAs(infile)
    except:
        print "Could not save as ",infile
        sys.exit(1)


    try:
        os.system("/home/tom/p/sourceforge/laidout/src/laidout")
        #os.system(thecommand)

    except:
        print "An error occured trying to run the system command:\n",thecommand
        sys.exit(1)

    scribus.closeDoc() #closes the "original" document, which has been rename to infile upon saveDocAs()
    scribus.openDoc(reimposed) #open the brand spanking new reimposed document

    #if (os.path.isfile(reimposed)): os.remove(reimposed) <-- keep this around
    print "Removing temporary file ",infile,"..."
    os.remove(infile)
Esempio n. 18
0
def main():
    # habe ich ein Scribus-Dokument
    if scribus.haveDoc():
        # dann speichere das
        scribus.saveDoc()
        # finde den Namen heraus
        name = scribus.getDocName()
        # nur den Dateinamen, ohne ext
        suchname = os.path.splitext(os.path.split(name)[1])[0]
        # frage nach erstem datensatz
        von = scribus.valueDialog(
            "Daten von", "Daten aus " + suchname +
            ".csv werden verarbeitet.\nBeginne bei Datensatz (keine Eingabe = von Anfang an):",
            "")
        # frage nach letztem datensatz
        bis = scribus.valueDialog(
            "Daten bis", "Daten aus " + suchname +
            ".csv werden verarbeitet.\nEnde bei Datensatz (keine Eingabe = bis zum letzten):",
            "")
        # starte das Bashscript fuer den Seriengenerator
        subprocess.call(['bash', '~/bin/scribus/meinSG', suchname, von, bis])
    else:
        scribus.messageBox("Fehler", "kein Dokument geöffnet",
                           scribus.ICON_CRITICAL)
Esempio n. 19
0
def getColorsFromDocument():
    """gets colors from opend document. if there is no document, display dialog to chose a file. returns a list[name,c,m,y,k]"""
    def getColors():
        """gets the colors and returns a list[name,c,m,y,k]"""
        colorNames=scribus.getColorNames()
        list=[]
        scribus.statusMessage("Reading Colors...")
        stepsTotal=len(colorNames)
        scribus.progressTotal(stepsTotal)
        steps=0
        for name in colorNames:
            color=scribus.getColor(name)
            listitem=[name, color[0], color[1],  color[2],  color[3]]
            list.append(listitem)
            #update progress bar
            steps=steps+1
            scribus.progressSet(steps)
        return list

    #check if we have a document - otherwise display open file dialog
    if scribus.haveDoc() > 0:
        pass
        list=getColors()
        return list
    else:
        pass
        #display file open dialog
        file=scribus.fileDialog("ColorChart by Sebastian Stetter",  'Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)')
        #open file
        try:
            scribus.openDoc(file)
        except:
            scribus.messageBox("ColorChart by Sebastian Stetter", "could not open file")
            sys.exit()
        list=getColors()
        return list
Esempio n. 20
0
            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)
if __name__ == '__main__':
    # This script makes no sense without a document open
    if not scribus.haveDoc():
        scribus.messageBox('Scribus - Script Error', "No document open",
                           scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(1)
    # Disable redraws
    scribus.setRedraw(False)
    # Run the main script, ensuring redraws are re-enabled even if the
    # script aborts with an exception, and don't fail with an exception
    # even if the document is closed while the script runs.
    try:
        main(sys.argv)
    finally:
        try:
            scribus.setRedraw(True)
        except:
            pass
def main(argv):
    if not scribus.haveDoc():
        sys.exit(1)

    os.chdir(os.path.expanduser("~"))

     ####
     ####  If you have a different location of your laidout program change it here:
     ####
    laidoutexecutable="/usr/bin/laidout"
    
    if os.path.exists(laidoutexecutable)==False:
        laidoutexecutable="/usr/local/bin/laidout"
    if os.path.exists(laidoutexecutable)==False:
        print "Could not find Laidout!"
        print "Please change scribus-call-laidout-to-impose-gui.py to have a correct path!"
        #scribus.messageBox("Could not find Laidout!",
        #                   "Please change line 37 in scribus-call-laidout-to-impose-gui.py to have a correct path!")
        #laidoutexecutable=scribus.valueDialog("Laidout path","You do not appear to have Laidout installed! Please enter a valid path for running Laidout","/usr/bin/laidout")
        laidoutexecutable=scribus.fileDialog('Please locate Laidout executable!!', defaultname='/usr/bin/laidout', issave=False)
        print "New laidout executable path: "+laidoutexecutable

     #fail if still not found
    if os.path.exists(laidoutexecutable)==False:
        scribus.messageBox("Could not find Laidout!",
                           "Please either change line for \'laidoutexecutable=\"/usr/bin/laidout\"\' in scribus-call-laidout-to-impose-gui.py"
                           " to have a correct path, or enter a valid path.")
        sys.exit(1)
        

    thecommand=""
    infile=os.getcwd()+"/this-is-a-temporary-file.sla"  #note this saves to a very random area usually!!
    reimposed=os.getcwd()+"/this-is-reimposed-from-laidout.sla" #  seems like directory of the plugin

    #infile =tempfile.NamedTemporaryFile()  <-- maybe this can be used instead?? how to create, get filename, then let laidout open??
    #outfile=tempfile.NamedTemporaryFile()  <-- maybe this can be used instead??

    size=scribus.getPageSize()
    units=scribus.getUnit()
    width=0
    height=0
    print "size "+str(size[0])+","+str(size[1])
    print "units "+str(units)
    if (units==scribus.UNIT_MILLIMETERS):
        width=size[0]/10/2.54
        height=size[1]/10/2.54
    elif (units==scribus.UNIT_PICAS):
        width=size[0]/6
        height=size[1]/6
    elif (units==scribus.UNIT_POINTS):
        width=size[0]/72
        height=size[1]/72
    elif (units==scribus.UNIT_INCHES):
        width=size[0]
        height=size[1]
    else:
        print "unknown units!!!"
        scribus.messageBox("Unknown units!","For some reason, scribus.getUnit() did not return units known to this script!"
                                            "This is probably a bug with the script.")

    #thecommand="/bin/ls"
    thecommand=laidoutexecutable+" --impose-only " \
                         +"'in=\""+infile+"\" " \
                         +" out=\""+reimposed+"\" " \
                         +" prefer=\"booklet\"" \
                         +" width=\""+str(width)+"\"" \
                         +" height=\""+str(height)+"\"" \
                         +"'"
    #print "command:\n", thecommand

    try:
        print "Creating temporary file ",infile,"..."
        scribus.saveDocAs(infile)
    except:
        print "Could not save as ",infile
        sys.exit(1)


    try:
        print "Trying: "+thecommand
        os.system(thecommand)

    except:
        print "An error occured trying to run the system command:\n",thecommand
        sys.exit(1)

    if os.path.exists(reimposed)==False:
        print "Reimposed file was not generated!"
        sys.exit(1)

    #scribus.closeDoc() #closes the "original" document, which has been rename to infile upon saveDocAs()
    scribus.openDoc(reimposed) #open the brand spanking new reimposed document

    #if (os.path.isfile(reimposed)): os.remove(reimposed) <-- might cause problems, but keep around for research
    print "Removing temporary file ",infile,"..."
    os.remove(infile)
    print "All done!"
def main():
    cache = defaultdict(dict)
    try:
        with open(CACHE_FILE, "rb") as cache_file:
            cache = defaultdict(dict, json.load(cache_file))
    except:
        pass

    with open(DATA_FILE, "rb") as data_file:
        songs_data = json.load(data_file)

    with open(MANUEL_PROCESSING_FILE, "rb") as manual_file:
        manual_processing = defaultdict(dict, json.load(manual_file))

    scribus.statusMessage("Running script...")
    scribus.progressReset()
    scribus.progressTotal(len(songs_data))

    init()
    front_matter()
    add_page_number()

    # trying to get the best sorting
    # setting all songs to the max height
    all_songs = dict(
        zip(songs_data.keys(), [EFFECTIVE_PAGE_HEIGHT] * len(songs_data)))
    # update according to cache
    for song_name, data in cache.iteritems():
        all_songs[song_name] = min(data.get("height", EFFECTIVE_PAGE_HEIGHT),
                                   EFFECTIVE_PAGE_HEIGHT)
    # let's see which songs should be set on a double sided page:
    songs_double_page = filter(
        lambda x: manual_processing[x].get("double_page", False),
        manual_processing)
    for double_page in songs_double_page:
        all_songs[
            double_page] = EFFECTIVE_PAGE_HEIGHT  # all double page songs should get a whole page despite their height

    appendix_filter = lambda a_s, boolean: {
        k: v
        for k, v in a_s.iteritems()
        if manual_processing[k].get("appendix", False) == boolean
    }

    main_songs = appendix_filter(all_songs, False)
    add_songs(main_songs, songs_double_page, manual_processing, songs_data,
              cache)

    appendix_songs = appendix_filter(all_songs, True)
    add_songs(appendix_songs, songs_double_page, manual_processing, songs_data,
              cache)

    toc = []
    for filename in filter(lambda s: manual_processing[s].get("show", True),
                           all_songs.keys()):
        toc.append(
            (songs_data[filename]["name"], cache[filename].get("page", "XX")))
    toc.sort(key=lambda (x, y): x)
    create_toc(toc)

    if scribus.haveDoc():
        scribus.setRedraw(True)
        scribus.statusMessage("")
        scribus.progressReset()

    with open(CACHE_FILE, "wb") as cache_file:
        json.dump(cache, cache_file, indent=2)
Esempio n. 23
0
def main():
    try:
        import scribus
    except ImportError:
        # if the script does not run inside of scribus, launch scribus with this script as paremeter

        filename = []

        if (len(sys.argv) == 2):
            print("launching the script for " + sys.argv[1])
            filename.append(sys.argv[1])
        else:
            print("launching the script for each .sla in the directory.")
            for file in os.listdir('.'):
                filenameSplit = os.path.splitext(file)
                if filenameSplit[-1] == '.sla' and filenameSplit[0].find(
                        '_autosave_') == -1:
                    filename.append(file)

        arguments = []
        for argument in sys.argv[1:]:
            if argument[0] == '-':
                # arguments.append('--python-arg')
                arguments.append('-pa')
                arguments.append(argument.strip('-'))

        print(arguments)
        for file in filename:
            call(['scribus', '-g', '-py', sys.argv[0]] + arguments +
                 ['--', file])

        sys.exit(1)

    if scribus.haveDoc():

        page_sizes = {(210, 297): 'A4', (148, 210): 'A5', (105, 148): 'A6'}

        filename = os.path.splitext(scribus.getDocName())[0]
        pdf = scribus.PDFfile()
        page_size = tuple(int(round(s)) for s in scribus.getPageSize())
        print(page_sizes[page_size])
        page_size = page_sizes[page_size]

        pdf.file = filename + '-' + page_size.lower() + '.pdf'
        pdf.save()

        single_sided = 'single' in sys.argv
        print(sys.argv)
        print(single_sided)
        # sys.exit(1)

        pdf = scribus.PDFfile()
        pdf.file = filename + "-reordered.pdf"
        pdf.pages = get_a4_pages(page_size, single_sided, scribus.pageCount())
        print(page_size)
        print(single_sided)
        print(scribus.pageCount())
        print(pdf.pages)
        pdf.save()

        # os.system("pdfnup --nup 2x2 --frame false --no-landscape " + filename + "-reordered.pdf --outfile " + filename.replace("a6", "a4") + ".pdf")
        call([
            'pdfnup', '--nup', '2x2', '--frame', 'false', '--no-landscape',
            filename + '-reordered.pdf', '--outfile', filename + "-a4.pdf"
        ])
        os.remove(pdf.file)
    else:
        print("No file open")
Esempio n. 24
0
def generateContent(string, window):

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

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

    lineWidth = 3.92  #aka 1.383mm, kp warum

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

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

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

        print("add element: " + rowName)

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

        objectlist = []  #list for all boxes

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    print("done")
    return 0
Esempio n. 25
0
                                setattr(pdf, name, 1)
                            elif value.lower() in ['false', 'f', 'no', 'n']:
                                setattr(pdf, name, 0)
                            else:
                                setattr(pdf, name, int(value))
                        except:
                            print 'Error: Could not set "', name, '", "', value, '" is not a valid integer.'
                    elif isinstance(pdf_attr, basestring):
                        # Should this differentiate str and unicode, or will the assignment do the conversion?
                        try:
                            setattr(pdf, name, value)
                        except:
                            print 'Error: Could not set "', name, '", "', value, '" is not a valid string.'
                    else:
                        print 'Error: Could not set "', name, ', type "', type(
                            pdf_attr), '" not supported.'
                    print name, ' is ', str(getattr(pdf, name)), '.'
            except:
                print 'Error: Ignoring unrecognized pdf attribute "', name, '".'
        i = i + 1

    pdf.save()


# start the script

if __name__ == '__main__':
    if haveDoc():
        main(sys.argv)
    else:
        print 'Error: You need to have a document open before you can run this script successfully.'
Esempio n. 26
0
import os
import scribus

if scribus.haveDoc() :
    filename = os.path.splitext(scribus.getDocName())[0]
    pdf = scribus.PDFfile()
    pdf.file = filename+".pdf"
    pdf.version = 15
    pdf.save()
else :
    print("Error : no file open")
Esempio n. 27
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  #
    #########################
    if not scribus.haveDoc() > 0: #do we have a doc?
        scribus.messageBox("importcvs2table", "No opened document.\nPlease open one first.")
        sys.exit()
    userdim = scribus.getUnit() #get unit and change it to mm
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
    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')
        if (not cellwidthL) :
            sys.exit()
        cellwidthleft = float(cellwidthL)
    while cellwidthright <= 0:
        cellwidthR = scribus.valueDialog('Right Cell Width','How wide (mm) do you wish right cells to be?','30.0')
        if (not cellwidthR) :
            sys.exit()
        cellwidthright = float(cellwidthR)
    while cellHeight <= 0:
        cellheight = scribus.valueDialog('Cell Height','How tall (mm) do you wish cells to be?','10.0')
        if (not cellheight) :
            sys.exit()
        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)
Esempio n. 28
0
# This script scales the image so that it fills the frame completely.
# One dimension of the image (width/height) may overflow the frame,
# but at least one dimension will fill the frame exactly.

# License
# Copyright 2007, Jeremy Brown (TrnsltLife)
# This script is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.

import scribus as sc

if sc.haveDoc():
    nbrSelected = sc.selectionCount()

objList = []

for i in range(nbrSelected):
    objList.append(sc.getSelectedObject(i))

for i in range(nbrSelected):
    try:
        obj = objList[i]
        sc.setScaleImageToFrame(True, False, obj)
        scaleX, scaleY = sc.getImageScale(obj)
        sc.setScaleImageToFrame(False, False, obj)
        if scaleX > scaleY:
            scale = scaleX
            sc.setImageScale(scale, scale, obj)
        elif scaleY > scaleX:
Esempio n. 29
0

"""
import scribus

non_breaking_space = u"\u00a0"
non_breaking_thin_space = u"\u202f"
thin_space = u"\u2009"


def est_espace(text):
    return (text == ' ') or (text == non_breaking_space) or (
        text == non_breaking_thin_space) or (text == thin_space)


if scribus.haveDoc() <= 0:
    scribus.messageBox(
        'Error - (fr) Erreur',
        'You need a Document open\n(fr) Ouvrez un document avant de lancer le script',
        scribus.ICON_WARNING, scribus.BUTTON_OK)
    sys.exit(2)

lang = scribus.valueDialog(
    "Language",
    'Choose language or country\n(fr) Choisissez la langue du texte ou le pays :\naf, be, ch, cs, de, en, es, et, fi, fr,\n hu, is, lt, mk, nl, pl, ru, se, sk, sl, sq and uk',
    'fr')
if (lang == 'en'):
    ouvrant_double = u"\u201c"  #lead_double
    fermant_double = u"\u201d"  #follow_double
    lead_single = u"\u2018"
    follow_single = u"\u2019"
def run_script() :
    args = get_args_scribus()
    print('booooklet ' + str(args.booklet))

    if not scribus.haveDoc():
        print("No file open");
        return

    filename = os.path.splitext(scribus.getDocName())[0]

    # scribus.getPageSize()
    # create a PDF with the original size
    pdf = scribus.PDFfile()
    pdf.file = filename + ".pdf"
    pdf.save()

    # create a pdf with the page reordered
    # get it to be steared by facing pages and first page left / right
    # it's booklet if it has facing pages and first page right
    # (the function are probably not in the API yet)
    n = scribus.pageCount()
    pdf = scribus.PDFfile()
    pdf.file = filename + "-reordered.pdf"
    if (n == 1) :
        pdf.pages = [1,1,1,1]
    elif (n == 2) :
        pdf.pages = [1,1,1,1,2,2,2,2]
    elif (n == 4) :
        if args.booklet:
            pdf.pages = [4,1,4,1,2,3,2,3]
        else:
            pdf.pages = [1,3,1,3,4,2,4,2]
    elif (n == 8) :
        if args.booklet:
            pdf.pages = [8,1,6,3,2,7,4,5]
        else:
            pdf.pages = [1,3,5,7,4,2,8,6]
    elif (n == 12) :
        if args.booklet:
            pdf.pages = [12, 1, 2, 11, 10, 3, 4, 9, 8, 5, 6, 7]
        else :
            pass
    elif (n == 16) :
        if args.booklet:
            pdf.pages = [16, 1, 14 , 3, 2, 15, 4, 13, 12, 5, 10, 7, 6, 11, 8, 9] # <- first join top/down , then staple 1/2
        else:
            pass
    elif (n == 24) :
        if args.booklet:
            pass
        else:
            pdf.pages = [1,3,5,7,4,2,8,6,9,11,13,15,12,10,16,14,17,19,21,23,20,18,24,22] # mit starter cards
    else:
        print('{} are not yet supported'.format(n))
    pdf.save()

    call_args = ['pdfnup', '--nup', '2x2', '--frame', 'false', '--no-landscape']
    call_args += ['--', 'outfile', filename.replace("a6", "a4") + ".pdf"]
    call_args += [filename + '-reordered.pdf']
    subprocess.call(call_args)

    os.system("pdfnup --nup 2x2 --frame false --no-landscape " + filename + "-reordered.pdf --outfile " + filename.replace("a6", "a4") + ".pdf")
    os.remove(pdf.file)
Esempio n. 31
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)
Esempio n. 32
0
def funzioneprincipale(csvData):  # def funzioneprincipale(row,headerRow):
    # scribus.messageBox('Scribus - Messaggio di test', str(row), scribus.ICON_WARNING, scribus.BUTTON_OK)
    # scribus.messageBox('Scribus - Messaggio di test', str(headerRow), scribus.ICON_WARNING, scribus.BUTTON_OK)
    # scribus.messageBox('Scribus - Messaggio di test', str(csvData), scribus.ICON_WARNING, scribus.BUTTON_OK)
    if scribus.haveDoc():
        # scribus.newDoc(scribus.PAPER_LETTER,  (20,20,20,20),scribus.PORTRAIT, 1, scribus.UNIT_POINTS,  scribus.NOFACINGPAGES, scribus.FIRSTPAGERIGHT)
        # Dichiaro variabili e costanti
        # le COSTANTI sono quelle in maiuscolo
        POS_X_FOOTER = 43
        WIDTH1 = 330
        WIDTH2 = 90
        HEIGHT = 26
        MAX_HEIGHT = 710
        # max_width = 520
        INTERLINEA = 12.5
        MARGIN_SX = 3.5
        MARGIN_DX = 3.5
        MARGIN_UP = 3.5
        MARGIN_DOWN = 2
        FONT_SIZE = 8
        NUM_COL = 3
        # primo numero da inserire dopo %VAR_F
        # n = 6

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

        # variabili in minuscolo
        pos_y = 521

        # ciclo tutte le righe del csv
        for i in range(ROW_START, len(csvData)):
            # creo la variabile pos_footer, che contiene la nuova posizione della y
            # che verrà assegnata alla cornice di testo chiamata 'footer'
            pos_x = 43
            for j in range(COL_START, len(csvData[i])):
                # i è la riga attuale del csv
                # j è la colonna attuale del csv
                # cur_col è la colonna attuale nella pagina
                cur_col = j % NUM_COL
                cur_width = WIDTH1
                if cur_col == 0:  # and pos_x <= pos_x:
                    # a capo ogni num_col celle
                    # pos_y = pos_y + height
                    pos_x = 43
                    if pos_y >= MAX_HEIGHT:
                        # crea una nuova pagina se la variabile pos_y raggiunge la dimensione
                        # massima prestabilita
                        scribus.newPage(-1)
                        pos_y = HEIGHT + 20
                    else:
                        pos_y = pos_y + HEIGHT
                if cur_col == 1 or cur_col == 2:
                    cur_width = WIDTH2
                nometxtbox = "Cella: csvrow=%d, row=%d, col=%d" % (i, pos_y, pos_x)
                # cell_label = "%VAR_F" + str(n) + "%"
                cell_label = csvData[i][j]
                scribus.createText(pos_x, pos_y, cur_width, HEIGHT, nometxtbox)
                scribus.createRect(pos_x, pos_y, cur_width, HEIGHT)
                scribus.setText(cell_label, nometxtbox)
                # modifico la dimensione del testo
                scribus.setFontSize(FONT_SIZE, nometxtbox)
                # modifico i margini (sx, dx, alto, basso)
                scribus.setTextDistances(MARGIN_SX, MARGIN_DX, MARGIN_UP, MARGIN_DOWN, nometxtbox)
                # modifico l’interlinea
                scribus.setLineSpacing(INTERLINEA, nometxtbox)
                pos_x = pos_x + cur_width
                # n=n+1
                pos_footer = pos_y + HEIGHT + 5
                scribus.moveObjectAbs(POS_X_FOOTER, pos_footer, "footer")
        # Salvo il documento attivo altrimenti
        # lo script ScribusGenerator non inserisce la tabella appena creata
        # scribus.messageBox('Scribus - Messaggio di test', str(cell_label), scribus.ICON_WARNING, scribus.BUTTON_OK)
        scribus.saveDoc()
    else:
        scribus.messageBox(
            "Alert di errore", "Devi avere una pagina Scribus aperta!!!", scribus.ICON_WARNING, scribus.BUTTON_OK
        )
        scribus.newDoc(
            scribus.PAPER_LETTER,
            (20, 20, 20, 20),
            scribus.PORTRAIT,
            1,
            scribus.UNIT_POINTS,
            scribus.NOFACINGPAGES,
            scribus.FIRSTPAGERIGHT,
        )
Esempio n. 33
0
Follow indications and answer 0, 1, 2 or 3 
Another dialog asks wether you want the script to manage 
existing correct doublequotes.


"""
import scribus

non_breaking_space = u"\u00a0"
non_breaking_thin_space = u"\u202f"
thin_space = u"\u2009"

def est_espace(text):
    return (text == ' ') or (text == non_breaking_space) or (text == non_breaking_thin_space)   or (text == thin_space)

if scribus.haveDoc() <= 0:
    scribus.messageBox('Error - (fr) Erreur', 'You need a Document open\n(fr) Ouvrez un document avant de lancer le script', scribus.ICON_WARNING, scribus.BUTTON_OK)
    sys.exit(2)

lang = scribus.valueDialog("Language", 'Choose language or country\n(fr) Choisissez la langue du texte ou le pays :\naf, be, ch, cs, de, en, es, et, fi, fr,\n hu, is, lt, mk, nl, pl, ru, se, sk, sl, sq and uk', 'fr')
if (lang == 'en'):
    ouvrant_double = u"\u201c" #lead_double
    fermant_double = u"\u201d" #follow_double
    lead_single = u"\u2018"
    follow_single = u"\u2019"
elif (lang == 'de'):
    ouvrant_double = u"\u201e"
    fermant_double = u"\u201c"
    lead_single = u"\u2019"
    follow_single = u"\u201a"
elif (lang == 'fr'):
Esempio n. 34
0
        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)
if __name__ == '__main__':
    # This script makes no sense without a document open
    if not scribus.haveDoc():
        scribus.messageBox('Scribus - Script Error', "No document open", scribus.ICON_WARNING, scribus.BUTTON_OK)
        sys.exit(1)
    # Disable redraws
    scribus.setRedraw(False)
    # Run the main script, ensuring redraws are re-enabled even if the
    # script aborts with an exception, and don't fail with an exception
    # even if the document is closed while the script runs.
    try:
        main(sys.argv)
    finally:
        try:
            scribus.setRedraw(True)
        except:
            pass
    for project in projectsRaw :
        # m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
        match = re.match(r'\*\*(.+)\*\* - (.+)', project, re.MULTILINE)
        if match :
            # print(match.group(1))
            # print(match.group(2))
            # TODO: remove the * for italics
            projects.append({'section' : section, 'title': match.group(1), 'description': match.group(2)})
        # print(project)

# print(projects)
# sys.exit(1)

# add the projects to a scribus doc, one project per A6 page. for each section there is a specific master page with a logo.

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

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

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

    # title: x=10 y=10 w=85mm h=20
Esempio n. 36
0
def main(argv):
    if not scribus.haveDoc():
        sys.exit(1)

    os.chdir(os.path.expanduser("~"))

    ####
    ####  If you have a different location of your laidout program change it here:
    ####
    laidoutexecutable = "/usr/bin/laidout"

    if os.path.exists(laidoutexecutable) == False:
        laidoutexecutable = "/usr/local/bin/laidout"

    if os.path.exists(laidoutexecutable) == False:
        print "Could not find Laidout!"
        print "Please change scribus-call-laidout-to-impose-gui.py to have a correct path!"
        #scribus.messageBox("Could not find Laidout!",
        #                   "Please change line 37 in scribus-call-laidout-to-impose-gui.py to have a correct path!")
        #laidoutexecutable=scribus.valueDialog("Laidout path","You do not appear to have Laidout installed! Please enter a valid path for running Laidout","/usr/bin/laidout")
        laidoutexecutable = scribus.fileDialog(
            'Please locate Laidout executable!!',
            defaultname='/usr/bin/laidout',
            issave=False)
        print "New laidout executable path: " + laidoutexecutable

    #fail if still not found
    if os.path.exists(laidoutexecutable) == False:
        scribus.messageBox(
            "Could not find Laidout!",
            "Please either change line for \'laidoutexecutable=\"/usr/bin/laidout\"\' in scribus-call-laidout-to-impose-gui.py"
            " to have a correct path, or enter a valid path.")
        sys.exit(1)

    thecommand = ""
    infile = os.getcwd(
    ) + "/this-is-a-temporary-file.sla"  #note this saves to a very random area usually!!
    reimposed = os.getcwd(
    ) + "/this-is-reimposed-from-laidout.sla"  #  seems like directory of the plugin

    #infile =tempfile.NamedTemporaryFile()  <-- maybe this can be used instead?? how to create, get filename, then let laidout open??
    #outfile=tempfile.NamedTemporaryFile()  <-- maybe this can be used instead??

    size = scribus.getPageSize()
    units = scribus.getUnit()
    width = 0
    height = 0
    print "size " + str(size[0]) + "," + str(size[1])
    print "units " + str(units)
    if (units == scribus.UNIT_MILLIMETERS):
        width = size[0] / 10 / 2.54
        height = size[1] / 10 / 2.54
    elif (units == scribus.UNIT_PICAS):
        width = size[0] / 6
        height = size[1] / 6
    elif (units == scribus.UNIT_POINTS):
        width = size[0] / 72
        height = size[1] / 72
    elif (units == scribus.UNIT_INCHES):
        width = size[0]
        height = size[1]
    else:
        print "unknown units!!!"
        scribus.messageBox(
            "Unknown units!",
            "For some reason, scribus.getUnit() did not return units known to this script!"
            "This is probably a bug with the script.")

    #thecommand="/bin/ls"
    thecommand=laidoutexecutable+" --impose-only " \
                         +"'in=\""+infile+"\" " \
                         +" out=\""+reimposed+"\" " \
                         +" prefer=\"booklet\"" \
                         +" width=\""+str(width)+"\"" \
                         +" height=\""+str(height)+"\"" \
                         +"'"
    #print "command:\n", thecommand

    try:
        print "Creating temporary file ", infile, "..."
        scribus.saveDocAs(infile)
    except:
        print "Could not save as ", infile
        sys.exit(1)

    try:
        print "Trying: " + thecommand
        os.system(thecommand)

    except:
        print "An error occured trying to run the system command:\n", thecommand
        sys.exit(1)

    if os.path.exists(reimposed) == False:
        print "Reimposed file was not generated!"
        sys.exit(1)

    #scribus.closeDoc() #closes the "original" document, which has been rename to infile upon saveDocAs()
    scribus.openDoc(reimposed)  #open the brand spanking new reimposed document

    #if (os.path.isfile(reimposed)): os.remove(reimposed) <-- might cause problems, but keep around for research
    print "Removing temporary file ", infile, "..."
    os.remove(infile)
    print "All done!"
Esempio n. 37
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  #
    #########################
    if not scribus.haveDoc() > 0: #do we have a doc?
        scribus.messageBox("importcvs2table", "No opened document.\nPlease open one first.")
        sys.exit()
    userdim = scribus.getUnit() #get unit and change it to mm
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
    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')
        if (not cellwidthL) :
            sys.exit()
        cellwidthleft = float(cellwidthL)
    while cellwidthright <= 0:
        cellwidthR = scribus.valueDialog('Right Cell Width','How wide (mm) do you wish right cells to be?','30.0')
        if (not cellwidthR) :
            sys.exit()
        cellwidthright = float(cellwidthR)
    while cellHeight <= 0:
        cellheight = scribus.valueDialog('Cell Height','How tall (mm) do you wish cells to be?','10.0')
        if (not cellheight) :
            sys.exit()
        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)
Esempio n. 38
0
"""

import os,  sys
try:
    import scribus
except ImportError:
    print("Dieses Script benötigt ein laufendes Scribus.")
    sys.exit(1)
    
def main():
    # hole Pfad aus der geoeffneten Datei
    dateiPfad = os.path.split(scribus.getDocName())[0]
    # extrahiere den Dateinamen ohne Erweiterung
    dateiName = os.path.splitext(os.path.basename(scribus.getDocName()))[0]
    # pdf-Objekt erzeugen
    pdf = scribus.PDFfile()
    # PDF-Info fuer Konformitaet PDF-X[34] irgendwas reinschreiben
    pdf.info = "Scribus-Source file -" + dateiName + ".sla - created by Robert Johnen"
    # Dateiname fuer PDF-Objekt festlegen
    pdf.file = dateiPfad + "/" + dateiName + ".pdf"
    # PDF-Objekt speichern
    pdf.save()
    
if __name__ == "__main__":
    if scribus.haveDoc():
        main()
    else:
        scribus.messageBox("Fehler", "Es wird eine geöffnete Scribus-Datei benötigt.")
        sys.exit(1)
    
def run_script():
    args = get_args_scribus()
    print('booooklet ' + str(args.booklet))

    if not scribus.haveDoc():
        print("No file open")
        return

    filename = os.path.splitext(scribus.getDocName())[0]

    # scribus.getPageSize()
    # create a PDF with the original size
    pdf = scribus.PDFfile()
    pdf.file = filename + ".pdf"
    pdf.save()

    # create a pdf with the page reordered
    # get it to be steared by facing pages and first page left / right
    # it's booklet if it has facing pages and first page right
    # (the function are probably not in the API yet)
    n = scribus.pageCount()
    pdf = scribus.PDFfile()
    pdf.file = filename + "-reordered.pdf"
    if (n == 1):
        pdf.pages = [1, 1, 1, 1]
    elif (n == 2):
        pdf.pages = [1, 1, 1, 1, 2, 2, 2, 2]
    elif (n == 4):
        if args.booklet:
            pdf.pages = [4, 1, 4, 1, 2, 3, 2, 3]
        else:
            pdf.pages = [1, 3, 1, 3, 4, 2, 4, 2]
    elif (n == 8):
        if args.booklet:
            pdf.pages = [8, 1, 6, 3, 2, 7, 4, 5]
        else:
            pdf.pages = [1, 3, 5, 7, 4, 2, 8, 6]
    elif (n == 12):
        if args.booklet:
            pdf.pages = [12, 1, 2, 11, 10, 3, 4, 9, 8, 5, 6, 7]
        else:
            pass
    elif (n == 16):
        if args.booklet:
            pdf.pages = [
                16, 1, 14, 3, 2, 15, 4, 13, 12, 5, 10, 7, 6, 11, 8, 9
            ]  # <- first join top/down , then staple 1/2
        else:
            pass
    elif (n == 24):
        if args.booklet:
            pass
        else:
            pdf.pages = [
                1, 3, 5, 7, 4, 2, 8, 6, 9, 11, 13, 15, 12, 10, 16, 14, 17, 19,
                21, 23, 20, 18, 24, 22
            ]  # mit starter cards
    else:
        print('{} are not yet supported'.format(n))
    pdf.save()

    call_args = [
        'pdfnup', '--nup', '2x2', '--frame', 'false', '--no-landscape'
    ]
    call_args += ['--', 'outfile', filename.replace("a6", "a4") + ".pdf"]
    call_args += [filename + '-reordered.pdf']
    subprocess.call(call_args)

    os.system("pdfnup --nup 2x2 --frame false --no-landscape " + filename +
              "-reordered.pdf --outfile " + filename.replace("a6", "a4") +
              ".pdf")
    os.remove(pdf.file)