Date Setting by Script

From Scribus Wiki
Revision as of 14:31, 30 December 2013 by Kunda (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
This article is part of the Scripts series.

A small chore I have been having is to daily create a page which has a header including the date. This kind of thing might come up with someone making a newsletter or other periodical.

Here is something like I wanted my header to look:

Dateheader.png

To the left is a static title, then the date is displayed with a particular format, and there is a right tab to place the date properly in the frame. Top and Left distances bring the line of text in the middle of the frame. I thought it would be nice to just run a short script to update the date each time I made another, and such commands are avaiable in a standard Python distribution.

The script

#!/usr/bin/env python
# -*- coding: utf-8  -*-
# header_date.py
 
try:
     import scribus
except ImportError:
     print "Unable to import the 'scribus' module. This script will only run within"
     print "the Python interpreter embedded in Scribus. Try Script->Execute Script."
     sys.exit(1)
 
from datetime import date
 
if not scribus.haveDoc():
     scribus.messageBox('Scribus - Script Error', "No document open", scribus.ICON_WARNING, scribus.BUTTON_OK)
     sys.exit(1)
 
if scribus.selectionCount() == 0:
     scribus.messageBox('Scribus - Script Error',
             "There is no object selected.\nPlease select a text frame and try again.",
             scribus.ICON_WARNING, scribus.BUTTON_OK)
     sys.exit(2)
if scribus.selectionCount() > 1:
     scribus.messageBox('Scribus - Script Error',
             "You have more than one object selected.\nPlease select one text frame and try again.",
             scribus.ICON_WARNING, scribus.BUTTON_OK)
     sys.exit(2)
textbox = scribus.getSelectedObject()
ftype = scribus.getObjectType(textbox)
 
if (ftype != "TextFrame"):
     scribus.messageBox('Scribus - Script Error', "This is not a textframe. Try again.", scribus.ICON_WARNING, scribus.BUTTON_OK)
     sys.exit(2)
 
scribus.deleteText(textbox)
 
today = date.today()
d = today.strftime("%A, %B %d, %Y")
headerstr = "Scribus Times & Gazette\t" + d
scribus.setText(headerstr, textbox)
scribus.setStyle("header", textbox)

As you can see, most of the script is to handle various errors, like not having a document open, not selecting a frame, not selecting a text frame, and so on. I have some static text and a style named header. Rather than try to parse the contents, I simply deleteText(), setText(), then setStyle().

From Python, we are pulling in the date command from the datetime module, and from this date.today() generates today's date. The strftime command formats the output. If we had put

d = today.strftime("%A, %d %B %Y")

we would get

Dateheader1.png

Related