Poor man's mail merge

From Scribus Wiki
Jump to navigation Jump to search
This article is part of the Scripts series.

The recommended way to get a fully working mail merge in Scribus is to use the Scribus Generator script extension, initially created by Ekkehard Will and further extended by various people.

Also look at "mail merge" script in ale's scribus script repository : https://github.com/aoloe/scribus-script-repository/tree/master/mail-merge

Legacy

There was a mail merge script for Scribus (at http://www.assembla.com/wiki/show/scribusmailmerge) which brought a good solution for mail merging with Scribus but it didn't work with any modern version of Scribus and the page has moved.

Other options are discussed below... but most of these features have been integrated in the Scribus Generator.

                    • BRINGING THE OLD VERSION BACK - STOP MOVING THE OLD STUFF AWAY************************** mrb@


Ekkehard Wil has also created a quite advanced mail merger.

The script on this page is a workaround which has (for now) to be adapted for each job.

It has been created for the following workflow:

  • Create your document without the frames to be filled with dynamic content; copy the content of the page.
  • Create a new document where you run the merging
  • Create a master page (in this example it's called "badge") and paste in there the page you have copied before1
  • Create a csv file with the content you want to insert in you document
    • every line will be a page
    • every field (separated by a comma) will go into its frame (or you can do more fancy things with each column)
  • adapt the values of the variables name_x to project_h (change the names and values to fit your document)2
  • adapt the part of the script after for row in data: to your needs

1 A better way is to transform the page in a master page and then import the master page into a the new document: at the time of writing this function doesn't work reliably on all version of scribus.
2 you can find the values by creating the frames in the document, reading the values and deleting them (or just removing them from the master page)

This is -- as far as I know -- the easiest way of (cleanly) doing it: there may be better ways to handle the job and you are invited to post your ideas and code in this page!

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ABOUT THIS SCRIPT:
Import CSV data files as tables into Scribus
"""


import sys

try:
    # Please do not use 'from scribus import *' . If you must use a 'from import',
    # Do so _after_ the 'import scribus' and only import the names you need, such
    # as commonly used constants.
    import scribus
except ImportError,err:
    print "This Python script is written for the Scribus scripting interface."
    print "It can only be run from within Scribus."
    sys.exit(1)

#########################
# YOUR IMPORTS GO HERE  #
#########################
import csv

def getCSVdata():
    """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
    csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
    if csvfile != "":
        try:
            reader = csv.reader(file(csvfile))
            datalist=[]
            for row in reader:
                rowlist=[]
                for col in row:
                    rowlist.append(col)
                datalist.append(rowlist)
            return datalist
        except Exception,  e:
            scribus.messageBox("csv2table", "Could not open file %s"%e)
    else:
        sys.exit


def create(argv):
    """
        - create a page using the "badge" master page.
        - add the text field with the name
        - add the text with the role in the project
    """
    #########################
    #  YOUR CODE GOES HERE  #
    #########################
    userdim=scribus.getUnit() #get unit and change it to mm
    scribus.setUnit(scribus.UNIT_POINTS)
    
    data = getCSVdata()
    
    scribus.progressTotal(len(data))
    scribus.setRedraw(False)

    name_x = 20;
    name_y = 140;
    name_w = 250;
    name_h = 30;
    project_x = 20;
    project_y = 165;
    project_w = 250;
    project_h = 45;

    i = 0;

    for row in data:
        #if i > 0 :
        #sys.exit(1)
        # scribus.messageBox("csv2table", row)
        #scribus.messageBox("csv2table", row[0])

        # create a page
        scribus.newPage(-1, 'badge');
        # create and fill the text boxes
        textbox=scribus.createText(name_x, name_y, name_w, name_h)
        scribus.insertText(row[0],0, textbox)
        scribus.setTextColor('orange', textbox);
        scribus.setFont('Nimbus Sans L Bold', textbox);
        scribus.setFontSize(24, textbox);
        scribus.setLineSpacing(28, textbox);
        textbox=scribus.createText(project_x, project_y, project_w, project_h)
        scribus.insertText(row[1]+"\n"+row[2], 0, textbox)
        scribus.setFontSize(14, textbox);
        scribus.setFont('Nimbus Sans L Bold', textbox);
        scribus.setLineSpacing(18, textbox);
        i = i + 1;
        scribus.progressSet(i)
    
    scribus.progressReset()
    scribus.setUnit(userdim) # reset unit to previous value
    scribus.docChanged(True)
    scribus.statusMessage("Done")
    scribus.setRedraw(True)


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."""
    try:
        scribus.statusMessage("Importing .csv table...")
        scribus.progressReset()
        create(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()

# This code detects if the script is being run as a script, or imported as a module.
# It only runs main() if being run as a script. This permits you to import your script
# and control it manually for debugging.
if __name__ == '__main__':
    main(sys.argv)