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.
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.
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.
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.
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.
Absent reverse-engineering the format…
Launch Pages, export to text, and parse that?
Log feedback with Apple about the lack of a document type, too.
NSAttributedString.DocumentType for .pages documents