CHAPTER 6: Text and Type Understanding Text Objects 85
var myDocumentA = app.documents.add();
var myPageA = myDocumentA.pages.item(0);
var myString = "Example text.\r";
var myTextFrameA = myPageA.textFrames.add({geometricBounds:myGetBounds(myDocumentA,
myPageA), contents:myString});
var myDocumentB = app.documents.add();
var myPageB = myDocumentB.pages.item(0);
var myTextFrameB = myPageB.textFrames.add({geometricBounds:myGetBounds(myDocumentB,
myPageB)});
//Make document A the active document.
app.activeDocument = myDocumentA;
//Select the text.
app.select(myTextFrameA.parentStory.texts.item(0));
app.copy();
//Make document B the active document.
app.activeDocument = myDocumentB;
//Select the insertion point at which you want to paste the text.
app.select(myTextFrameB.parentStory.insertionPoints.item(0));
app.paste();
One way to copy unformatted text from one text object to another is to get the contents property of a
text object, then use that string to set the
contents property of another text object. The following script
shows how to do this (for the complete script, see CopyUnformattedText):
var myDocument = app.documents.item(0);
var myPage = myDocument.pages.item(0);
//Create a text frame on the active page.
var myTextFrameA = myPage.textFrames.add({geometricBounds:[72, 72, 144, 288]});
myTextFrameA.contents = "This is a formatted string.";
myTextFrameA.parentStory.texts.item(0).fontStyle = "Bold";
//Create another text frame on the active page.
var myTextFrameB = myPage.textFrames.add({geometricBounds:[228, 72, 300, 288]});
myTextFrameB.contents = "This is the destination text frame. Text pasted here will
retain its formatting.";
myTextFrameB.parentStory.texts.item(0).fontStyle = "Italic";
//Copy from one frame to another using a simple copy.
app.select(myTextFrameA.texts.item(0));
app.copy();
app.select(myTextFrameB.parentStory.insertionPoints.item(-1));
app.paste();
//Create another text frame on the active page.
var myTextFrameC = myPage.textFrames.add({geometricBounds:[312, 72, 444, 288]});
myTextFrameC.contents = "Text copied here will take on the formatting of the existing
text.";
myTextFrameC.parentStory.texts.item(0).fontStyle = "Italic";
//Copy the unformatted string from text frame A to the end of text frame C (note
//that this doesn't really copy the text; it replicates the text string from one
//text frame in another text frame):
myTextFrameC.parentStory.insertionPoints.item(-1).contents =
myTextFrameA.parentStory.texts.item(0).contents;
Text objects and iteration
When your script moves, deletes, or adds text while iterating through a series of text objects, you can
easily end up with invalid text references. The following script demonstrates this problem. (We omitted the
myGetBounds function from this listing; you can find it in “Creating a text frame” on page 71,” o r s e e th e
TextIterationWrong tutorial script.)