Poor man's mail merge: Difference between revisions

From Scribus Wiki
Jump to navigation Jump to search
m ((almost) Removed outgoing dead link and tweaked grammar accordingly)
(cleaned)
Line 1: Line 1:
{{Scripting Index}}
{{Scripting Index}}
There was a mail merge script for Scribus (at <del>http://www.assembla.com/wiki/show/scribusmailmerge</del>) 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.


Ekkehard Wil has also created a quite advanced [[Scribus Generator|mail merger]].
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.


==Legacy==


 
There was a mail merge script for Scribus (at <del>http://www.assembla.com/wiki/show/scribusmailmerge</del>) 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.
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 before<sup>1</sup>
* 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 <tt>name_x</tt> to <tt>project_h</tt> (change the names and values to fit your document)<sup>2</sup>
* adapt the part of the script after <tt>for row in data:</tt> to your needs
 
<sup>1</sup> 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.<br />
<sup>2</sup> 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!
 
<syntaxhighlight lang='python'>
#!/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)
</syntaxhighlight>

Revision as of 14:37, 14 September 2015

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.

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.