javascript illustrator copy pdf documents and stack them issue - javascript

I'm looking for a way to copy pdf documents and stack them resized (I think resize works as duplicate, so once this works I will be able to complete my script).
I've been using .duplicate for now, and I can only manage to copy 1 item[0] on the same doc. Besides if I copy element by element I won't be able to replace them easily that's why I want to copy the whole document
I'm opening every script I find to understand a possible method.
Syntax is ok
var targetFile = app.documents.add(); //this is my output file - it is created
folder = Folder.myDocuments; //this paragraph works for now
sourceFolder = folder.selectDlg("source");
for ( i = 0; i < files.length; i++ ){
var sourceDoc = app.open(files[i]);
var doc = app.activeDocument;
for (l = 0; l < doc.pageItems.length; l++) { //corrected error
doc.pageItems[i].selected = true;
}
var mySel = app.activeDocument.selection; //this paragraph need rework
newItem = mySel[0].duplicate(targetFile); //mysel.duplicate(targetFile) is not a function
// MAIN ERROR
}
I use ESTK and notepad++ and have checked the variable, nothing obviously wrong during F10 debug. Using Jongware's CHM reference guide and some github tutorial but they tend to help for single operation script. My goal is to have script without GUI to reduce errors and time to proceed
Thank you for your time
EDIT: spotted an error with i used two times in a loop

Simple self solution:
var mySel = app.activeDocument.selection;
app.executeMenuCommand('copy');
targetFile.activate();
newItem = app.executeMenuCommand('paste');

Related

How to get the JavaScript display results "on click" query to display ALL results

I'm trying to create an excel spreadsheet compiling all responses from an online survey on Google Chrome, there are over 500 entries and to click on each entry to get the results would take forever.
I've pinpointed the problem on the Google Chrome > Inspect > Elements at the point with the multiple display results onclick. Is there any way to remove the onclick to be able to download or copy-paste all the results at once?
I've attached a picture below:
https://imgur.com/wyxoRjN
I would appreciate any advice on how best to do this! Apologies in advance as I have absolutely no programming experience so I might not get all the terminology.
EDIT
You should check with the online survey service since there should be a way to export your results to csv (csv can be opened in excel). (Author indicated there was no way)
Before using website scraping code, make sure that the service is alright with you grabbing the data that way. The code should not be scraped for malicious intent or means that break terms of the agreement.
IF the structure that you provided is consistent then you should be able to copy the code below (or from the javascript pane in the fiddle), run it in the console on the page with the data (F12, console tab in chrome), the data should print to the console where you can copy it, and then use an online tool(like this) to convert it from json to csv for excel.
var getData = () => {
var table = document.getElementById('table_survey'); // get table
var data = []; // holds all the data
for (i = 0; i < table.rows.length; i++) { //loops through rows
var pieceOfData = {}
var cells = table.rows.item(i).cells; //gets cells
for (var j = 0; j < cells.length; j++) { //loops through each cell
var cellVal = cells.item(j).innerHTML; // get piece of data
// store data in object dependent on index
//assumes only 4 <td>s with valid data
switch (j) {
case 0:
pieceOfData.id = cellVal
case 1:
pieceOfData.data1 = cellVal
case 2:
pieceOfData.data2 = cellVal
case 3:
pieceOfData.day = cellVal
}
}
data.push(pieceOfData); // add data object to array
}
return data; // return all the data
}
var allData = getData(); // puts all the data in a variable
console.log(allData); // print data to console
My Fiddle: https://jsfiddle.net/m852hge8/
In my view the easiest, low-tech way to do this is to paste the whole thing in a text editor such as Notepad++ (which is free), and do a lot of "replace all" to remove what you don't want (by replacing by blank).
For example replace "tr onclick="displayResults(" by "" (i.e. blank)
The simplest solution is to switch off the Javascript of your browser while you work on the CSV and swith it back on when you are finished. The onclick is executing Javascript and if it is switched off for your browser, then it will not be executed.
This should work, however, if Javascript is needed to display the data you need to extract, then you need Javascript to be switched on, but you can override displayResult to be a dummy function, so you will not experience the problematic behavior when you click in your browser console:
displayResult = function() {};
This should work, but if, for some reason displayResult is redefined, then you can remove the onclick of each element. If there are too many elements for manual execution, then you can execute something like this in your console:
var survey = document.querySelectorAll("#table-survey tr");
for (var index = 0; index < survey.length; index++) {
survey[index].onclick = "";
}

How to change position of the automatic filename numbering with javascript as InDesign exports files?

Here's a js script for InDesign I wrote that exports layouts from a book file and saves them in a desktop folder. It works fine, except that I want to change the position of the automatic numbering. I have it set up now so that it adds an underscore between the filename and the automatic numbering to avoid confusion, because the end of the filenames all contain a number.
The script outputs files named like this: SampleStory_FL164.jpg. The number 4 (right after "FL16" which is part of the filename)is the automatic page number, so in this case this is page number 4 from a multipage indd document. I'd like to move the 4 from its current position to right before the underscore, so that the file would be renamed like this: SampleStory4_FL16.jpg. I can do this outside of InDesign (ignoring the exporting automation) with javascript, as seen here:
myDocument = "SampleStory_FL164.jpg"
//get position right after "FL16"
var firstIndex = myDocument.indexOf("FL16") + 4;
//get position right before ".jpeg"
var secondIndex = myDocument.indexOf(".jpg");
//find anything between firstIndex and secondIndex and assign it to a variable
var charsBetweenIndexes = myDocument.substring(firstIndex, secondIndex);
//search file name and replace anything between first and second index
var newFileName = myDocument.replace(charsBetweenIndexes, "");
//add what you deleted back right after the file name and before the underscore
newFileName = newFileName.replace("_", charsBetweenIndexes + "_");
//change myDocument to the value of newFileName before exporting
myDocument = newFileName;
But, with InDesign the tacking on of a number as the files are saved seem out of reach and not available to manipulate. I'm thinking here of the exportFile method or maybe the File object. Is there a way to do this? Here's the code I have working now:
Main();
// If you want the script to be un-doable, comment out the line above, and remove the comment from the line below
// app.doScript(Main, undefined, undefined, UndoModes.ENTIRE_SCRIPT,"Run Script");
function Main() {
// Check to see whether any InDesign documents are open.
// If no documents are open, display an error message.
if(app.documents.length > 0) {
app.jpegExportPreferences.exportingSpread = false;
app.jpegExportPreferences.jpegExportRange = ExportRangeOrAllPages.EXPORT_ALL;
if (app.books.length != 1)
alert ("This only works when you have one (1) book open");
else
for (b=0; b<app.books[0].bookContents.length; b++)
{
var myDocument = app.books[0].bookContents[b].fullName ;
c = app.open(app.books[0].bookContents[b].fullName);
myDocument = myDocument.name.replace("indd","jpg");
myDocument = myDocument.replace("FL16", "FL16_");
c.exportFile (ExportFormat.JPG, File(Folder.desktop + "/EDIT_Jpgs/" + myDocument));
}
}
else {
// No documents are open, so display an error message.
alert("No InDesign documents are open. Please open a document and try again.");
}
}
You may not be able to alter InDesign's built-in naming convention, but you could always rename them after you export them using the File object's rename method. Something like this would work (placed after your for loop):
var myFiles = Folder(Folder.desktop + "/EDIT_Jpgs/").getFiles("*.jpg");
for (var i = 0; i < myFiles.length; i++){
var myFile = myFiles[i];
//Adjust this regular expression as needed for your specific situation.
myFile.rename(myFile.name.replace(/(_FL16)(\d+)/, "$2$1"));
}
Rename returns a boolean value so you could log information on any failures if you needed to.

Loading a Random Caption from a text file using Javascript and Displaying via HTML

I am trying to load a random caption every time my page is loaded. I have a separate text file and contained on each line is a string. I am new to both html and Javascript, as you will see.
HTML:
<div class="centerpiece">
<h1>DEL NORTE BANQUEST</h1>
<p class="caption"><script src = "js/caption.js"></script><script>getCaption();</script></p>
<a class="btn" id="browse-videos-button" href="#video-list">Browse Videos<br><img src="img/arrow-down.svg"style="width:15px;height:15px;"></a>
</div>
Javascript:
function getCaption()
{
var txtFile = "text/captions.txt"
var file = new File(txtFile);
file.open("r"); // open file with read access
var str = "";
var numLines = 0; //to get the range of lines in the file
while (!file.eof)
{
// read each line of text
numLines += 1;
}
file.close();
file.open("r");
var selectLine = Math.getRandomInt(0,numLines);//get the correct line number
var currentLine = 0;
while(selectLine != currentLine)
{
currentLine += 1;
}
if(selectLine = currentLine)
{
str = file.readln();
}
file.close();
return str;
}
Text in Source File:
We talked yesterday
Freshman boys!
5/10
I'm having a heart attack *pounds chest super hard
The site is for my highschool cross country team in case the text file was confusing.
I am unfamiliar with most syntax and was unable to see if by iterating through the file with a loop if i needed to reset somehow which is why I opened and closed the file twice. Here is a jsfiddle of the specific caption I am trying to change and what my function is in Javascript.
https://jsfiddle.net/7cre9qqj/
If you need more code to work with please let me know and any critiques you may have please dont hold back if it looks like a mess, I am trying to learn after all! Thank you for your help!
The File API allows access to the file system on the client side, so it's not really suited to what you want to do. It's also only allowed to be used in very specific circumstances.
A simple solution is to just run an AJAX request to populate your quote. The AJAX call can read the file on your server, then it's simple to split the contents of the file by line, and pick a random line to display. Since you're open to jQuery, the code is pretty simple:
$.get("text/captions.txt")).then(function(data) {
var lines = data.split('\n');
var index = Math.floor(Math.random() * lines.length);
$("#quote").html(lines[index]);
});
Here's a fiddle that demonstrates it in full; every time it runs it will load a random quote: https://jsfiddle.net/s1w8x4ff/

getting pictures into an array in javascript

im kinda new to javascript i mean i know the syntax but not so much the libraries.
i need some help to get some files (pictures) from a folder into an arry lets say:
var[] pictures = ?;
(the folder is in my project and contain some pictures)
so i can loop over them and diplay them on the page i did some search but i didnt find any guide on how to do this.
i realy want to understand on how to do this for future projects even a link to known guid you guys know we will be a big help.
if it help im using asp.net.
Well, there are a lot of ways to approach the problem, to me what you can do is (if you don't know the location of the images beforehand) make a service that returns the src of every image, store that in an array, and then show them in the page.
I believe you are using jQuery so you can make an ajax request like this:
jQuery.ajax({
url: /*path to*/"Service.asmx/getSources"
//options, check documentation
});
then, from asp, make a new service (Service.asmx in my case) and create a method that returns the location of the pictures (in my case the method is called getSources)
I recommend you use JSON (and jQuery.getJSON() method) so you can return a List<string>.
Lastly you can iterate or store the sources in an array, I'll put an example with the getJSON method
var sources = []
jQuery.getJSON("Service.asmx/getSources", function(data) {
for(var i = 0, len = data.length; i<len ; i++) {
sources.push(data[i]);//store every source in the array
}
});
once you have the sources you can display them like this fiddle
Tell me if it helped or if you need another solution.
If you want an array of pictures just to display them later, you can simply use:
var sources = [
"path/to/yourImage1.jpg",
"path/to/yourImage2.jpg",
// ...
"path/to/yourImageN.jpg",
];
var pics = [];
for(var i = 0; i < sources.length; i++) {
var pic = new Image();
pic.src = sources[i];
pics[i] = pic;
}

Collect DOM elements from external HTML documents

I am trying to write a report-generator to collect user-comments from a list of external HTML files. User-comments are wrapped in < span> elements.
Can this be done using JavaScript?
Here's my attempt:
function generateCommentReport()
{
var files = document.querySelectorAll('td a'); //Files to scan are links in an HTML table
var outputWindow = window.open(); //Output browser window for report
for(var i = 0; i<files.length; i++){
//Open each file in a browser window
win = window.open();
win.location.href = files[i].href;
//Scan opened window for 'comment's
comments = win.document.querySelectorAll('.comment');
for(var j=0;j<comments.length;j++){
//Add to output report
outputWindow.document.write(comment[i].innerHTML);
}
}
}
You will need to wait for onload on the target window before you can read content from its document.
Also what type of element is comment? In general you can't put a name on just any element. Whilst unknown attributes like a misplaced name may be ignored, you can't guarantee that browsers will take account of them for getElementsByName. (In reality, most browsers do, but IE doesn't.) A class might be a better bet?
Each web browse works in a defined and controlled work space on a user computer where certain things are restrict to code like file system - these are safety standards to ensure that no malicious code from internet runs into your system to phishing sensitive information stored on in it. Only ways a webbrowser is allowed if access granted explicitly by the user.
But i can suggest you for Internet Application as
- If List of commands is static then cache either by XML, Json or Cookies [it will store on user's system until it expires]
- If dynamic then Ajax to retrieve it
I think I have the solution to this.
var windows = [];
var report = null;
function handlerFunctionFactory(i,max){
return function (evt){
//Scan opened window for 'comment's
var comments = windows[i].document.querySelectorAll('.comment');
for(var j=0;j<comments.length;j++){
//Add to output report
report.document.write(comments[j].innerHTML);
}
if((i+1)==max){
report.document.write("</div></body></html>");
report.document.close();
}
windows[i].close();
}
}
function generateReport()
{
var files = document.querySelectorAll('td a'); //The list of files to scan is stored as links in an HTML table
report = window.open(); //Output browser window for report
report.title = 'Comment Report';
report.document.open();
report.document.write('<!DOCTYPE html PUBLIC"-// W3C//DTD XHTML 1.0 Transitional//EN"" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
+ '<html><head><title>Comment Report</title>'
+ '</head><body>');
for(var i = 0; i<files.length; i++){
//Open each file in a browser window
win = window.open();
windows.push(win)
win.location.href = files[i].href;
win.onload = handlerFunctionFactory(i,files.length);
}
}
Any refactoring tips are welcome. I am not entirely convinced that factory is the best way to bind the onload handlers to an instance for example.
This works only on Firefox :(

Categories

Resources