Subversion Repositories Scribus

Rev

Rev 17396 | Rev 19316 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
13369 subik 1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
"""
4
ABOUT THIS SCRIPT:
5
 
6
Import CSV data files as tables into Scribus
7
 
8
1. Create any frame of any size on your page but positioned
9
where you want the table to be located (upper left corner)
10
 
11
2. Make sure it is selected
12
 
13
3. Execute this script:
14
 
15
You will be prompted first for the width of the left column in mm,
16
then the right column in mm, then height of all cells, and finally
17
for a csv filename
18
 
19
4. The data from the csv file will be imported and a table of
20
textboxes will be drawn on the page.
21
 
22
LIMITATIONS:
23
 
24
1. You are limited to two-column CSV data in your file.
25
 
26
2. In Scribus versions 1.3.5svn, when the script ends, you cannot
27
adjust text, colors, and line features for a group, whereas in 1.3.3.x,
28
all of these can be done without ungrouping.
29
 
30
HINTS:
31
 
32
Postgresql:
33
You can easily create a CSV file with a Postgresql database. From Postgresql,
34
toggle unaligned output with the '\a' switch, then activate a comma as
35
a separator with '\f ,' (without apostrophes). Send output to a file
36
with '\o myfile.csv', then query your database.
37
 
38
Sqlite3:
39
You can use "sqlite3 -csv" in the command line or ".mode csv" in sqlite's
40
interactive shell.
41
 
42
############################
43
 
44
LICENSE:
45
 
46
This program is free software; you can redistribute it and/or modify
47
it under the terms of the GNU General Public License as published by
48
the Free Software Foundation; either version 2 of the License, or
49
(at your option) any later version.
50
 
51
This program is distributed in the hope that it will be useful,
52
but WITHOUT ANY WARRANTY; without even the implied warranty of
53
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
54
GNU General Public License for more details.
55
 
56
You should have received a copy of the GNU General Public License
57
along with this program; if not, write to the Free Software
18122 mrdocs 58
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
13369 subik 59
 
60
Author: Sebastian Stetter
61
 
62
Modifications: Gregory Pittman
63
 
64
please report bugs to: scribusscript@sebastianstetter.de
65
"""
66
 
67
from __future__ import division
68
import sys
69
 
70
try:
71
    # Please do not use 'from scribus import *' . If you must use a 'from import',
72
    # Do so _after_ the 'import scribus' and only import the names you need, such
73
    # as commonly used constants.
74
    import scribus
75
except ImportError,err:
76
    print "This Python script is written for the Scribus scripting interface."
77
    print "It can only be run from within Scribus."
78
    sys.exit(1)
79
 
80
#########################
81
# YOUR IMPORTS GO HERE  #
82
#########################
83
import csv
84
 
85
#get information about the area where the bale should be drawed
86
def getPosition():
87
    if scribus.selectionCount() == 1:
88
        areaname = scribus.getSelectedObject()
89
        position= scribus.getPosition(areaname)
90
        vpos = position[1]
91
        hpos = position[0]
92
        scribus.deleteObject(areaname)
93
        return vpos, hpos
94
 
95
    else:
96
        scribus.messageBox("csv2table", "please select ONE Object to mark the drawing area for the table")
97
        sys.exit()
98
 
99
#get the cvs data
100
def getCSVdata():
101
    """opens a csv file, reads it in and returns a 2 dimensional list with the data"""
102
    csvfile = scribus.fileDialog("csv2table :: open file", "*.csv")
103
    if csvfile != "":
104
        try:
105
            reader = csv.reader(file(csvfile))
106
            datalist=[]
107
            for row in reader:
108
                rowlist=[]
109
                for col in row:
110
                    rowlist.append(col)
111
                datalist.append(rowlist)
112
            return datalist
113
        except Exception,  e:
114
            scribus.messageBox("csv2table", "Could not open file %s"%e)
115
    else:
116
        sys.exit
117
 
118
def getDataInformation(list):
119
    """takes a 2 dimensional list object and returns the numbers of rows and cols"""
120
    datainfo = dict()
121
    datainfo["rowcount"]=len(list)
122
    datainfo["colcount"]= len(list[0])
123
    return datainfo
124
 
125
def cellsize(areainfo, datainfo):
126
    """"takes the area and data info and calculates the prper cell size"""
127
    csize=dict()
128
    csize["v"]= areainfo["vsize"] / datainfo["rowcount"]
129
    csize["h"]= areainfo["hsize"] / datainfo["colcount"]
130
    return csize
131
 
132
def main(argv):
133
    """This is a documentation string. Write a description of what your code
134
    does here. You should generally put documentation strings ("docstrings")
135
    on all your Python functions."""
136
    #########################
137
    #  YOUR CODE GOES HERE  #
138
    #########################
139
    userdim=scribus.getUnit() #get unit and change it to mm
140
    scribus.setUnit(scribus.UNIT_MILLIMETERS)
141
    cellwidthleft = 0
142
    cellwidthright = 0
143
    cellHeight = 0
144
    pos = getPosition()
145
    while cellwidthleft <= 0:
146
      cellwidthL = scribus.valueDialog('Left Cell Width','How wide (mm) do you wish left cells to be?','30.0')
147
      cellwidthleft = float(cellwidthL)
148
    while cellwidthright <= 0:
149
      cellwidthR = scribus.valueDialog('Right Cell Width','How wide (mm) do you wish right cells to be?','30.0')
150
      cellwidthright = float(cellwidthR)
151
    while cellHeight <= 0:
152
      cellheight = scribus.valueDialog('Cell Height','How tall (mm) do you wish cells to be?','10.0')
153
      cellHeight = float(cellheight)
154
    data = getCSVdata()
155
    di= getDataInformation(data)
156
    hposition=pos[1]
157
    vposition=pos[0]
158
 
159
    objectlist=[] # here we keep a record of all the created textboxes so we can group them later
160
    i=0
161
    scribus.progressTotal(len(data))
162
    scribus.setRedraw(False)
163
    for row in data:
164
        c=0
165
        for cell in row:
166
            cell = cell.strip()
167
            cellsize=cellwidthleft
168
            if c == 1: cellsize=cellwidthright
169
            textbox=scribus.createText(hposition, vposition, cellsize, cellHeight) #create a textbox
170
            objectlist.append(textbox)
171
            scribus.insertText(cell,0, textbox)#insert the text into the textbox
172
            hposition=hposition+cellwidthleft #move the position for the next cell
173
            c=1
174
        vposition=vposition+cellHeight #set vertical position for next row
175
        hposition=pos[1] #reset vertical position for next row
176
        i=i+1
177
        scribus.progressSet(i)
178
 
179
    scribus.groupObjects(objectlist)
180
    scribus.progressReset()
181
    scribus.setUnit(userdim) # reset unit to previous value
182
    scribus.docChanged(True)
183
    scribus.statusMessage("Done")
184
    scribus.setRedraw(True)
185
 
186
def main_wrapper(argv):
187
    """The main_wrapper() function disables redrawing, sets a sensible generic
188
    status bar message, and optionally sets up the progress bar. It then runs
189
    the main() function. Once everything finishes it cleans up after the main()
190
    function, making sure everything is sane before the script terminates."""
191
    try:
192
        scribus.statusMessage("Importing .csv table...")
193
        scribus.progressReset()
194
        main(argv)
195
    finally:
196
        # Exit neatly even if the script terminated with an exception,
197
        # so we leave the progress bar and status bar blank and make sure
198
        # drawing is enabled.
17396 fschmid 199
        if scribus.haveDoc() > 0:
13369 subik 200
            scribus.setRedraw(True)
201
        scribus.statusMessage("")
202
        scribus.progressReset()
203
 
204
# This code detects if the script is being run as a script, or imported as a module.
205
# It only runs main() if being run as a script. This permits you to import your script
206
# and control it manually for debugging.
207
if __name__ == '__main__':
208
    main_wrapper(sys.argv)