Newsroom Update

New features come to Apple services this fall. Learn more >

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Batch Convert pages to Word Document in multiple folders

I found an answer for one folder and must select both folders input and output by: VikingOSX

 Reference: Batch Convert pages to Word Document- Mac… - Apple Community

It worked perfectly but in my case I have multiple folders within main folder some have pages files and other don't, is there a way to look through including folders and if there is a pages file create a folder named "word" and convert all pages files into it?




MacBook Pro 15″, macOS 13.0

Posted on Dec 6, 2022 3:01 AM

Reply
Question marked as Best reply

Posted on Dec 6, 2022 10:09 AM

For this particular exercise, I chose an Automator application solution over a more complicated (read time consuming to debug) Shortcut solution. The code works on Ventura 13.0.1, and should also work on earlier versions of macOS.


It will prompt your for the parent folder that contains your subfolders and Pages document hierarchy. It works on an list of your Pages documents, determines for a given document location if a "Word" folder exists and makes one if missing. It then requests that Pages export that Pages document to .docx with that respective Word folder as the export target. When done, a completion dialog will appear showing how many Pages documents were processed and a count of Word documents exported.



Because of your volume (6000) of Pages documents, I chose to use the Zsh shell instead of AppleScript. With this volume of files, it will still run for a long while as the Pages export process will take its toll on the clock.


Steps:

  1. Launch Automator from your /Applications folder.
    1. From the initial Automator dialog select Application and then click Choose
    2. In order left to right, you will have a list of libraries, actions in those libraries, and the much larger (and currently) empty Workflow window.
  2. Configure Workflow actions
    1. Files & Folders library
      1. Drag and drop Ask for Finder Items action onto the Workflow window
      2. Start at: Desktop
      3. Type: Folder
      4. Do not select Multiple Selection
    2. Utilities library
      1. Drag and drop Run Shell Script action onto the Workflow window
      2. Shell: /bin/zsh
      3. Pass Input: as arguments
      4. remove all content in this action as it will be replaced by Code shown below.
    3. Save the Automator application (e.g. name it Pages2Docx) and you do not need to give it an extension
    4. Quit Automator
    5. Try the new application


Copy and paste the following code into the now blank Run Shell Script window.


Code:


#!/bin/zsh

: <<"COMMENT"
Do a recursive descent on a folder hierarchy gathering Pages document. Export these
documents from Pages as Word .docx documents into a Word folder at the file location.
If the Word folder does not exist at the particular folder location, then create it.
Tested: Ventura 13.0.1
VikingOSX, 2022-12-06, Apple Support Communities, No implicit warranty or support.
COMMENT

typeset -gi pagesCnt=0 docxCnt=0

STARTDIR="${@}"

function pages_export () {

    /usr/bin/osascript <<-AS
    use scripting additions

    tell application "Pages"
        activate
        try
            set infile to POSIX file "${1}"
            set outfile to POSIX file "${2}"

            set thisDoc to open infile as alias

            with timeout of 1200 seconds
                export thisDoc to file outfile as Microsoft Word
            end timeout
            close thisDoc saving no
        on error errmsg number errNo
            display dialog "[ " & errNo & " ]: " & errmsg
        end try
    end tell
    -- unhide the exported filename extensions
    tell application "Finder"
        if exists (item outfile as alias) then
            set extension hidden of (item outfile as alias) to false
        end if
    end tell
    return
AS
}

function completion () {
    /usr/bin/osascript <<-AS
    use scripting additions

    set DialogIcon to "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MultipleItemsIcon.icns"

    display dialog "Pages documents found: " & "${1}" & return & ¬
        "Pages documents exported to Word docx: " & "${2}" with title "Processing Complete" with icon POSIX file DialogIcon
    return
AS
}

# ask user for the starting folder from a choose folder dialog
parent_folder="$(folder_prompt)"

# do a case-insensitive recursion finding Pages documents and sorting by name
setopt nocaseglob
for f in ${STARTDIR}/**/*.pages(.Non);
do
    (( ++pagesCnt ))
    # if there is no Word folder at this file location, then make one
    [[ -d "${f:a:h:r}/Word" ]] || mkdir -p "${f:a:h:r}/Word"

    # construct the full path to the word docx document to be exported
    wordfile="${f:a:h:r}/Word/${f:r:t}.docx"

    pages_export "${f}" "${wordfile}"

    # do we have an exported docx that is non-zero in size?
    [[ -s $wordfile ]] && (( ++docxCnt ))
done

# give the user statistics
completion $pagesCnt $docxCnt



29 replies
Question marked as Best reply

Dec 6, 2022 10:09 AM in response to Moaweyah

For this particular exercise, I chose an Automator application solution over a more complicated (read time consuming to debug) Shortcut solution. The code works on Ventura 13.0.1, and should also work on earlier versions of macOS.


It will prompt your for the parent folder that contains your subfolders and Pages document hierarchy. It works on an list of your Pages documents, determines for a given document location if a "Word" folder exists and makes one if missing. It then requests that Pages export that Pages document to .docx with that respective Word folder as the export target. When done, a completion dialog will appear showing how many Pages documents were processed and a count of Word documents exported.



Because of your volume (6000) of Pages documents, I chose to use the Zsh shell instead of AppleScript. With this volume of files, it will still run for a long while as the Pages export process will take its toll on the clock.


Steps:

  1. Launch Automator from your /Applications folder.
    1. From the initial Automator dialog select Application and then click Choose
    2. In order left to right, you will have a list of libraries, actions in those libraries, and the much larger (and currently) empty Workflow window.
  2. Configure Workflow actions
    1. Files & Folders library
      1. Drag and drop Ask for Finder Items action onto the Workflow window
      2. Start at: Desktop
      3. Type: Folder
      4. Do not select Multiple Selection
    2. Utilities library
      1. Drag and drop Run Shell Script action onto the Workflow window
      2. Shell: /bin/zsh
      3. Pass Input: as arguments
      4. remove all content in this action as it will be replaced by Code shown below.
    3. Save the Automator application (e.g. name it Pages2Docx) and you do not need to give it an extension
    4. Quit Automator
    5. Try the new application


Copy and paste the following code into the now blank Run Shell Script window.


Code:


#!/bin/zsh

: <<"COMMENT"
Do a recursive descent on a folder hierarchy gathering Pages document. Export these
documents from Pages as Word .docx documents into a Word folder at the file location.
If the Word folder does not exist at the particular folder location, then create it.
Tested: Ventura 13.0.1
VikingOSX, 2022-12-06, Apple Support Communities, No implicit warranty or support.
COMMENT

typeset -gi pagesCnt=0 docxCnt=0

STARTDIR="${@}"

function pages_export () {

    /usr/bin/osascript <<-AS
    use scripting additions

    tell application "Pages"
        activate
        try
            set infile to POSIX file "${1}"
            set outfile to POSIX file "${2}"

            set thisDoc to open infile as alias

            with timeout of 1200 seconds
                export thisDoc to file outfile as Microsoft Word
            end timeout
            close thisDoc saving no
        on error errmsg number errNo
            display dialog "[ " & errNo & " ]: " & errmsg
        end try
    end tell
    -- unhide the exported filename extensions
    tell application "Finder"
        if exists (item outfile as alias) then
            set extension hidden of (item outfile as alias) to false
        end if
    end tell
    return
AS
}

function completion () {
    /usr/bin/osascript <<-AS
    use scripting additions

    set DialogIcon to "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MultipleItemsIcon.icns"

    display dialog "Pages documents found: " & "${1}" & return & ¬
        "Pages documents exported to Word docx: " & "${2}" with title "Processing Complete" with icon POSIX file DialogIcon
    return
AS
}

# ask user for the starting folder from a choose folder dialog
parent_folder="$(folder_prompt)"

# do a case-insensitive recursion finding Pages documents and sorting by name
setopt nocaseglob
for f in ${STARTDIR}/**/*.pages(.Non);
do
    (( ++pagesCnt ))
    # if there is no Word folder at this file location, then make one
    [[ -d "${f:a:h:r}/Word" ]] || mkdir -p "${f:a:h:r}/Word"

    # construct the full path to the word docx document to be exported
    wordfile="${f:a:h:r}/Word/${f:r:t}.docx"

    pages_export "${f}" "${wordfile}"

    # do we have an exported docx that is non-zero in size?
    [[ -s $wordfile ]] && (( ++docxCnt ))
done

# give the user statistics
completion $pagesCnt $docxCnt



Dec 6, 2022 11:43 AM in response to Moaweyah

Since Pages is not a Word clone, there is no guarantee that the exporting to Word will appear the same in Word as it does in Pages. Features unique to Pages and not available in Word will get dropped.


A more accurate solution might be to export the Pages document to PDF, and as needed, open that PDF in Word v16.31 or later and it will be converted to Word .docx. I would expect the accuracy of this conversion done by Word to be better than what one could expect from a Pages translation.


Probably a ten minute fix to the existing script to switch to PDF and not .docx.


By the way, I omited something from the Automator configuration post. When you first run the application, you will get at least one dialog that you should click OK:


Dec 6, 2022 4:09 PM in response to Moaweyah

I have revised the Run Shell Script content to produce this output with the added PDF export included:



The default folders in macOS are blue, so not sure what you meant by that, and at any rate, I cannot change folder colors with a script.


Replace the entire contents of your Run Shell Script action with the following code:


#!/bin/zsh

: <<"COMMENT"
Do a recursive descent on a folder hierarchy gathering Pages document. Export these
documents from Pages as Word .docx documents (and PDF) into a Word folder at the file location.
If the Word folder does not exist at the particular folder location, then create it.
Tested: Ventura 13.0.1
VikingOSX, 2022-12-06, Apple Support Communities, No implicit warranty or support.
COMMENT

typeset -gi pagesCnt=0 docxCnt=0 pdfCnt=0

STARTDIR="${@}"

function pages_export () {

    /usr/bin/osascript <<-AS
    use scripting additions

    tell application "Pages"
        activate
        try
            set infile to POSIX file "${1}"
            set wordOutFile to POSIX file "${2}"
            set pdfOutFile to POSIX file "${3}"

            set thisDoc to open infile as alias

            with timeout of 1200 seconds
                export thisDoc to file wordOutFile as Microsoft Word
                export thisDoc to file pdfOutFile as PDF with properties {image quality:Best}
            end timeout
            close thisDoc saving no
        on error errmsg number errNo
            display dialog "[ " & errNo & " ]: " & errmsg
        end try
    end tell
    -- unhide the exported filename extensions
    tell application "Finder"
        if exists (item wordOutFile as alias) then
            set extension hidden of (item wordOutFile as alias) to false
        end if
        if exists (item pdfOutFile as alias) then
            set extension hidden of (item pdfOutFile as alias) to false
        end if
    end tell
    return
AS
}

function completion () {
    /usr/bin/osascript <<-AS
    use scripting additions

    set DialogIcon to "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MultipleItemsIcon.icns"

    tell application "Pages" to if it is running then quit

    display dialog "Pages documents found:  ${1}" & return & ¬
        "Exported to Word docx:  ${2}" & return & ¬
        "Exported to PDF files:  ${3}" with title "Processing Complete" with icon POSIX file DialogIcon
    return
AS
}

# do a case-insensitive recursion finding Pages documents and sorting by name
setopt nocaseglob
for f in ${STARTDIR}/**/*.pages(.Non);
do
    (( ++pagesCnt ))
    # if there is no Word folder at this file location, then make one
    [[ -d "${f:a:h:r}/Word" ]] || mkdir -p "${f:a:h:r}/Word"

    # construct the full path to the word docx document and PDF to be exported
    wordfile="${f:a:h:r}/Word/${f:r:t}.docx"
    pdffile="${f:a:h:r}/Word/${f:r:t}.pdf"

    pages_export "${f}" "${wordfile}" "${pdffile}"

    # do we have an exported docx and PDF that is non-zero in size?
    [[ -s $wordfile ]] && (( ++docxCnt ))
    [[ -s $pdffile ]] && (( ++pdfCnt ))
done

# give the user statistics
completion $pagesCnt $docxCnt $pdfCnt


Dec 7, 2022 1:55 AM in response to VikingOSX

it keeps opening pages files and shows the following massage form pages and when I click ok the next one opens and so on, how can I stop it from opening I tried to cancel the application but it didn't stop opening the pages files.

using macOS High Sierra

[ -1728 ]: Pages got an error: Can’t get file (file "Macintosh HD:Users:......:Various files:Word:32327.docx").

Dec 8, 2022 3:42 AM in response to Moaweyah

Hello, I did everything you told me but still getting this error from both Ventura and High Sierra, and there are some files are not been exported, but tried the first application the one with apple script it worked with those files, could you do the application using AppleScript it might work?


I chose to use the Zsh shell instead of AppleScript. With this volume of files, it will still run for a long while as the Pages export process will take its toll on the clock.

Dec 8, 2022 6:05 AM in response to Moaweyah

I have deleted, and rebuilt Automator applications containing the following code. These Automator applications worked without error and produced the correct output on macOS High Sierra 10.13.6, macOS Monterey 12.6.1, and macOS Ventura 13.0.1. I recommend that you start over and copy/paste the following code into separate Automator application Run Shell Script actions, save those applications, and run again. On Monterey and Ventura, you may receive up to three separate prompts to authorize Finder or Pages to do some action and you need to click OK on those. If you don't the application may fail.


Start with this:



Clear out all default content in that Run Shell Script action, and paste this code into it:


: <<"COMMENT"
Do a recursive descent on a folder hierarchy gathering Pages document. Export these
documents from Pages as Word .docx documents (and PDF) into a Word folder at the file location.
If the Word folder does not exist at the particular folder location, then create it.
Tested: Ventura 13.0.1
VikingOSX, 2022-12-06, Apple Support Communities, No implicit warranty or support.
COMMENT

typeset -gi pagesCnt=0 docxCnt=0 pdfCnt=0

STARTDIR="${@:a:s/\~\//}"

trap 'error_report $LINENO' ERR

function error_report () {
	echo "Error on line $1"
	exit 1
}

function pages_export () {

    /usr/bin/osascript <<-AS
    use scripting additions

    set infile to POSIX file "${1}" as alias
    set wordOutFile to POSIX file "${2}" as text
    set pdfOutFile to POSIX file "${3}" as text

    tell application "Pages"
        activate
        set thisDoc to open infile
        try
            with timeout of 1200 seconds
                export thisDoc to file wordOutFile as Microsoft Word
                export thisDoc to file pdfOutFile as PDF with properties {image quality:Best}
            end timeout
            close thisDoc saving no
        on error errmsg number errNo
            display dialog "[ " & errNo & " ]: " & errmsg
            close thisDoc saving no
            return
        end try
    end tell
    -- unhide the exported filename extensions
    tell application "Finder"
        if exists (item wordOutFile as alias) then
            set extension hidden of (item wordOutFile as alias) to false
        end if
        if exists (item pdfOutFile as alias) then
            set extension hidden of (item pdfOutFile as alias) to false
        end if
    end tell
    return
AS
}

function completion () {
    /usr/bin/osascript <<-AS
    use scripting additions

    set DialogIcon to "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/MultipleItemsIcon.icns"

    tell application "Pages" to if it is running then quit

    display dialog "Pages documents found:  ${1}" & return & ¬
        "Exported to Word docx:  ${2}" & return & ¬
        "Exported to PDF files:  ${3}" with title "Processing Complete" with icon POSIX file DialogIcon
    return
AS
}

# do a case-insensitive recursion finding Pages documents and sorting by name
setopt nocaseglob
for f in ${STARTDIR}/**/*.pages(.Non);
do
    (( ++pagesCnt ))
    # if there is no Word folder at this file location, then make one
    [[ -d "${f:a:h:r}/Word" ]] || mkdir -p "${f:a:h:r}/Word"

    # construct the full path to the word docx document and PDF to be exported
    wordfile="${f:a:h:r}/Word/${f:r:t}.docx"
    pdffile="${f:a:h:r}/Word/${f:r:t}.pdf"

    pages_export "${f}" "${wordfile}" "${pdffile}"

    # do we have an exported docx and PDF that is non-zero in size?
    [[ -s $wordfile ]] && (( ++docxCnt ))
    [[ -s $pdffile ]] && (( ++pdfCnt ))
done

# give the user statistics
completion $pagesCnt $docxCnt $pdfCnt


I have too many demands on my time to rewrite this entire solution in AppleScript. Not all Pages documents from years past can open correctly in Pages v8.1 or newer, and any issue with opening, or issues encountered when exporting can cause the workflow to fail.

Dec 11, 2022 3:35 AM in response to VikingOSX

The same issue with the files that have extension of .pages and some other too are not being opened and exported:

I am trying only on number of files before testing on all the files so it doesn't hang.

if there is no resolve for this issue its okay I can try open the files not being exported and export it one by one the help you did already helped a lot. thanks in advance.

Dec 6, 2022 7:50 AM in response to Moaweyah

I had a working AppleScript by 9:30 am and no end of trouble adapting it to work in Shortcuts. Since you have that many Pages documents, I will need to get the Pages documents in that hierarchy using another approach to Finder as it would take forever. I may provide this as an Automator application if I cannot get it to work in Shortcuts.

Dec 6, 2022 2:18 PM in response to VikingOSX

Thanks a million!, if possible I would appreciate if you would make both pdf and word as exported in the created word folder, as I want to open the file from windows and usually edit it, and while editing the code could you make the word folder colored blue to be easily noticed.

I’ll be using the application on an old mac pro (late 2013) with its basic OS, tried the old program on it and worked fine but not sure it would convert the file as same as new macOS would with the latest pages version vs the old one. But will check first as I can’t update the old mac pro as it is been used as a server and the files are on it and it would be much faster to run it rather from the MacBook Pro 2017 connected to the server through wifi right?

Dec 7, 2022 8:27 AM in response to Moaweyah

As I mentioned at the outset, this is a solution tested on Ventura 13.0.1. AppleScript on Ventura behaves differently than AppleScript on High Sierra, and I had to make some slight changes to the code on High Sierra to make it work correctly.


Replace the pages_export function in the script with this code. It will run correctly on High Sierra, Monterey, and Ventura where I have now tested it. Assumption: Pages v8.1 on High Sierra, and v12.2.1 on others.


function pages_export () {

    /usr/bin/osascript <<-AS
    use scripting additions

    set infile to POSIX file "${1}" as alias
    set wordOutFile to POSIX file "${2}" as text
    set pdfOutFile to POSIX file "${3}" as text

    tell application "Pages"
        activate
        set thisDoc to open infile
        try
            with timeout of 1200 seconds
                export thisDoc to file wordOutFile as Microsoft Word
                export thisDoc to file pdfOutFile as PDF with properties {image quality:Best}
            end timeout
            close thisDoc saving no
        on error errmsg number errNo
            display dialog "[ " & errNo & " ]: " & errmsg
            close thisDoc saving no
            return
        end try
    end tell
    -- unhide the exported filename extensions
    tell application "Finder"
        if exists (item wordOutFile as alias) then
            set extension hidden of (item wordOutFile as alias) to false
        end if
        if exists (item pdfOutFile as alias) then
            set extension hidden of (item pdfOutFile as alias) to false
        end if
    end tell
    return
AS
}



Dec 7, 2022 10:31 AM in response to VikingOSX

Will test and let you know, sorry I tried doing it from my MacBook Pro but it would take a long time that is why I would do it on the Mac Pro to leave it and check it the next day, now if you could just help me with how to force the application to stop as I did force quit it and stopped it from the top bar but it is still running and pages files are opening with the error message, so how to stop the application from running, on the MacBook pro I had to restart the laptop but can’t restart the mac pro as I’m connected to it remotely. Thanks a lot.

Dec 7, 2022 12:51 PM in response to Moaweyah

Because the error occurs within the pages_export function and not the actual Zsh shell, the latter just continues to feed documents to that function because of the shell loop.


Let's see if this will stop the script entirely when an error condition appears. Make these changes:


From:


typeset -gi pagesCnt=0 docxCnt=0 pdfCnt=0


To:


typeset -gi pagesCnt=0 docxCnt=0 pdfCnt=0

trap 'error_report $LINENO' ERR

function error_report () {
	echo "Error on line $1"
	exit 1
}


You shouldn't encounter that Pages error condition again as that was fixed in the most recent changes I posted for you this (2022-12-07) morning.


Batch Convert pages to Word Document in multiple folders

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.