Creating a TOC with Scripter: Difference between revisions

From Scribus Wiki
Jump to navigation Jump to search
 
(16 intermediate revisions by the same user not shown)
Line 5: Line 5:
I had already written a script that could analyze the content of a document and extract text and filenames of the images in the file, page by page. What follows is a modification of that script for creating a table of contents.
I had already written a script that could analyze the content of a document and extract text and filenames of the images in the file, page by page. What follows is a modification of that script for creating a table of contents.


To use this script, although it's not a requirement, it is useful to rename the frames to something useful in a TOC. One problem with this is that you will find that, at least when you edit the frame name, you cannot have spaces, so instead of ''First Article'' we'll use ''First_Article'', substituting an underline for the space – don't worry, we take care of that in the script.
To use this script, although it's not a requirement, it is useful to rename the frames to something useful in a TOC. One problem with this is that you will find that, at least when you edit the frame name, it cannot have spaces, so instead of ''First Article'' we'll use ''First_Article'', substituting an underline for the space – don't worry, we take care of switching back in the script.
===createTOC.py===
===createTOC.py===
<pre>
<pre>
Line 57: Line 57:
===Using the Script===
===Using the Script===
{|
{|
|[[File:CreateTOC2.png]]
|valign="top"|[[File:CreateTOC2.png]]
|
|
{|
{|
|Here is a simple artificial document, with sample text and an image frame, copied four times, then arbitrary images loaded. I've changed the frame names as we'll see. Again, instead of spaces between words of the frame names I have used an underline character.
|Here is a simple artificial document, with sample text and an image frame, copied four times, then arbitrary images loaded. I've changed the frame names as we'll see. Again, instead of spaces between words of the frame names I have used an underline character. These are not the image file names, but the names we are assigning to the image frames.


We simply run this script, which asks for a filename to store our text for the table of contents. Next, make a text frame, then using ''Get Text'', load this text, and you get what you see below to the left.  
We simply run this script, which asks for a filename to store our text for the table of contents. Next, make a text frame, then using ''Get Text'', load this text, and you get what you see below to the left. This can easily be an iterative process, where you might continue to add pages and content, then rerun the script and replace the text in the TOC frame.


Sure, it's a bit sloppy, but all it takes to make it look like the list below on the right is to adjust the tabulators &ndash; in this case just make one right tab at about 200 pts.
Sure, it's a bit sloppy, but all it takes to make it look like the list below on the right is to adjust the tabulators &ndash; in this case just make one right tab at about 200 pts.
I considered having the script create a TOC frame, or use an existing selected frame, and then rather than save to a file just put the TOC list right into the frame, but in the end it did not seem such a great advantage. If you create a frame with the script, then you have to decide where it would be, its size, and a number of other features. If you use an existing frame, this frame will also be included in the list and will need to be deleted from it.
|-
|-
{|
{|
Line 79: Line 81:
{|
{|
|[[File:CreateTOC3.png]]
|[[File:CreateTOC3.png]]
|valign=top|This produces a different sort of format, with text frames first, images later. Again, you could delete the images list if you wish. Here we have not only adjusted tabs (there are 2 here), but also text distances and given the frame border a color.
|valign=top|This produces a different sort of format, with text frames first, images later. There is logic built in so that if there are no images, only text frame names will be listed. Again, you could delete the images list if you wish.  
After running the script, here we have not only adjusted tabs (there are 2 here), but also text distances and given the frame border a color.
 
If you want to consider listing other sorts of content, the value for item[1] (in other words, the second element of the tuple you get for each page object when you use ''getPageItems()'') for shapes and polygons is 6. It is also 6 for SVGs, but keep in mind that many SVGs are a grouped object, and in that case each part of the group will be listed in your TOC. For Render frames, item[1] is 9.
|}
|}
<pre>
<pre>

Latest revision as of 16:30, 7 August 2011

This article is part of the Scripts series.

While working on some documentation for generating a TOC in something of an automatic way with Scribus, it seemed to me that this seems rather complex, and I wondered if there might be a better way to do this with Scripter.

I had already written a script that could analyze the content of a document and extract text and filenames of the images in the file, page by page. What follows is a modification of that script for creating a table of contents.

To use this script, although it's not a requirement, it is useful to rename the frames to something useful in a TOC. One problem with this is that you will find that, at least when you edit the frame name, it cannot have spaces, so instead of First Article we'll use First_Article, substituting an underline for the space – don't worry, we take care of switching back in the script.

createTOC.py

#!/usr/bin/env python
# File: createTOC.py - Creates a Table of Contents from text
# and image frames, using frame names as the reference
# This version 2011.08.06
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

import scribus

def exportText(textfile):
    page = 1
    pagenum = scribus.pageCount()
    T = []
    while (page <= pagenum):
        scribus.gotoPage(page)
        d = scribus.getPageItems()
        strpage = str(page)
        for item in d:
            if (item[1] == 4):
                rawname = item[0]
                newname = rawname.replace('_',' ')
                T.append(newname + '\t'+ strpage + '\n')
            elif (item[1] == 2):
                rawname = item[0]
                newname = rawname.replace('_',' ')   # where we switch underline to space
                T.append(newname + ' (image)' + '\t' + strpage + '\n')
        page += 1
    output_file = open(textfile,'w')
    output_file.writelines(T)
    output_file.close()
    endmessage = textfile + ' was created'
    scribus.messageBox("Finished", endmessage,icon=0,button1=1)
if scribus.haveDoc():
    textfile = scribus.fileDialog('Enter name of file to save to', filter='Text Files (*.txt);;All Files (*)')
    try:
        if textfile == '':
            raise Exception
        if (textfile[-4:] != '.txt'):
            textfile = textfile + '.txt'
        exportText(textfile)
    except Exception, e:
        print e
else:
    scribus.messageBox('Export Error', 'You need a Document open, and a frame selected.', icon=0, button1=1)

Using the Script

CreateTOC2.png
Here is a simple artificial document, with sample text and an image frame, copied four times, then arbitrary images loaded. I've changed the frame names as we'll see. Again, instead of spaces between words of the frame names I have used an underline character. These are not the image file names, but the names we are assigning to the image frames.

We simply run this script, which asks for a filename to store our text for the table of contents. Next, make a text frame, then using Get Text, load this text, and you get what you see below to the left. This can easily be an iterative process, where you might continue to add pages and content, then rerun the script and replace the text in the TOC frame.

Sure, it's a bit sloppy, but all it takes to make it look like the list below on the right is to adjust the tabulators – in this case just make one right tab at about 200 pts.

I considered having the script create a TOC frame, or use an existing selected frame, and then rather than save to a file just put the TOC list right into the frame, but in the end it did not seem such a great advantage. If you create a frame with the script, then you have to decide where it would be, its size, and a number of other features. If you use an existing frame, this frame will also be included in the list and will need to be deleted from it.

CreateTOC.png CreateTOC1.png

As you can see, this initial script lists page by page and includes the images. If we didn't want to list images we could just comment out that part of the script, or edit the TOC frame. But let's also create a different version of the script for a different kind of list.

createTOC2.py

CreateTOC3.png This produces a different sort of format, with text frames first, images later. There is logic built in so that if there are no images, only text frame names will be listed. Again, you could delete the images list if you wish.

After running the script, here we have not only adjusted tabs (there are 2 here), but also text distances and given the frame border a color.

If you want to consider listing other sorts of content, the value for item[1] (in other words, the second element of the tuple you get for each page object when you use getPageItems()) for shapes and polygons is 6. It is also 6 for SVGs, but keep in mind that many SVGs are a grouped object, and in that case each part of the group will be listed in your TOC. For Render frames, item[1] is 9.

#!/usr/bin/env python
# File: createTOC2.py - Creates a Table of Contents from text
# and image frames, using frame names as the reference
# This version 2011.08.06
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

import scribus

def exportText(textfile):
    page = 1
    pagenum = scribus.pageCount()
    T = []
    images = 'no'
    while (page <= pagenum):
        scribus.gotoPage(page)
        d = scribus.getPageItems()
        strpage = str(page)
        for item in d:
            if (item[1] == 4):
                rawname = item[0]
                newname = rawname.replace('_',' ')
                T.append(newname + '\t'+ strpage + '\n')
            elif (item[1] == 2):
                images = 'yes'
        page += 1
    if (images == 'yes'):
        page = 1
        T.append('\n'+ 'Images' + '\n')
        while (page <= pagenum):
            scribus.gotoPage(page)
            d = scribus.getPageItems()
            strpage = str(page)
            for item in d:
                if (item[1] == 2):
                    rawname = item[0]
                    newname = rawname.replace('_',' ')
                    T.append('\t' + newname + '\t' + strpage + '\n')
            page += 1
    output_file = open(textfile,'w')
    output_file.writelines(T)
    output_file.close()
    endmessage = textfile + ' was created'
    scribus.messageBox("Finished", endmessage,icon=0,button1=1)
if scribus.haveDoc():
    textfile = scribus.fileDialog('Enter name of file to save to', filter='Text Files (*.txt);;All Files (*)')
    try:
        if textfile == '':
            raise Exception
        if (textfile[-4:] != '.txt'):
            textfile = textfile + '.txt'
        exportText(textfile)
    except Exception, e:
        print e
else:
    scribus.messageBox('Export Error', 'You need a Document open, and a frame selected.', icon=0, button1=1)