get current text frame width in indesign script - javascript

the below code gets the first text frame width in my doc. How can I get the active text frame Width in Indesign script? The image shows my problem.
function freamWidth() {
var frameRef = app.documents[0].textFrames[0];
var gBounds = frameRef.geometricBounds;
var y0 = gBounds[0];
var x0 = gBounds[1];
var y1 = gBounds[2];
var x1 = gBounds[3];
//do calculations
var frameWid = x1 - x0;
// var frameHgt = y1 - y0;
return frameWid;
}

This is more a question of how to retreive the parent text frame of a selection. You can usually do this via the parentTextFrames property of a text selection. You could optionally also include a check if the text frame itself is selected instead of some text within the text frame. So the following code should work for your scenario:
var tf;
var sel = app.selection[0];
if(sel.hasOwnProperty('baseline')) {
tf = sel.parentTextFrames[0];
} else if (sel instanceof TextFrame) {
tf = sel;
}
var tfWidth = tf.geometricBounds[3] - tf.geometricBounds[1];
alert("The text frame width is " + tfWidth);

Related

adobe illustrator script- printing custom size paper

we have at work an HP plotter and I'm trying to make a script that will print the job with the right paper size.
the width of the paper is 900mm and the height can be set as we want it to be but we have to do it manualy for every job.
I have written a script that prints the job on the HP plotter but I can't find a way to chek the artboard size to detrmain the printing orientation and print it at the size of the artboard + some space for the cutting.
here is what I have now:
var Doc = app.activeDocument;
var abActive = Doc.artboards[Doc.artboards.getActiveArtboardIndex()];
var bounds = abActive.artboardRect;
var left = bounds[0];
var top = bounds[1];
var right = bounds[2];
var bottom = bounds[3];
var Pheight = right - left;
//Lexmark 1
//HP 2
var Lexmark = app.printerList[1].name;
var HP = app.printerList[2].name;
var PaperA3 = printerList[2].printerInfo.paperSizes[1];
var printJobOptions = new PrintJobOptions();
var options = new PrintOptions();
var coordinateOptions = new PrintCoordinateOptions();
//coordinateOptions.fitToPage = true;
coordinateOptions.orientation = PrintOrientation.AUTOROTATE ;
options.coordinateOptions = coordinateOptions;
var printPaperOpts = new PrintPaperOptions();
printPaperOpts.name = PaperA3;
printPaperOpts.height = 600;
options.paperOptions = printPaperOpts;
options.printerName = HP;
options.printPreset = "HP";
Doc.print(options);
Not sure if understand the problem a whole. Probably it's need to clarify some details.
For example here is the snippet to get a size of the active artboard and its orientation:
var doc = app.activeDocument;
var artboard = doc.artboards[doc.artboards.getActiveArtboardIndex()];
const mm = 2.834645669;
var bounds = artboard.artboardRect;
var width = Math.round((bounds[2] - bounds[0]) / mm);
var height = Math.round((bounds[1] - bounds[3]) / mm);
var landscape = (width > height) ? true : false;
alert('height = ' + height + ' mm\nwidth = ' + width + ' mm\nlandscape: ' + landscape);
This way you can get the numbers. The code is quite simple and obvious.
Is it enough? Let me know if you need help.
I made a script that will set a preset depending on the artboard size but it's not working and not because of my script. For some reason illustrator sets the paper size to A4 even when I set a diffrent size in the preset.
From reading online it has to be a problem with the printer drivers.

InDesign script, resize images after word import

Sometimes we have big images in word file and after importing this word file inside InDesign, the image goes inside the overflow text and the text flow stops at this point.
We couldn't resize these images or can't get hold of this image for applying any scripting logic.
Basically, I will search for figure parastyle, then check for rectangles inside the para, and do resize logic. Sample jsx code here:
app.findTextPreferences.appliedParagraphStyle= 'figure';
var founds = app.findText();
// find 92% text width area
var pageWidth = this.props.textAreaWidth * 92 /100;
for(var i=0, len=founds.length; i<len; i++){
// find the rectangles inside the para
var rect = founds[i].rectangles;
if(rect.length == 0) continue;
var vb = rect[0].visibleBounds;
var imgWidth = vb[3] - vb[1];
// image resize logic
if(imgWidth > pageWidth){
vb[3] = pageWidth;
rect[0].visibleBounds = vb;
rect[0].fit(FitOptions.PROPORTIONALLY);
rect[0].fit(FitOptions.FRAME_TO_CONTENT);
}
How to apply some logic to the images which are in the overflow text? how to resize the image which is in overflow text?
We can just import the below word file into any InDesign template
Sample word file
You could iterate through all the graphics and resize the big ones.
var images = app.activeDocument.allGraphics;
var max = {};
max.w = 100; // max width
max.h = 100; // max height
for (var i=0; i<images.length; i++) {
var gb = images[i].geometricBounds;
var size = {};
size.w = -gb[1] + gb[3];
size.h = -gb[0] + gb[2];
if (size.w > max.w || size.h > max.h) {
var scale = (size.w > size.h) ? max.w/size.w : max.h/size.h;
images[i].horizontalScale *= scale;
images[i].verticalScale *= scale;
images[i].parent.fit(FitOptions.FRAME_TO_CONTENT);
}
}

move fake cursor to position taken from clicked character

I have a div with text using monospace font, and I need to display a cursor in the place where I click, I have functions that display text with cursor:
function draw() {
var text = textarea.val();
var html;
if (pos == text.length) {
html = encode(text) + '<span class="cursor"> </span>';
} else {
html = encode(text.slice(0, pos)) + '<span class="cursor">' +
encode(text[pos+1]) + '</span>' + encode(text.slice(pos+1));
}
output.html(html);
}
and function that get cursor position based on x/y coordinate of the mouse event:
function get_char_pos(div, text, event) {
var num_chars = get_num_chars(div);
var cursor = div.find('.cursor');
var rect = cursor[0].getBoundingClientRect();
var width = rect.width;
var height = rect.height;
var offset = div.offset();
var col = Math.floor((event.pageX-offset.left)/width);
var row = Math.floor((event.pageY-offset.top)/height);
var try_pos = col + (row > 0 ? num_chars * row : 0);
return try_pos;
}
It almost working except when text contain tabs (tabs are replaced by 4 spaces by encode function). I've try to fix tabs using this:
var before = text.slice(0, try_pos);
var tabs = before.match(/\t/g);
var fix = tabs ? tabs * 3 : 0;
try_pos += fix;
return try_pos > text.length ? text.lenght : try_pos;
but this don't work. It should also work for a case when I click on space that may be part of tab. How to fix it when text contain tabs?
Here is codepen demo
The tab character is the issue. It's a single character which means the string it's not calculated as four characters in the text.slice. If you replace \t with four spaces your issue is solved.

JavaScript mouseover/mousemove cusor postion without clicking in input text box

I'm attempting to combine a JavaScript mechanism for auto placing the users cursor inside of an input box through the mouseover and mousemove listeners.
I have an almost perfect working example here: http://codepen.io/anon/pen/doxNLm?editors=101
var current_element = document.getElementById("hover");
current_element.onmousemove = function showCoords(evt) {
var form = document.forms.form_coords;
var parent_id = this.id;
form.parentId.value = parent_id;
form.pageXCoords.value = evt.pageX;
form.pageYCoords.value = evt.pageY;
form.layerXCoords.value = evt.layerX;
form.layerYCoords.value = evt.layerY;
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
var element_base_browser_styles = window.getDefaultComputedStyle(current_element);
var total_text_pixal_length = getTextWidth(current_element.value, element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);
var add_char_pixal_lengths = 0;
var myStringArray = current_element.value.split('');
var arrayLength = myStringArray.length;
for (var i = 0; i <= arrayLength; i++) {
var get_char_value = getTextWidth(myStringArray[i], element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);
add_char_pixal_lengths = add_char_pixal_lengths + (get_char_value) + 1.311111111111; //every char value is added together.
// console.log("Total: " + x);
if ((add_char_pixal_lengths)> (evt.layerX)) {
this.setSelectionRange(i, i);
add_char_pixal_lengths = 0;
break;
}
}
}
current_element.onmouseover = function() {
this.focus()
}
The problem I'm having is like Geosynchronous orbit; the cursor shifts out of place sometimes a few pixels (left or right). My calculation probably sucks, but I'm not sure canvas is really the best way to do the measurement? Is there a better way?
mousemove listener to receive element cursor coordinates from e.pageX
font style using window.getComputedStyles(input_element)
arr.split('') from input_element.text string: x = ['a','b','c']
'for loop' the array, generate a canvas and measure each characters width
add all char widths one by one until the value is greater than e.pageX
set the 'for loop' iterate as the setSelectionRange(i, i)
Any help or suggestions on making this better would be appreciated. Thanks!

how to check whether crop div covers rotated image?

I want to check whether cropping div covers images in it.Everything works fine when image is not rotated but after rotating image crop does not shows error msg...
Here is fiddle : Fiddle
function isCropValid(){
var $selector = $("#resizeDiv"); // cropping Div
var $img = $("#rotateDiv"); // image div
var $selectorW = $selector.width();
var $selectorH = $selector.height();
var $selectorX = $selector.offset().left ;
var $selectorY = $selector.offset().top ;
var $imgW = $img.width();
var $imgH = $img.height();
var $imgX = $img.offset().left;
var $imgY = $img.offset().top;
var diff_X = $selectorX - $imgX;
var diff_Y = $selectorY - $imgY;
if(diff_X+$selectorW > $imgW){
return false;
} else if(diff_Y+$selectorH > $imgH){
return false;
} else if($selectorX<$imgX){
return false;
} else if($selectorY<$imgY){
return false;
}
else {
return true;
}
}
or another function
function isCropValid(){
var el1 = document.getElementById("resizeDiv"); // cropDiv
var el2 = document.getElementById("rotateDiv"); // imageDiv
var cropdiv = el1.getBoundingClientRect();
var imgdiv = el2.getBoundingClientRect();
return (
((imgdiv.top <= cropdiv.top) && (cropdiv.top <= imgdiv.bottom)) &&
((imgdiv.top <= cropdiv.bottom) && (cropdiv.bottom <= imgdiv.bottom)) &&
((imgdiv.left <= cropdiv.left) && (cropdiv.left <= imgdiv.right)) &&
((imgdiv.left <= cropdiv.right) && (cropdiv.right <= imgdiv.right))
);
}
I above code i have one image inside div.if crop div gets out of this div i m showing label bg color red meaning crop is not correct otherwise i m showing label color green means crop is correct..
I think what you'll have to do is to calculate the positions of each of the 4 points of the image top-left top-right bottom-right and bottom-left, then do the same thing for the crop div something like this:
var $topLeftX=$selectorX-($selectorW/2)-($selectorH/2);
var $topLeftY=$selectorY-($selectorH/2)-($selectorW/2);
var $bottomLeftX=$selectorX-($selectorW/2)+($selectorH/2);
var $bottomLeftY=$selectorY+($selectorH/2)-($selectorW/2);
var $topRightX=$selectorX+($selectorW/2)-($selectorH/2);
var $topRightY=$selectorY-($selectorH/2)+($selectorW/2);
var $bottomRightX=$selectorX+($selectorW/2)+($selectorH/2);
var $bottomRightY=$selectorY+($selectorH/2)+($selectorW/2);
Then compare the corner points.
now the issue is with the corners of the image, as after rotation this will need some sine/cosine calculations.
you might want to take a look at this post: Find the coordinates of the corners of a rotated object in fabricjs
I think it will make your life much easier
So this is gonna be a big hack, but hey :-) The idea is to put the cut out behind the image, and then see whether the image overlaps the cut out on all four corners.
function cutoutIsOK() {
// Grab the cutout element and position it behind the image
var cutout = document.querySelector('#resizeDiv');
cutout.style.zIndex = -1;
// Grab the image
var image = document.querySelector('#rotateDiv img');
// Take the four corners of the cutout element
var cutoutRect = cutout.getBoundingClientRect();
var pos = [
[cutoutRect.left, cutoutRect.top],
[cutoutRect.right - 1, cutoutRect.top],
[cutoutRect.left, cutoutRect.bottom - 1],
[cutoutRect.right - 1, cutoutRect.bottom - 1]
];
// And verify that the image overlaps all four corners
var ok = pos.every(function(p) {
return document.elementFromPoint(p[0], p[1]) === image;
});
// Reset the cutout's z-index to make it visible again
cutout.style.zIndex = 0;
return ok;
}

Categories

Resources