I've set-up a document that contains identical structures, including a text box labeled "pageNumber" to hold a variable based on the page number, an empty rectangle to receive an illustrator file, and a text box filled with placeholder text.
Eventually, I'll be using data-merge to create a much longer document, comprised of identically structured pages, but containing personalized data.
(I created a zip file containing these elements, in case it would be helpful to see what I'm testing)( http://arthousemedia.com/files/PageNumbers.zip )
The jsx I've created works to an extent. When I run it, there are a couple alerts that show I've created the right variables) But instead of placing pageNumber-p1.ai on page one and pageNumber-p2 on the second page, whichever page I'm "focused" upon gets its graphic placed twice on page 1. Apparently, I'm not succeeding in looping through pages. Not sure.
Any advice you have would be helpful. Thanks.
var doc = app.activeDocument,
pagesLength = doc.pages.length;
for (var i = 0; i < pagesLength; i++) {
var myLabel = "pageNumber",
myPage = app.properties.activeWindow && app.activeWindow.activePage,
myTextFrames = myPage.textFrames.everyItem().getElements(myLabel).slice(0),
l = myTextFrames.length,
myVariable
alert(myVariable);
while (l--) {
if (myTextFrames[l].label != myLabel) continue;
myVariable = myTextFrames[l].contents;
break;
}
var thisState = "~/Documents/PageNumbers/pageNumber-" + myVariable + ".ai";
alert(thisState);
var rect = doc.pages[i].rectangles[0];
try {
rect.place(File(thisState));
rect.fit (FitOptions.CONTENT_TO_FRAME);
rect.fit (FitOptions.PROPORTIONALLY);
rect.fit (FitOptions.CENTER_CONTENT);
}
catch(e){
alert(e);
};
}
Related
I have a Google spreadsheet and a Google document. The document is a report which gets filled by the spreadsheet. The spreadsheet is also defining what comes into the report. Therefore I have a script, which gathers a bunch of placeholders depending on values in the the document.
After all the placeholders have been inserted in the document (there are a couple of pages before that) it looks kind of like this:
{{header1.1}}
{{text1.1}}//this is already a couple lines of text
{{table1.1}}
{{table.dir}}
{{blob1.1}}
{{blob.dir}}
I already have a script, which inserts all the text parts and I have set up a script, which should be capable of writing the tables at the correct position. So far I can replace the {{header1.1}}, but if I try to define it as a heading it works, but everything after the header1.1 is also a heading
I've been at this problem for quite a while and didn't get and its always one step forward one step back. Also this is my first question after a couple of years just reading on stackoverflow. I'd appreciate if someone could help.
function myUeberschriftenboi() {
doc = DocumentApp.openById('someID');
console.log(doc.getName());
var body = doc.getBody();
//formate
const plain3style = {};
plain3style[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.HEADING3;
var lvl2array = [ "{{header1.1}}" , "{{header1.2}}" ];
var fill2array = [ "Energy" , "Energyflow" ]
var lvl2count = 1;
for( var j = 0 ; j < lvl2array.length ; j++)
{
var seek = body.findText(lvl2array[j]);
if( seek != null)
{
body.replaceText(lvl2array[j] , "1.1."+lvl2count+" "+fill2array[j]+"\n");
var seek2 = body.findText("1."+lvl2count+" "+fill2array[j]);
seek2.getElement().getParent().getChild().setAttributes(plain3style);
lvl2count++;
}}}
Background
I have a Google Apps Script that we use to parse the footnote content, wrapped in double parenthesis, in place of the footnote number superscript. The intended result should be:
Before Script
This is my footie index.1 1This is my
footie content with a link and emphasis.
After Script
This is my footie index. (( This is my footie content with a
link and emphasis.)
Problem
Everything works fine, except when I parse the footnotes in double parenthesis, they are losing all the links and formatting:
This is my footie index. (( This is my footie content with a
link and emphasis.)
If anyone can assist me with fixing the code below I would really appreciate the help :)
SOLUTION:
function convertFootNotes () {
var doc = DocumentApp.getActiveDocument()
var copy = generateCopy(doc) // make a copy to avoid damaging the original
var openCopy = doc; //DocumentApp.openById(copy.getId()) // you have to use the App API to copy, but the Doc API to manipulate
performConversion(openCopy); // perform formatting on the copy
}
function performConversion (docu) {
var footnotes = docu.getFootnotes(); // get the footnotes
footnotes.forEach(function (note) {
// Traverse the child elements to get to the `Text` object
// and make a deep copy
var paragraph = note.getParent(); // get the paragraph
var noteIndex = paragraph.getChildIndex(note); // get the footnote's "child index"
insertFootnote(note.getFootnoteContents(),true, paragraph, noteIndex);
note.removeFromParent();
})
}
function insertFootnote(note, recurse, paragraph, noteIndex){
var numC = note.getNumChildren(); //find the # of children
paragraph.insertText(noteIndex," ((");
noteIndex++;
for (var i=0; i<numC; i++){
var C = note.getChild(i).getChild(0).copy();
if (i==0){
var temp = C.getText();
var char1 = temp[0];
var char2 = temp[1];
if (C.getText()[0]==" "){
C = C.deleteText(0,0);
}
}
if (i>0){
paragraph.insertText(noteIndex,"\n");
noteIndex++;
}
paragraph.insertText(noteIndex,C);
noteIndex++;
} //end of looping through children
paragraph.insertText(noteIndex,"))");
}
function generateCopy (doc) {
var name = doc.getName() + ' #PARSED_COPY' // rename copy for easy visibility in Drive
var id = doc.getId()
return DriveApp.getFileById(id).makeCopy(name)
}
Were there any changes to the code other than the added )) to make it not work? Removing the (( & )) still did not have the formatting applied when testing it; getText() returns the element contents as a String, not a rich text object/element which contains the formatting info.
To get to the Text object:
getFootnoteContents().getChild(0) returns the FootnoteSection Paragraph
getChild(0).getChild(0) returns the Text object of that paragraph
copy() returns a detached deep copy of the text object to work with
Note: If there are other child elements in the FootnoteSection or in it's Paragraph child, you'll want to add some kind of type/index checking to get the correct one. However, with basic footnotes - as the above example - this is the correct path.
function performConversion (docu) {
var footnotes = docu.getFootnotes() // get the footnotes
var noteText = footnotes.map(function (note) {
// Traverse the child elements to get to the `Text` object
// and make a deep copy
var note_text_obj = note.getFootnoteContents().getChild(0).getChild(0).copy();
// Add the `((` & `))` to the start and end of the text object
note_text_obj.insertText(0, " ((");
note_text_obj.appendText(")) ");
return note_text_obj // reformat text with parens and save in array
})
...
}
I have a very long plain text file in my google drive which I need to parse through and select pieces of information through a script. I have successfully pulled out the text and put it into a string variable, but it is so long that the variable only contains about 1/6 of the full document.
This is the code I am using:
function f09ToSpreadsheet() {
var allFilesInFolder,cntFiles,docContent,fileNameToGet,fldr,
thisFile,whatFldrIdToUse;//Declare all variable at once
whatFldrIdToUse = '0B2O23fJ4nQLONlA4RlhuLWp0Y0k';
fileNameToGet = 'Copy of RS_Tionesta_1N.txt';//Assign the name of the file to get to a variable
//Get a reference to the folder
fldr = DriveApp.getFolderById(whatFldrIdToUse);
//Get all files by that name. Put return into a variable
//allFilesInFolder = fldr.getFilesByName(fileNameToGet);
allFilesInFolder = fldr.getFiles();
//Logger.log('allFilesInFolder: ' + allFilesInFolder);
if (allFilesInFolder.hasNext() === false) {
//If no file is found, the user gave a non-existent file name
return false;
};
cntFiles = 0;
//Even if it's only one file, must iterate a while loop in order to access the file.
//Google drive will allow multiple files of the same name.
while (allFilesInFolder.hasNext()) {
Logger.log("yup")
var thisFile = allFilesInFolder.next();
//KEY TO READING TEXT FROM .F05 & .F09 ->
docContent = thisFile.getAs("application/octet-stream");
var string = docContent.getDataAsString();
Logger.log('docContent : ' + string );
};
}
The "string" object, when printed to the log, only contains the first part of the text doc.
Is there any way to, say, split up the document into small pieces and store each part in a variable?
I'm afraid I've not tested this so apologies if it doesn't work straight away but could you get your document paragraph by paragraph and append the text like that?
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paras = body.getParagraphs();
paras.forEach(function( para ){
var text = para.getText();
populateSheet( text );
});
I have an element displaying an image on an HTML page. This element's source is one of many different images in a JavaScript array.
I already have a script for looping through the images, creating a slideshow effect, but now I want to manually flick through the images with buttons.
This is my code so far, but I get no response when clicking the button.
function nextup()
{
imgs = [];
imgs[0] = "/snakelane/assets/images/thumb/_1.jpg"; imgs[10] = "/snakelane/assets/images/thumb/_19.jpg";
imgs[1] = "/snakelane/assets/images/thumb/_2.jpg"; imgs[11] = "/snakelane/assets/images/thumb/_20.jpg";
imgs[2] = "/snakelane/assets/images/thumb/_3.jpg"; imgs[12] = "/snakelane/assets/images/thumb/_21.jpg";
imgs[3] = "/snakelane/assets/images/thumb/_4.jpg"; imgs[13] = "/snakelane/assets/images/thumb/_22.jpg";
imgs[4] = "/snakelane/assets/images/thumb/_5.jpg"; imgs[14] = "/snakelane/assets/images/thumb/_23.jpg";
imgs[5] = "/snakelane/assets/images/thumb/_6.jpg"; imgs[15] = "/snakelane/assets/images/thumb/_24.jpg";
imgs[6] = "/snakelane/assets/images/thumb/_7.jpg"; imgs[16] = "/snakelane/assets/images/thumb/_25.jpg";
imgs[7] = "/snakelane/assets/images/thumb/_8.jpg"; imgs[17] = "/snakelane/assets/images/thumb/_26.jpg";
imgs[8] = "/snakelane/assets/images/thumb/_9.jpg"; imgs[18] = "/snakelane/assets/images/thumb/_27.jpg";
imgs[9] = "/snakelane/assets/images/thumb/_32.jpg"; imgs[19] = "/snakelane/assets/images/thumb/_28.jpg";
var pic = document.getElementById("picbox");
for(i =0; i < imgs.length; i++) {
var current = indexOf(pic.src);
var next = Math.round(current + 1);
pic.src = imgs[next];
}
}
Can anyone tell me what's wrong with my code or suggest a better way?
Multiple problems in the approach you had used. Have a look at the modified function below. Let me know if you need explanation with anything.
The following code will use an array containing image URLs and later assign in a sequential manner to an img tag on click. Enjoy!
Here you can try to see the output.
function nextup(){
//Initialized img array with 10 images, you can do it any way you want to.
var imgs = [];
for(i=0;i<10;i++){
imgs[i] = "http://lorempixel.com/output/cats-q-c-100-100-"+(i+1)+".jpg";
}
//Fetch the pic DOM element by ID
var pic = document.getElementById("picbox");
//Know what is position of currently assigned image in array.
var current = imgs.indexOf(pic.src);
var next = 0;
//Handle case if no image is present, the initial case.
if(current!=-1){
next = (current + 1)%(imgs.length);
}
//Assign the next src
pic.src = imgs[next];
}
//Scoped outside to call the function first time on load.
nextup();
I found the following problems in your code:
You tried to use indexOf without specifying the array in which the search has to be performed. Imagine s school principal asking someone to go find if John is present in the classroom without specifying a specific classroom.
For iterating through array you used a next variable which could have been a good idea if you needed an endless loop. But here since we are limited to 10 or 20 images we need to make sure that if the currently selected image is the last one, we find that next goes to 21 (assuming a total of 20 images.) and this would try to access a variable out of bounds.
Hence I've used the mod operator %.
For reference in JavaScript, 5%10 would return 5 , 15%10 would return 5 and so on. Read more about the mod operator HERE.
I was looking about indesign scripts and I have not found anything about this topic, which I think is important. So here it is my question:
How to find a text frame in Indesign CS6 with javascript?
I can query by text-frames containing a particular paragraph style?
I can set some kind of name on my text-frame (which is in the master page) to get it in javascript?
Ok, after some research I've found that you can set a label to an object by opening the "Script label", selecting the object you want and the write the label-name into the "Script label" panel. You don't have to click ok or nothing, it will automatically save the label for that object.
After you do that, you can check the ".label" property on objects and when you will find the object with that label, you found it. Multiple objects can have the same label.
Below is an example with a helper function "selectWhere":
var document = app.documents.item(0); // active document
var allTextFrames = toArray(document.textFrames);
var textFrames = selectWhere("chapterLetter", "label", allTextFrames);
function selectWhere(value, key, array){
var i = array.length; var t; var filtered = [];
while(i--){
t = array[i];
if(t && t[key] == value){
filtered.push(t);
}
}
return filtered;
}
function toArray(objects){
var i = objects.length; var array = [];
while(i--){
array.push(objects[i]);
}
return array;
}
1)The answer to your first question is:-
solved in this thread
2)Now you get array of textframes.So you can query to get the paragraph style on the text frames
var paraStyle1 = app.activeDocument.paragraphStyles.itemByName("styleA");
var paraStyle2 = app.activeDocument.paragraphStyles.itemByName("styleB");
if (paraStyle1.isValid && paraStyle2.isValid)
3) Through paraStyle1.name you can get the name of the style.See parastyle1 is the paragraph style object so get the style object and find by this property.