Subversion Repositories Scribus

Rev

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

Rev Author Line No. Line
12781 subik 1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3
"""
4
ABOUT THIS SCRIPT:
5
 
6
Import Colors from a CSV file to Scribus
7
 
8
csv2color.py allows a user to import colors from a given csv file into a scribus document.
9
The file must be a text file with comma seperated values in the following format:
10
 
11
"colorname", c,m,y,k
12
 
13
There must be a document opend in scribus where the colors can be defined in.
14
If the csv contanins one or more color names that already exist in the document, the colors will be imported with a `*` as prefix.
15
 
16
This script is especially helpfull if you want to use CMYK color representations of color systems like HKS, Pantone or RAL in Scribus. Lots of such CMYK translation tables can be found on the Web.
17
One can easily copy such a table into a text file, save it in the obove described format and import it into a scribus document.
18
 
19
Use color2csv to export the colors from a scribus document into a csv file.
20
 
21
############################
22
 
23
LICENSE:
24
 
25
This program is free software; you can redistribute it and/or modify
26
it under the terms of the GNU General Public License as published by
27
the Free Software Foundation; either version 2 of the License, or
28
(at your option) any later version.
29
 
30
This program is distributed in the hope that it will be useful,
31
but WITHOUT ANY WARRANTY; without even the implied warranty of
32
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33
GNU General Public License for more details.
34
 
35
You should have received a copy of the GNU General Public License
36
along with this program; if not, write to the Free Software
18122 mrdocs 37
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
12781 subik 38
 
39
Author: Sebastian Stetter
40
 
41
please report bugs to: scribusscript@sebastianstetter.de
42
"""
43
from __future__ import division
44
import sys
45
 
46
__version__=1.1
47
 
48
 
49
try:
50
    # Please do not use 'from scribus import *' . If you must use a 'from import',
51
    # Do so _after_ the 'import scribus' and only import the names you need, such
52
    # as commonly used constants.
53
    import scribus
54
except ImportError,err:
55
    print "This Python script is written for the Scribus scripting interface."
56
    print "It can only be run from within Scribus."
57
    sys.exit(1)
58
 
59
#########################
60
# YOUR IMPORTS GO HERE  #
61
#########################
62
import csv
63
import os
64
 
65
PREFIX="*"
66
 
67
def checkValue(c, m, y, k):
68
    """returns true if the cmyk values are between 0 and 255"""
69
    MINVAL=0
70
    MAXVAL=255
71
    valueOk=True
72
    for val in c, m, y, k:
73
        if val >=MINVAL and val <=255:
74
            pass
75
        else:
76
            valueOk=False
77
 
78
    return valueOk
79
 
80
def getColorsFromCsv(filename):
81
    """get colors from csv file and return a list with name and cmyk 255 values"""
82
    csvreader=csv.reader(file(filename))
83
 
84
    csvcolors=[]
85
    i=0
86
    for row in csvreader:
87
        name=row[0]
88
        name=name.strip()
89
        c=int(row[1] )* 2.55
90
        c=int(c)
91
        m=int(row[2] )* 2.55
92
        m=int(m)
93
        y=int(row[3] )* 2.55
94
        y=int(y)
95
        k=int(row[4] )* 2.55
96
        k=int(k)        
97
        if checkValue(c, m, y, k) ==False:
98
            scribus.messageBox("csv2color", "At least one CMYK value in your csv file is not correct \n(must be between 0 and 100)\nAborting script - nothing imported.",  icon=scribus.ICON_WARNING)
99
            sys.exit()
100
        else:
101
            pass
102
        color=(name, c, m, y, k)
103
        csvcolors.append(color)
104
        i=i+1
105
    return csvcolors
106
 
107
def getColorDict():
108
    """get the colors that already exist from the opened Document and return a dictionary"""
109
    scribus.statusMessage("Reading existing colors...")
110
    colornames = scribus.getColorNames()
111
    scribus.progressTotal(len(colornames))
112
    i=0
113
    colordict={}
114
    for name in colornames:
115
        colordict[name]=None
116
        i=i+1
117
        scribus.progressSet(i)
118
    return colordict #we can ask this dict if the color already exists
119
 
120
def importColors(colorlist):
121
        """check if colors exists an import"""
122
        colordict=getColorDict()
123
        scribus.statusMessage("Defining new colors...")
124
        scribus.progressTotal(len(colorlist))
125
        i=0
126
        for color in colorlist:
127
            name=color[0]
128
            c=color[1]
129
            m=color[2]
130
            y=color[3]
131
            k=color[4]
132
            while colordict.has_key(name):# check if color already exists - then add PREFIX to name
133
                name = PREFIX+name
134
 
135
            scribus.defineColor(name, c, m, y, k)
136
            i=i+1
137
            scribus.progressSet(i)
138
 
139
def main(argv):
140
    """Main method for importing colors."""
17396 fschmid 141
    if not scribus.haveDoc() > 0: #do we have a doc?
12781 subik 142
        scribus.messageBox("csv2color", "No document to import colors \n Please open one, first.")
143
        sys.exit()
144
    else:
145
        filename=scribus.fileDialog("csv2color",  "CSV files(*.csv *.CSV *.txt *.TXT)")
146
        while os.path.isdir(filename):
147
            filename=scribus.fileDialog("csv2color",  "CSV files(*.csv *.CSV *.txt *.TXT)") #proper filename?
148
        else:
149
            try:
150
                colorlist=getColorsFromCsv(filename)
151
                messagestring = "You are going to import %i colors \n This may take a while" % len(colorlist)
152
                answer = scribus.messageBox("csv2color", messagestring, button1=scribus.BUTTON_OK,  button2=scribus.BUTTON_CANCEL)
153
                if answer != scribus.BUTTON_OK:
154
                    sys.exit()
155
                else:
156
                    importColors(colorlist)
157
                    scribus.docChanged(True)
158
                    scribus.messageBox("csv2color", "Colors imported! \n Thank you for using csv2color and Scribus!")
159
            except:
160
                scribus.messageBox("csv2color", "Could not import file!", icon=scribus.ICON_WARNING)
161
                sys.exit()
162
 
163
 
164
 
165
def main_wrapper(argv):
166
    """The main_wrapper() function disables redrawing, sets a sensible generic
167
    status bar message, and optionally sets up the progress bar. It then runs
168
    the main() function. Once everything finishes it cleans up after the main()
169
    function, making sure everything is sane before the script terminates."""
170
    try:
171
        #scribus.statusMessage("Running script...")
172
        scribus.progressReset()
173
        main(argv)
174
    finally:
175
        # Exit neatly even if the script terminated with an exception,
176
        # so we leave the progress bar and status bar blank and make sure
177
        # drawing is enabled.
178
        if scribus.haveDoc():
179
            scribus.setRedraw(True)
180
        scribus.statusMessage("")
181
        scribus.progressReset()
182
 
183
# This code detects if the script is being run as a script, or imported as a module.
184
# It only runs main() if being run as a script. This permits you to import your script
185
# and control it manually for debugging.
186
if __name__ == '__main__':
187
    main_wrapper(sys.argv)