inDesign JSX scripted add of heading and content into textFrame - adobe-indesign

I'm attempting to use inDesign JSX scripts to insert the following data into a document:
data = [{heading:"Heading 1", content: ["Some content"]},
{heading:"Heading 2", content: ["Some other content with", "Multiple paragraphs"]}]
The data has to be placed into a single TextFrame, but have different styling on the heading and content.
The only way I can see to add the text is in one go via the textFrame.contents variable:
allContent = "";
headingParagraphs = []; // keep track of which paragraphs are headings
paragraph = 0;
for (var i = 0; i < data.length; i++) {
allContent += data.heading + "\r"; // Use a newline to split the paragraph
headingParagraphs.push(paragraph);
paragraph++;
for (var j = 0; j < data.content.length; j++) {
allContent += data.content[j] + "\r"; // Use a newline to split the paragraph
paragraph++;
}
}
textFrame.contents = allContent; // all data is in, but all text is styled the same
Then once the data is in, I iterate the paragraphs and add some style to the headings:
for (var i = 0; i < textFrame.paragraphs.count(); i++) {
if (headingParagraphs.indexOf(i) != -1) { // this is a heading paragraph
textFrame.paragraphs[i].pointSize = 20;
}
}
This works fine for small data sets that fit on one page, but once the contents gets bigger than the frame, paragraphs only returns visible paragraphs. And if I follow on to a new textFrame, paragraphs get split and the headingParagraphs[] array no longer lines up.
Ideally I'd like to append to the contents and set styles before I append the next content - but the API docs aren't very clear on how you might do that (if at all)
// Pseudo code:
for all sections:
append the heading to the frame, split to next page if needed
style all the *new* paragraphs as headings
for all section contents
append the content to the frame, split to next page if needed
style any *new* paragraphs as normal content
Is there a way to achieve this using either an append function or some other way to assign headings to the right place after content has been added? Perhaps special characters in the content to define style?

Your longer text gets messed up because currently you are working inside a single text frame. As soon as the text runs out of this one frame, you can't refer to them as this frame's "owned" paragraphs anymore. Use parentStory instead, as it points to the whole story, inside one text frame or spanning more than one. It also keeps on working if the text gets overset.
So if you have a starting frame called textFrame, set a new variable story to textFrame.parentStory and use that to add text.
As for adding text to this frame(/story): indeed, there is no fast way to add formatted text. Setting contents only works for long swathes with the same formatting. One way I've used is to write INX formatted text to a temporary file and importing that. It's slow for short fragments, but larger stories (up to several hundreds of pages) can be created very efficiently in Javascript itself, and then importing it into ID is .. well, it aint fast but faster than trying to do it "manually".
The other way is to add contents one paragraph at a time. The trick is to set formatting and add your text to story.insertionPoints[-1]. This, in a particularly handy notation, refers to the very last text insertion point of the story. You can think of an insertion point as "the text cursor"; you can 'apply' formatting to it, and any text added will then have this formatting as well.
Your code snippet reworked to add one data item at a time:
for (var i = 0; i < data.length; i++)
{
story.insertionPoints[-1].pointSize = 20;
story.insertionPoints[-1].contents = data[i].heading + "\r"; // Use a newline to split the paragraph
story.insertionPoints[-1].pointSize = 10;
for (var j = 0; j < data[i].content.length; j++)
{
story.insertionPoints[-1].contents = data[i].content[j] + "\r"; // Use a newline to split the paragraph
}
}
One thing to note is that you cannot temporarily override the pointSize here. If you set it to your larger size, you must also set it back to the original size again (the '10' in my snippet).
Can I convince you to look in to using paragraph styles? With paragraph styles, you'd have something like
hdrStyle = app.activeDocument.paragraphStyles.item("Header");
textStyle = app.activeDocument.paragraphStyles.item("Text");
for (var i = 0; i < data.length; i++)
{
story.insertionPoints[-1].contents = data[i].heading + "\r"; // Use a newline to split the paragraph
story.insertionPoints[-2].appliedParagraphStyle = hdrStyle;
for (var j = 0; j < data[i].content.length; j++)
{
story.insertionPoints[-1].contents = data[i].content[j] + "\r"; // Use a newline to split the paragraph
story.insertionPoints[-2].appliedParagraphStyle = textStyle;
}
}
Note that it's worth here to invert inserting contents and applying formatting. This is so any previous 'temporary' formatting gets cleared; applying a paragraph style this way overrides any and all local overrides. As you have to apply the style to the previous paragraph (the one before the hard return you just inserted), you would use insertionPoints[-2] here.
The advantages of using styles over local formatting are countless. You can apply all formatting you want with a single command, safely remove all local overridden formatting, and change any part of the formatting globally if you are not satisfied with it, rather than having to re-run your script with slightly different settings.

Related

Indesign Script: Looping ALL paragraphs (including in overset)

Looking for a selector of ALL paragraphs in the selected TextFrame, including the "not visible ones" in the overset. Script is already working and looping through the visible paragraphs:
[...]
if(app.selection[0].constructor.name=="TextFrame") {
var myParagraphs = app.selection[0].paragraphs; // only visible ones?!
var myArray = myParagraphs.everyItem().contents;
for (var i=0; i<myArray.length; i++) {
// do some fancy styling - WORKING
myParagraphs[i].appliedParagraphStyle = app.activeDocument.paragraphStyles.item('Format XYZ');
}
}
myArray.length changes when I set another hight for the TextFrame. But how can I work with ALL paragraphs? Already tested .anyItem() with the same result :(
Well, the paragraphs in the overset are not paragraphs of the text frame, so it makes sense that they are skipped in your script. To access all the paragraphs of the text frames + those that are in the overset part, you will need to access all paragraphs of the parent story (a story is the text entity that describes all the text within linked text frames and the overset text) of the text frame.
You can do so like this:
if(app.selection[0].constructor.name === "TextFrame") {
var myParagraphs = app.selection[0].parentStory.paragraphs;
for (var i = 0; i < myParagraphs.length; i++) {
myParagraphs[i].appliedParagraphStyle = app.activeDocument.paragraphStyles.item("Format XYZ");
}
}
Be aware though that this will handle all paragraphs in all text frames that are linked to your text frame in case there are any of those.
Also, since it looks like you need to apply the paragraph style on each paragraph of the entire story, you might as well apply the paragraph style to the entire story directly instead of looping over the paragraphs:
app.selection[0].parentStory.appliedParagraphStyle = app.activeDocument.paragraphStyles.item("Format XYZ");

Photoshop scripting - Close all except first document

I'm trying to make a photoshop script that closes all documents without saving except for the first document. The first document will be a psd/psdc, the rest will be images
Currently I have the below code, this closes all documents
while (app.documents.length > 0) {
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
I've tried modifying it the same way I've done with a previous script, but it closes random documents, and not even all of them, it can leave 5-6 documents open
for (var i = 1; i < app.documents.length; i++) {
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
}
Can anyone point me in the right direction
Just use the inverted loop (so the docs are closed from the last to the first) and address them by the reference from the documents array, not by active document:
for (var i = documents.length - 1; i >= 1; i--) {
documents[i].close(SaveOptions.DONOTSAVECHANGES)
}

MigraDoc Formatting

I am completely new to PDF creation including MigraDoc. I have gotten this far, which is really close to what I want for now. My question is that the text string (myMessage) that I pass to the "bodyParagraph" is up to 100 lines long, which causes three pages to be created, which is good. However the first page's Top margin is slightly greater than the second and third pages. I have no idea of why...
Basically, I am trying to create every page the same. Same header, footer and the body to take the same space regardless of the number of lines in the "bodyParagraph" content. If I have taken the completely wrong approach I would be open to suggestions.
Also, if there is a good tutorial to point me to that would be great. I can't really find anything but samples. I have learned everything from the samples, but sections, paragraph, etc is all new to me and I would like to get a better understanding of what I've done.
public static Document CreateWorkOrderPDF2(Document document, string filename, string WorkOrderHeader, string myMessage)
{
Section section = document.AddSection();
section.PageSetup.PageFormat = PageFormat.Letter;
section.PageSetup.StartingNumber = 1;
section.PageSetup.LeftMargin = 40;
//Sets the height of the top margin
section.PageSetup.TopMargin = 100;
section.PageSetup.RightMargin = 40;
section.PageSetup.BottomMargin = 40;
//MARGIN
HeaderFooter header = section.Headers.Primary;
header.Format.Font.Size = 16;
header.Format.Font.Color = Colors.DarkBlue;
MigraDoc.DocumentObjectModel.Shapes.Image headerImage = header.AddImage("../../Fonts/castorgate.regular.png");
headerImage.Width = "2cm";
Paragraph headerParagraph = section.AddParagraph();
headerParagraph = header.AddParagraph(WorkOrderHeader);
//BODY PARAGRAPH
Paragraph bodyParagraph = section.AddParagraph();
bodyParagraph = section.AddParagraph(myMessage);
bodyParagraph.Format.Font.Size = 10;
bodyParagraph.Format.Font.Color = Colors.DarkRed;
//paragraph.Format.Distancne = "3cm";
Paragraph renderDate = section.AddParagraph();
renderDate = section.AddParagraph("Work Order Generated: ");
renderDate.AddDateField();
return document;
}
The line Paragraph bodyParagraph = section.AddParagraph(); adds an empty paragraph. I assume that is the extra space on the first page.
Same issue with renderDate in the following code block.
Just remove the calls section.AddParagraph() to remove the empty paragraphs if you don't want them.
MigraDoc is much like Word and understanding sections, paragraphs, &c. in Word will also help you with MigraDoc. That knowledge along with the samples and IntelliSense should get you going.
You can use MigraDoc to create an RTF file, open the RTF in Word, and click the pilcrow to show formatting characters in Word.

kendo ui editor how to modify user selection with range object

Kendo UI 2015.2.805 Kendo UI Editor for Jacascript
I want to extend the kendo ui editor by adding a custom tool that will convert a user selected block that spans two or more paragraphs into block of single spaced text. This can be done by locating all interior p tags and converting them into br tags, taking care not to change the first or last tag.
My problem is working with the range object.
Getting the range is easy:
var range = editor.getRange();
The range object has a start and end container, and a start and end offset (within that container). I can access the text (without markup)
console.log(range.toString());
Oddly, other examples I have seen, including working examples, show that
console.log(range);
will dump the text, however that does not work in my project, I just get the word 'Range', which is the type of the object. This concerns me.
However, all I really need however is a start and end offset in the editor's markup (editor.value()) then I can locate and change the p's to br's.
I've read the telerik documentation and the referenced quirksmode site's explanation of html ranges, and while informative nothing shows how to locate the range withing the text (which seems pretty basic to me).
I suspect I'm overlooking something simple.
Given a range object how can I locate the start and end offset within the editor's content?
EDIT: After additional research it appears much more complex than I anticipated. It seems I must deal with the range and/or selection objects rather than directly with the editor content. Smarter minds than I came up with the range object for reasons I cannot fathom.
Here is what I have so far:
var range = letterEditor.editor.getRange();
var divSelection;
divSelection = range.cloneRange();
//cloning may be needless extra work...
//here manipulate the divSelection to how I want it.
//divSeletion is a range, not sure how to manipulate it
var sel = letterEditor.editor.getSelection()
sel.removeAllRanges();
sel.addRange(divSelection);
EDIT 2:
Based on Tim Down's Solution I came up with this simple test:
var html;
var sel = letterEditor.editor.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
html = html.replace("</p><p>", "<br/>")
var range = letterEditor.editor.getRange();
range.deleteContents();
var div = document.createElement("div");
div.innerHTML = html;
var frag = document.createDocumentFragment(), child;
while ((child = div.firstChild)) {
frag.appendChild(child);
}
range.insertNode(frag);
The first part, getting the html selection works fine, the second part also works however the editor inserts tags around all lines so the result is incorrect; extra lines including fragments of the selection.
The editor supports a view html popup which shows the editor content as html and it allows for editing the html. If I change the targeted p tags to br's I get the desired result. (The editor does support br as a default line feed vs p, but I want p's most of the time). That I can edit the html with the html viewer tool lets me know this is possible, I just need identify the selection start and end in the editor content, then a simple textual replacement via regex on the editor value would do the trick.
Edit 3:
Poking around kendo.all.max.js I discovered that pressing shift+enter creates a br instead of a p tag for the line feed. I was going to extend it to do just that as a workaround for the single-space tool. I would still like a solution to this if anyone knows, but for now I will instruct users to shift-enter for single spaced blocks of text.
This will accomplish it. Uses Tim Down's code to get html. RegEx could probably be made more efficient. 'Trick' is using split = false in insertHtml.
var sel = letterEditor.editor.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
var block = container.innerHTML;
var rgx = new RegExp(/<br class="k-br">/gi);
block = block.replace(rgx, "");
rgx = new RegExp(/<\/p><p>/gi);
block = block.replace(rgx, "<br/>");
rgx = new RegExp(/<\/p>|<p>/gi);
block = block.replace(rgx, "");
letterEditor.editor.exec("insertHtml", { html: block, split: false });
}

Programatically updating underlying data in Slickgrid

I have 6 textboxes at the top of the screen that update an entire column(one textbox per column) based on any changes. I was selecting the columns based on their class (.l#). Here is the code (issues to follow):
function UpdateField() {
var ctrl = this;
var id = parseInt(ctrl.id.replace("item", ""), 10) - 1;
var bound = [".l1", ".l7", ".l8", ".l9"];
var fields = $(bound[id]);
for (var i = 0; i < fields.length; i++)
{
fields[i].innerHTML = $(ctrl).val();
}
};
which is bound to the keyup event for the text areas. Issues are:
1) initially fields.length was -1 as I didn't want to put data in the "add new
row" section at the bottom. However, when running it, I noticed the
final "real" record wasn't being populated. Also, when stepping through, I
noticed that the "new row" field was before the "last row" field.
2) when doing it this way, it is purely superficial: if I double click the field,
the real data hasn't been changed.
so in the grand scheme of things, I know that I was doing it wrong. I'm assuming it involves updating the data and then forcing a render, but I'm not certain.
Figured out how to do it. Modified the original code this way:
function UpdateField() {
var ctrl = this;
var id = parseInt(ctrl.id.replace("item", ""), 10) - 1;
var bound = ['title1', 'title2', 'title3', 'title4'];
var field = bound[id];
for (var i = 0; i < dataView.getLength(); i++)
{
var item = dataView.getItem(i);
item[field] = $(ctrl).val();
dataView.updateItem(i, item);
}
grid.invalidate();
};
I have 6 textboxes (item1-item6) that "bind" to fields in the sense that if I change data in a textbox, it updates all of the rows and any new rows added also have this data.
Parts where the two issues can be explained this way:
1) to work around that, though still it would be a presentational fix and not a real updating of the underlying data, one could force it to ignore if it had the active class attached. Extra work, and not in the "real" direction one is going for (masking the field).
2) It was pretty obvious with the original implementation (though it was all I could figure out via Chrome Dev Tools that I could modify at the time) that it was merely updating a div's content and not actually interacting with the data underneath. Would look nice, and perhaps one could just pull data from the item1-item6 boxes in place of the column if it is submitted, but if someone attempts to modify the cell, they'll be looking at the real data again.

Resources