0

I would like to use a python script to find and replace some text in an InDesign file and then save it as pdf.

I managed to use python to open indesign and save it as pdf however I do not know how to search for text and replace it with a random string generated by the first part of the script.

Here is what I got so far:

import win32com.client
import random
import string

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

voucher=id_generator()

app = win32com.client.Dispatch('InDesign.Application.CC.2018')
myFile = r'C:\Users\some_file.indd'
    myDocument = app.Open(myFile)
myPDFFile = r'C:\Users\some_file.pdf'
    directory = os.path.dirname(myPDFFile)

    idPDFType = 1952403524
    # 1=[High Quality Print], 2=[PDF/X-1a:2001] etc..
    myPDFPreset = app.PDFExportPresets.Item(1)
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
        if os.path.exists(directory):
            myDocument.Export(idPDFType, myPDFFile, False, myPDFPreset)
    except Exception as e:
        print('Export to PDF failed: ' + str(e))
    myDocument.Close()
Irah
  • 1
  • 1

1 Answers1

0

You need to iterate over all of the TextFrames of the document and then search and replace the text with the ChangeText function.

Here is a snippet of what you can do:

voucher = id_generator()
searchText = 'test'

app = win32com.client.Dispatch('InDesign.Application.CC.2018')
app.scriptPreferences.userInteractionLevel = 1699640946
myFile = r'C:\Users\some_file.indd'
myDocument = app.Open(myFile)
myPage = myDocument.Pages.Item(1)

idNothing = 1851876449  #from enum idNothingEnum, see doc_reference

for it in myDocument.TextFrames:
    if searchText in (it.Contents):
        app.FindTextPreferences.FindWhat = searchText
        app.ChangeTextPreferences.ChangeTo = voucher
        it.ChangeText()
        continue        

    app.FindTextPreferences.FindWhat = idNothing
    app.ChangeTextPreferences.ChangeTo = idNothing

#and then save the changes as PDF...