PDF Snake Scripting Tutorial

 

PDF Snake home

scripting reference

table of contents

Data Mailer

So now we have seen the template file and the data we want to substitute into it, so it's time to write some code.

First, let's write our main data mailer function:

def
DataMailer
(
sTemplateFile
,
tupData
)
:
doc
=
acrobat
.
documentOpen
(
sTemplateFile
)
docNew
=
acrobat
.
documentNew
(
)
docNew
[
:
]
=
doc
[
0
:
1
]
*
len
(
tupData
)
for
i
in
range
(
len
(
tupData
)
)
:
dictSubs
=
MakeSubsDictionary
(
tupData
[
i
]
)
docNew
[
i
]
.
textrunReplace
(
dictSubs
)
return
docNew

The first interesting new line is this one:

    docNew
[
:
]
=
doc
[
0
:
1
]
*
len
(
tupData
)

In short, this line sets the contents of our new document to be N copies of our template page, where N is the number of people we are customizing the postcard for.

Pages are accessed in a document using Python's slice [] operator. For example, doc[0] returns the first page in a document. In this case docNew[:] = means we are setting the entire page range in docNew.

doc[0:1] gets the page range containing the first page of doc. We have to get a page range, not just the first page, because we cannot set a page range to a page. A page range must be set to a page range. In Python, just as 'H' * 5 returns the string 'HHHHH', multiplying doc[0:1] * len( tupData) returns a page range containing as many pages as there are rows in our data.

The next interesting line is:

	dictSubs 
=
MakeSubsDictionary
(
tupData
[
i
]
)

MakeSubsDictionary() is a function that we'll define in a minute. It takes one row of our data and translates it into a Python dictionary, so that we can pass it to the textrunReplace() method.

	docNew
[
i
]
.
textrunReplace
(
dictSubs
)

This is the line which actually replaces the text in the template. As an argument, it takes a dictionary where the keys are the strings to be replaced and the values are the what will replace them. For example, the dictionary:

 { 'big' : 'large'}

will replace all occurences of the word 'big' with the word 'large'.

Next Page >>