The Scripter

From Scribus Documentation Project

Jump to: navigation, search

Contents

The Scripter

Using Scripts

General

The Scripter is a plug-in which allows for the use of the Python programming language to carry out a series of operations within Scribus. In general, one should consider using a script whenever there are a series of precise, repetitive tasks you want to do in Scribus, particularly when you will be doing this in a number of documents you create. Another advantage of the Scribus scripting engine – the Scripter – is that you can easily add a feature you are missing by using Python. Python is a powerful, yet easily learned programming language which is readily available for all current operating systems. [1]

There are a number of scripts included with your Scribus distribution which you may find useful for a variety of tasks, but also as examples which you can modify for customized purposes, as well as helping to understand Python syntax and associated Scribus commands. In addition, there are many more to be found on the Scribus Wiki. [2]

The requirements for being able to use Scripter are as follows:

  • Python
  • Python development libraries if you are going to compile Scribus with Scripter enabled.
  • Tk and Tkinter – not always needed, but many of the scripts shipped with Scribus require Tkinter for the creation of various dialogs.
  • Some 3rd party scripts may also require PyQt.

There are some fundamental differences between scripts and other functions of Scribus. For instance, a script will perform the task it is written for and then finish. Scripts that use dialogs will close them once they’re finished. You have to re-run the script to use it again. Also, scripts can’t be translated like other elements of the Scribus user interface. If you want a version of a script in your language, you have to edit the source file yourself. It’s also impossible to add tooltips to scripts. Finally, Scribus uses Tk/Tkinter for building a user interface by default. As you will see in the examples below, this user interface toolkit has a different “look and feel” than the rest of the Scribus interface.

Using Scripts

There are three different ways to run a script within Scribus.

  • The first is to go on the menu go to Scripts > Scribus Scripts, which will show you all of the scripts mentioned above.
  • Under Scripts > Execute Script … you will be presented with a file dialog to find your desired script. Some additional scripts can be found in /usr/share/scribus/samples or wherever Scribus is installed, and if you make your own, you can of course save them wherever you like.
  • Once you have used a script, it will be saved in a list under Scripts > Recent Scripts.

Simply select a script in the file dialog, click “OK,” and it will be executed. Be aware that each script will have certain requirements, which, if not met, will generate a failure, hopefully with a helpful error message. For example, some scripts require a document to be open or a frame selected. In case of a failure, the error message will be copied to the clipboard automatically, so that you can copy it into an email program and send it to the author of the script.

[1] http://www.python.org

[2] http://wiki.scribus.net/index.php/Category:Scripts_%26_Plugins

The Python Console

General

The Python Console is a helper tool for small Python code bits. Use standalone scripts when you need to perform complex or repeating tasks. This console might show some unexpected behavior in some cases. You can use the third party Extension Script (IDE) [1] from Henning Schröder in case you’re facing some limitations or just when you like to have more functionality.

Since this is not a manual on Python programming, we’ll cover just a few elements of console functions. As you see below, in the top of the Console window you enter one or more commands. If a command would result in output such as the print command, you will see the results in the bottom part of the window. Scribus commands resulting in changes on the main window produce them there, such as this text frame placed on the document to the left of the console window.

This simple console is really mainly useful for small parts of a Python program for troubleshooting. It may have trouble interpreting blank lines or indentations, so error messages can sometimes be hard to understand.

The Python Console Menus

  • Open … opens a Python script in the console.
  • Save saves the content of the console editor into a text file with the file extension *.py.
  • Save As … saves the content of the console editor into a text file with the file extension *.py.
  • Exit closes the console window.
  • Run runs the whole editor text or a selection as one Python statement.
  • Run As Console runs the statement and waits for next one then. It’s the same as in the Python interactive console mode.
  • Save Output … saves the current console output into a text file.

Console Configuration

Open File > Preferences > Scripter from the Scribus main window.

You can change syntax highlighting colors for the console editor in this dialog. There is no need to change it in standard environments, but it’s very useful when you are using a dark desktop theme. You can set the console colors as you wish.

[1] http://henning.cco-ev.de/scribus/extensions/ide.py

Script Info

A programmer can use this feature to provide information about a script. If a user clicks on Script > About Script a file dialog appears, in which a Python script can be selected. After selecting a script and clicking “Save,” the text will be displayed in the Help Browser.

Python scripts should contain the so-called Docstring. It’s a general documentation about a program (script, module, etc.). Let’s have a sample script foo.py:

""" This is a hello world example. """
if __name__ == ’__main__’:
    print "Hello World!"

The Help Browser will now display the following text:

Documentation for: foo.py

This is a hello world example.

It is recommended that script authors add the following information to the docstring:

  1. Author(s)
  2. Copyright and licensing informations
  3. A short description of what the script does
  4. Basic instructions on use

If the Python script doesn’t contain any docstring, it will display the text “Script measurements.py doesn’t contain any docstring!” and the content of the script is shown instead.

Extension Scripts

Extension Scripts, like the one mentioned above, can enhance the functionality of Scribus, unlike regular Scripts that merely use the feature set of Scribus. For instance, it is possible to use them to create new palettes and dockable dialogs that can be used as if they were a part of Scribus.

Extension Scripts are mostly like normal Python scripts for Scribus. The most fundamental differences between normal scripts and extensions scripts are that:

  • Extension Scripts can create Python objects that continue to exist after the script exits.
  • Extension Scripts can create code that runs without blocking the execution of scribus, so it’s possible to create floating palettes that can be present while the user works normally with Scribus.
  • PyQt works correctly in extension scripts, unlike normal scripts.
  • Extension scripts can make changes to the Python environment that will affect scripts run after it. Modules imported by one script can be seen by another, settings changed by one may stay changed, etc.

Since those scripts aren’t controlled by the Scribus team, you need to permit their execution before you are able to use them for security reasons. Go to File > Preferences > Scripter and check “Enable Extension Script.” Now you can load an Extension Script via Script > Execute Script.

If you want an Extension Script to be automatically started with Scribus, you can select one by clicking on the “Change …” button in this tab. You will be presented a file dialog, where you can choose the Extension Script. Note that you can only set a default Extension Script in the Preferences, not per document.


Scribus Scripts

Bleed and Print Marks

Bleed, printing marks, and color bars are currently only found natively in development versions of Scribus. In the meantime, this script provides a workaround for these features in the 1.3.3.x versions. This script gives you choices to independently allow for bleed, crop marks, registration marks, and also adds some information about the PDF outside the margins in the bleed area. It will take a multi-page Scribus document and create individual PDF files for each page. First let’s explain a bit about the terminology.

Bleed

Bleed as a printing term refers to situations where you want some element of your final document to go completely to the edge of the paper. For example, this might be a photograph or a shape filled with color. The easiest way to ensure this is to print on a sheet of paper larger than your final desired size, after laying out your work, so that your image or shape extends beyond that future edge, then trim down or crop the paper after printing. Standard bleed amounts (the amount your object should extend beyond the final edge of the page) are 1/8 inch (9 pts) in the US and UK, 3 to 5 mm in Continental Europe, but you should always check with your printer.

Your printing company may indicate it is unnecessary, but in many cases adding crop marks to the page to indicate precisely where you wish the paper to be cut can be useful.

Registration Marks

There are various meanings of this term in business and industrial processes, but in our printing context, registration marks are printed in the parts of the paper that will be cropped, and allow for alignment of the paper when a multicolor process is used – the paper will sequentially pass through the equipment for each color printed, and obviously one desires good alignment of these on the page. They are also used to align the print on opposite sides of a sheet of paper. (see Preparing Files for Commercial Printing for more information) It is important that these marks be printed using a color which will appear in each color separation. Here is one registration mark, along with an optional message the script will add.

Color Bars

Color Bars are used by your printer to help with quality control of the colors being used in the document, representing various colors, sometimes with varying dot densities to ensure a uniform and desired end result of a multicolor print process. Again, for obvious reasons, these are in some part of the page that will be cropped.

As we see to the right in this partial example from our script, these have associated labels to indicate C, M, Y, and K values.

BleedAndPrintMarks.py

In preparation for using this script, make your document in Scribus with the final dimensions you wish it to have, in other words the size after cropping. The script works by creating new, temporary document pages, which are slightly larger than your original, while maintaining the size and relative positions of your original layout. Thus, the script does not modify your original document. Crop marks will be placed to mark your original dimensions. As we will see below, precisely where to place objects to get the result you desire will depend on various dialog entries.

When you run the script, with Script > Scribus Scripts > BleedandPrintMarks from the menu, you are presented with a series of dialogs. If you do not have a document open, the script will end with a message to that effect.

Properly running the script with a document first shows a dialog in which you can choose either the default English or German for dialog messages. Type “German” or “DE,” if you wish, but actually anything other than the default chooses German. If you want to add another language, the script is structured so that you can easily add other language phrases – these are not built-in. Ask on the Scribus mailing list if you need help. The “posix” in the title bar is a message indicating this was run on Linux or UNIX – Windows would show “nt.”

Next, you can choose a color for your registration and other marks. The default is a registration color – fully saturated in CMYK. You may choose your own if you are not using a four-color process, but importantly, make sure you have created the color and the name is correct.

Now choose the directory where you wish your final PDFs to be saved:

After this, you may edit the file prefix for your PDF files. The default names for your files will be “scribus_print_00001.pdf,” “scribus_print_00002.pdf,” and so on.

The next dialog will choose the units for your final document and the calculations for various parameters. The default is millimeters – you do not have to choose the units of your original document.

The following dialog will show a different default value depending on the units chosen. The default distance is equal to 20 points, but here we see this amounts to 7mm. This is the amount to be cropped from the edges of the final paper size.

The page layout type will change the behavior of our script. For this script we may choose either a double page layout or single pages – see Opening, Creating and Saving Files, under “New Document Dialog” for more about this. In the script dialog below we can choose “dr” for double-sided, first page a right page, “dl” for double-sided, first page left, and “s” for all single pages. Let’s look at an artificial example to show what happens when we run our script.

Above are pages 2 and 3 of an A4 document in Scribus where the images have been placed at the outer edges and inner margins of the original paper size. Note that it is up to the person using Scribus to place objects for the appropriate amount of bleed, the script does not do this for you. Here, the far left and far right images each extend 9 pts beyond the edge of the original page.

Here is the output as seen in Adobe Reader – these were individual PDFs from which a montage was created. These final pages are now 14 mm larger than A4 in both height and width, and are marked to be trimmed to A4 size. We anticipate that the left and right images will have about 9 pts trimmed from their outer edges.

Now you have choices for adding these various components individually. Again, ask your printer if these are necessary, useful, or perhaps a hindrance.

Finally, you have the opportunity to add a little message at the bottom of each page, and of course you want to proudly proclaim your use of Scribus, even though you can insert whatever message you prefer:

When you click this last OK, the script transforms pages one by one, making single-page PDFs.

Limitations

  • In Windows, a problem can occur if you run the script while you simultaneously have Adobe Reader running, and have opened a file of the same name that the script wishes to create – the script will fail in this case. This is presumably related to the way Adobe Reader functions in Windows, and does not occur with Linux.
  • It is important to use the “dr,” “dl,” and “s” options correctly for the layout, since results can be quite unexpected otherwise.
  • The Scribus document that you begin with will be closed in Scribus, hopefully replaced by one called “tmp.sla,” although this one will also not automatically be saved. Therefore, be sure that you have saved your original document before running the script, since there will be no warning or option to save once the script starts.
  • There are quite a number of dialogs, and no way to go back or halt the script in the middle. Once you begin, if you should change your mind about an entry you will need to finish the script, then start from the beginning again.

Calendar Wizard

The Calendar Wizard allows you to create good looking calendars in a fast, flexible and comfortable way.

In the list on the left side, you can select the language of your calendar. Select a language and click “Change Language.” The “Short” versions in Czech and English refer to the way the days of the week will be written, ie. “Mon” or “Monday” etc. The months in the calendar can be selected in the list on the right side. You can select one or more months by clicking on a name in the list. Clicking again will deselect a month. If you choose the option “Whole year,” the script automatically selects all months.

In the field “Year” you can enter the year for which the calendar will be created. The default is the current year. With “Week begins with” you can decide whether a week begins with Monday (European style) or Sunday (American style).

With “Calendar type” you can create two different kinds of layouts. See the screenshots below for a comparison.

If “Draw Image Frame” is activated, the script will create an empty image frame in the upper or left part of each page, depending on the calendar type.

Clicking “OK” brings up the standard dialog for creating a new Scribus document. Select page size, margin guides etc. as usual. Click “OK,” and paragraph style dialog appears. Here you can select the font, its size etc. for your calendar text. Click “OK” again, and the script will create a new Scribus document with the settings you chose.

The resulting Scribus document consists of three layers, “Background,” “Calendar Image” (if you decided to use an image frame) and “Calendar.” This is important to know, as you have to switch between layers to edit either the image frame or the text frames.

Direct Image Import

If you want to import an image into Scribus, the normal way is to create an image frame and then load the image into this frame. For people who are unfamiliar with DTP programs, this is uncommon.

With this script, you can import an image into Scribus in a way that’s more similar to a word processor: just execute the script, and it will open a file dialog, in which you can select an image. The image will be inserted immediately, as the script is drawing a frame and importing the image automatically.

The downside of this approach, compared to the regular procedure, is that you have no control over the size of the frame when it’s created, even though you can change it later.

Extract Text

To extract all text from a Scribus file, you can use Script > Scribus Scripts > ExtractText. This script will allow you to extract all text from all frames from within Scribus. In addition, it will list all pathnames for images in image frames.

When you start the script, it will ask for a name for the text file to create. As soon as you enter this, it scans your document and creates the file.

Here is an example of the output from this script:


Page 1
header: Scribus
An Introductory Manual
body: A very brief intro
Scribus is an open source program for the production of professional layout targeted toward press-ready output, as well as other purposes PDFs may be used for, such as presentations and online document distribution like this manual. Begun as a personal project of Franz Schmid, it has attracted an increasing number of developers and users. The main sources of information will be found in the online manual included with the Scribus distribution, at docs.scribus.net, and at wiki.scribus.net. This manual is meant to collect together selected information from these sources in a format many have requested. Because Scribus is rapidly changing and improving, all of the sources of information, and especially this one may have errors or incomplete instructions, and in fact this is to be expected for development/unstable versions of Scribus. In general this manual will focus on the current stable version, now in the 1.3.3.x series, but additional notes may be included for 1.3.4+ when procedures and requesters substantially change.
Orientation
Some detailed explanations of DTP (Desktop Publishing) and its differences from wordprocessing can be found on the Scribus sites. Here we will merely point out that DTP is the design and layout of various elements on the workspace. Your workspace, the Document, is a 2-dimensional area on which you place the content with high precision. In the screenshot below, the blank white area whose border is lined in red and has some light blue margin guides is the workspace.
On this sample Document, two items or frames have been placed. The one with a picture in it is called an image frame, and to its left is a text frame. To the right of our Document is the Properties window, which you will find to be one of the most important if not essential tools for using Scribus. Note that the image frame has been selected, since it is outlined in a dotted red line. For whichever item is selected, the Properties window displays and allows the adjustment of its size, position, and many other properties.
The display gives the appearance that the image frame is resting on top of the text frame -- thus a workspace has its elements on various Levels in relationship to each other. Any new element added is laid on top of others, but with the Properties window, one can move frames and other items up or down Levels. Also note that our text flows around our image -- this too is selected in the Properties window. Furthermore, while not depicted in this screenshot, a Document may have one or more Layers, each Layer being a collection of items on different Levels. This should begin to give you a sense of the complexity of Scribus and DTP. If we have Levels, why do we need Layers? A more detailed explanation and demonstration is found in the tutorial in the Wiki, but for this manual let us sum it up by saying that the Layers allow you to work on selected elements without disturbing others.
Image3: /home/downloads/Scribus/MainScreen.png
Page 2
Text4: Duplication, perhaps linked-to frame 


Font Sample

The script “Font Sampler” allows you to create a Scribus document, which contains samples of some or all on your installed fonts.

Select the fonts you would like to include in the sample in the left list (“Available Fonts”). The button with one arrow in the middle of the two lists adds the the selected fonts from the left list to the right one (“Selected Fonts”). The button with the two arrows adds all the fonts from the left list to the right one. With the buttons “Up” and “Down” you can control the order of the fonts in the right list. The buttons with arrows to the left can be used to remove entries from the list of selected fonts.

Under the list there’s a preview field, where each selected font will be displayed with an English sample text, no matter if it’s selected in the right or the left list.

Next you find some options for the layout of the sample document:

  • Print page numbers: If activated, the Scribus document will contain page numbers at the bottom of each page.
  • Print table of contents: A table of contents will be added to your document.
  • Page count includes TOC: If selected, the table of contents will have page numbers too.
  • Extra offset for binding: Adds some extra space to the left or inner margin for binding.
  • Double sided pages: The document uses facing pages.

At the bottom of the window, a status bar provides information about the number of detected and selected fonts, the number of sheets required for printing, the number of font examples per page, and the paper size. The latter will be chosen automatically from your default settings.

If you have a great many fonts installed and decide to create a document with samples of most or all of them, executing the script may take a very long time!

InfoBox

Infobox.py is a script for creating smaller frames on top of a text frame, which horizontally exactly fill the space of one or more columns. You can add either a text or image frame, and by entering imageL for frame type, you are then presented with a file dialog to choose the image to load.

Other features are that you can determine the vertical size and vertical placement within the underlying text frame. The new frame also sets text flow around frames for all frames and scales all images to frames.

The example to the right illustrates two successive runs of the program, creating one image infobox, one text infobox (the text content was added afterward).

The script will fail with an appropriate message if you do not meet these requirements:

  • You have to run this in Scribus.
  • You must have a document open.
  • A text frame is selected – it can have one or more columns, and does not have to have content.

After the script analyzes the frame, you then indicate via dialogs:

  • How many columns you wish the infobox to spread across.
    • If there is only one column this is skipped.
  • Which column to start in:
    • If there is only one column this is also skipped.
  • What height you wish the infobox to be – default is entire height of selected frame. If you are going to load an image, there is no need to change this setting – it will be adjusted automatically.
  • Where you want the top of infobox to be – default is top of selected frame, measured from the top of the document.

Now you are presented with a default name for the infobox, which you can change.

Next you select the frame type:

  • text for text frame – this is the default.
  • imageL for image frame and file dialog to load image.
  • anything else (including blank) for an empty image frame.

At this point, the infobox is created and the script ends. You can run this script again on the same selected frame.

Although there is no Scripter command for “Adjust Frame to Image,” the script has a workaround so that you can skip over specifying a height when you load an image from the script.

You cannot have your infobox extend outside your selected frame horizontally in the version that comes with Scribus, but you can do this vertically, depending on the parameters you enter for height and vertical placement.

Unflip Content

The “Unflip Content” script comes in handy if you have to make changes to your layout. Imagine you are working on a document with different margins for left and right pages, and your layout reflects the different margin settings. Imagine further that at some point you have to add a page, for instance to insert a one-page advertisement. You will now have to “flip” all content from left to right and the other way around. Look at the right page below, which then becomes a left page:

We can select all content on a page, group it and then “flip” it, but now the content is also flipped:

Here is where “Unflip Content” comes to the rescue. Select the group on the page (to work reliably, the content has to be grouped) and use Script > Scribus Scripts > UnflipContent and voilà: the images and the texts are displayed correctly again:


Scripting Basics

Some Basic Recommendations

Scripts are plain text files, and Python programs should have a .py extension – this extension is not a requirement per se, but for one thing, the file dialog uses this as a filter for its default behavior, and this is a general convention in Python script writing.

The first line of your file must begin with

#!/usr/bin/env python

or some equivalent, so that your operating system knows this is a Python script and where to find Python on your system.

The next line is strongly recommended, and if included must be the second line of the file:

# -*- coding: utf-8 -*-

which tells Python the character encoding for the file. Alternative choices to utf-8 might be latin-1 or ascii, which depend on your operating system and the editor which generated the script.

Individual comments can be inserted beginning with #. Use these to help others (and yourself for that matter) understand what the script is doing at certain points if it isn’t obvious. In many cases, thoughtfully choosing variable names can avoid the need for comments.

Other than this, it is strongly suggested to have several comment lines, demarcated by """ at beginning and end, which indicate the author(s) of the script, its purpose and perhaps some brief instructions on use, since this will be displayed to users trying to understand what a script does and how it is used. If you look at Script > About Script … > ExtractText, you will see how Scribus shows the following information:

"""
(C)2006.03.04 Gregory Pittman
(C)2008.02.28 Petr Vanek - fileDialog replaces valueDialog
this version 2008.02.28
This program is free software; you can redistribute it and/or modify
it under the terms of the  GPL, v2 (GNU General Public License as published by
the Free Software Foundation, version 2 of the License), or any later version.
See the Scribus Copyright page in the Help Browser for further informaton 
about GPL, v2.
SYNOPSIS
This script takes the current document and extracts all the text from text frames,
and also gets the pathnames to all images. This is then saved to a file named
by the user.
REQUIREMENTS
You must run from Scribus and must have a file open.
USAGE
Start the script. A file dialog appears for the name of the file 
to save to. The above information is saved to the file.
"""

After this, the actual Python commands begin. An important and usually essential one in our context is to tell Python to also look for Scripter commands in Scribus. We do this either with

import scribus

or

from scribus import *

The former is preferred, since the latter choice will load all of Scripter’s commands into Python, while import scribus only loads them as needed, and also avoids confusion both to someone reading the script and to Python when two modules might have the same command. Be aware, though, that you must indicate to Python that a command is from Scribus with a prefix, and this includes predefined constants like ICON_WARNING:

import scribus
#
# other lines of code
#
if not scribus.haveDoc():
       scribus.messageBox(’Scribus - Script Error’, "No document open", scribus.ICON_WARNING, scribus.BUTTON_OK)
       sys.exit(1)
pagenum = scribus.pageCount()

where, for example, pageCount() is the actual Scripter command. Otherwise, we could have:


from scribus import *
#
# other lines of code
#
if not haveDoc():
       messageBox(’Scribus - Script Error’, "No document open", ICON_WARNING, BUTTON_OK)
       sys.exit(1)
pagenum = pageCount()
  1. A list of all Scripter commands is available via the Help Browser.
Personal tools