NSAttributedString.DocumentType for .pages documents

Is there a way in swift to extract text from a .pages file? There are DocumentTypes e.g. for .rtf, officeOpenXML etc. but not for the apple own .pages format.

Posted on Sep 7, 2022 2:29 AM

Reply
Question marked as Top-ranking reply

Posted on Sep 7, 2022 10:36 AM

And working swift code to return the plain body text of a Pages document to a variable using NSAppleScript from Foundation:


#!/usr/bin/swift

import Foundation


var AS: String = """
use scripting additions

tell application "Pages"
activate
open file (choose file of type {"Pages"})
tell front document to set btext to its body text
close front document
end tell
return btext as text
tell application "Pages" to if it is running then quit
"""

var errorDict: NSDictionary?
let ascript = NSAppleScript(source:AS)!

guard let output: String = ascript.executeAndReturnError(&errorDict).stringValue else {
    print("script failed to execute")
    exit(EXIT_FAILURE)
}

print(output)

Tested on macOS 11.6.8 with Swift version 5.5.2.

3 replies
Question marked as Top-ranking reply

Sep 7, 2022 10:36 AM in response to VikingOSX

And working swift code to return the plain body text of a Pages document to a variable using NSAppleScript from Foundation:


#!/usr/bin/swift

import Foundation


var AS: String = """
use scripting additions

tell application "Pages"
activate
open file (choose file of type {"Pages"})
tell front document to set btext to its body text
close front document
end tell
return btext as text
tell application "Pages" to if it is running then quit
"""

var errorDict: NSDictionary?
let ascript = NSAppleScript(source:AS)!

guard let output: String = ascript.executeAndReturnError(&errorDict).stringValue else {
    print("script failed to execute")
    exit(EXIT_FAILURE)
}

print(output)

Tested on macOS 11.6.8 with Swift version 5.5.2.

Sep 7, 2022 8:02 AM in response to feribavale

No. Pages internal document content is encrypted and the format is undocumented by Apple. There is no means to directly access it to obtain attributed strings without first exporting the content to RTF, Word, or PDF. In the latter case, one can get the plain text of the entire document, or the attributed text of a specified PDF page using PDFKit (PDFDocument/PDFPage).


You might be able to use the Scripting Bridge to open a Pages document and save that content as plain text (but not attributable strings) into a variable for further processing.


Or even use NSAppleScript from Foundation to run an AppleScript HERE document to return the text of the Pages document.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

NSAttributedString.DocumentType for .pages documents

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