Hi, I am writing a macro to translate PDF documents based on dictionary text file by automating Replace All function, where each line on the text file represents one translation string, for example:
Hello=Hola
Bye=Adios
Here is my macro:
REM ***** BASIC *****
CONST DICTPATH = "D:\EN SP dictionary.txt"
Sub Main
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")
Dim loadedDict As Variant
Set loadedDict = LoadDictionaryFromFile(DICTPATH)
Dim dictKey as Variant
For Each dictKey In loadedDict.Keys()
ReplaceAll(dictKey, loadedDict.Item(dictKey))
Next
End Sub
Function ReplaceAll(searchString, replacementString) As Long
Dim oReplace as Object
Dim oDrawPages as Object
Dim oDrawPage as Object
oDrawPages = ThisComponent.getDrawPages()
for Each oDrawPage in oDrawPages
oReplace = oDrawPage.createReplaceDescriptor
oReplace.setSearchString( searchString )
oReplace.setReplaceString( replacementString )
ReplaceAll = oDrawPage.replaceAll( oReplace )
Next
End Function
Function LoadDictionaryFromFile() As Scripting.Dictionary
Dim FSO As Object, MyFile As Object
Dim FileName As String, Arr As Variant
FileName = DICTPATH
Set FSO = CreateObject("Scripting.FileSystemObject")
Set MyFile = FSO.OpenTextFile(FileName, 1)
Arr = Split(MyFile.ReadAll, Chr(13))
Dim loadedDict As Variant
loadedDict = CreateScriptService("Dictionary")
Dim arrString as String
For Each arrString in Arr
Dim arrStringSplit as Variant
arrStringSplit = Split(arrString, "=")
loadedDict.Add(arrStringSplit(0), arrStringSplit(1))
Next
LoadDictionaryFromFile = loadedDict
End Function
As you can see, it loads the text file, parses it to turn it’s contents into a dictionary variable (I confirmed that this part definitely works), and then runs a loop to replace all matching English strings with Spanish translations.
The issue is that while the loop runs twice in this example, it only replaces the first instances of the string (all “Hello” get replaced by “Hola”, but “Bye” does not get replaced by “Adios”). If I swap them in my dictionary text file, then “Bye” gets replaced, but “Hello” does not.
So clearly the oDrawPage.replaceAll function only works once per macro run, and I can’t figure out why. Do I need to run some additional API call to allow replaceAll to be work again or something? Some kind of refresh maybe?