Javascript Auto Increment Code not working - javascript

I need to generate 1000 images each with different numbers. Doing this is found a script online which works fine, but it doesn't work with 00 in front of the increments.
I can't just add 00 in front of every number because when it hits 10 it's doing 0010 instead of 010 like I want it to.
That means I need to change the code a bit. And it's probably REALLY basic, but I just can't figure it out. There is no log sadly, because I am running the script in Photoshop.
Here is the code I have trouble with. And underneath is the result:
for (var i=1; i <= numImages; i++) {
if(layer.textItem.contents < 10) {
layer.textItem.contents = "00" + i.toString();
} else if(layer.textItem.contents >= 10) {
layer.textItem.contents = "0" + i.toString();
} else {
layer.textItem.contents = i.toString();
}
SavePNG(directory + imageName + '_'+ i +'.png');
};
Any assistance is highly appreciated! I don't need to be fed by a spoon! I need to learn from my mistakes!
Here is the entire code in the script (Forgot to add this, edited afterwards)
var imageName = 'Oppmoteskjema';
var numImages = 15;
function SavePNG(saveFile){
var pngOpts = new ExportOptionsSaveForWeb;
pngOpts.format = SaveDocumentType.PNG
pngOpts.PNG8 = false;
pngOpts.transparency = false;
pngOpts.interlaced = false;
pngOpts.quality = 10;
activeDocument.exportDocument(new File(saveFile),ExportType.SAVEFORWEB,pngOpts);
}
var layer = activeDocument.layers[0];
if (layer.kind == 'LayerKind.TEXT') {
for (var i=1; i <= numImages; i++) {
layer.textItem.contents = i.toString();
var str = "" + i;
var pad = "000";
var ans = pad.substring(0, pad.length - str.length) + str;
SavePNG(directory + imageName + '_'+ ans +'.png');
}
};```

You could try it this way:
for (var i=1; i <= numImages; i++) {
var str = "" + i;
var pad = "000";
var ans = pad.substring(0, pad.length - str.length) + str;
layer.textItem.contents = ans;
SavePNG(directory + imageName + '_'+ ans +'.png');
};
You can change pad template as you wish. The output of this will be:
1 -> 001
97 -> 097
999 -> 999
1234 -> 1234

If you're just trying to manipulate a variable based off the index of the loop then the below would suffice.
for (var i = 1; i <= 1000; i++) {
// Result will be '00' | '0' | ''
const result = i < 10 ? '00' : i < 100 ? '0' : '';
// The result is prepended to the current index
// Aka (001, 010, 100)
const contents = result + i;
// Set the text item object contents to value of contents
layer.textItem.contents = contents;
// Saves the Image
SavePNG(directory + imageName + '_' + contents + '.png');
}
This
i < 10 ? '00' : i < 100 ? '0' : ''
Is a ternary operator btw, it's essentially a shorthand if statement.

You can add the number to a string of zeroes, and then slice the resulting string based on desired length:
var template = "0000";
var num = 0;
var targetNumber = 1000;
for(let i = 0; i <= targetNumber; i++) {
// add i to the template. Javascript will automatically to this type-coerceon since we're adding string + number
let numStr = template + i;
// strip leading zeroes to match the template length
numStr = numStr.slice(numStr.length - template.length);
console.log(numStr);
}

Related

Reverse String In Place Using for loop in JavaScript

var n = "reversestrings", k=3;
want to reverse string in chunk of 'k',
Answer would be : ver sre tse nir gs;
if Last word less then 'k' then don't need to reverse.
I am using below code but not getting expected answer.
var n = 'stringreverses', k = 3, str = '', s = '';
var c = 0;
for( var i=0; i<n.length; i++ ){
if( c<k ){
c++
str += n[i];
s=str.split('').reverse().join('');
}
else{
console.log("-" + s);
c=0;
}
}
First we need to split input to chunks with the same size (the last one can be smaller), next we reverse every chunk and concatenate at the end.
var input = "123456",
chunks = input.match(new RegExp('.{1,' + k + '}', 'g'));
var result = chunks.map(function(chunk) {
return chunk.split('').reverse().join('');
}).join('');
Homework or not, here is a good use case to start with strings.
Here is a C approach but you have more in Javascript.
In fact you want to reverse by chunk so deal with chunk. How to create a chunk of string ? a way is to use slice https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice
var str = "abcdef";
console.log(str.slice(0,2));
So you have an easy way to slice your string into chunk.
Then you have to iterate over it, there is no good way of doing it actually there is dozen but you could do it from backward to the beginning of the string:
for( i=str.length ; i>0 ; i -= k ){
// i will go from the end of your str to
// the beginning by step of k(=3) and you can use i - k and i
// to slice your string (as we see it before)
// you have to take care of the last part that could be less than
// 3
}
then you have to format the result, the most easy way to do that is to concatenate results into a string here it is :
var strRes = "";
strRes += "res 1";
strRes += "res 2";
console.log(strRes); // should screen "res 1res 2"
As it is homework, I wont make a jsfiddle, you have here all the pieces and it's up to you to build the puzzle.
hope that help
$(function() {
var n = 'reversestrings', k = 3;
var revString = "";
for (var i =0; i<=n.length; i++) {
if (i%k == 0) {
l = parseInt(k) + parseInt(i);
var strChunk = n.substring(i,l);
var innerStr = "";
for (var j =0; j<strChunk.length; j++) {
var opp = parseInt(strChunk.length) - parseInt(j) - 1;
innerStr = innerStr + strChunk.charAt(opp);
}
revString = revString + " "+innerStr;
}
}
alert(revString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
My take on this. Pure JS without even built-in functions:
function reverseSubStr(str) {
var right = str.length - 1, reversedSubStr = '';
while(right >= 0) {
reversedSubStr += str[right];
right--;
}
return reversedSubStr;
}
function reverseStr(str) {
var initialStr = str, newstr = '', k = 3, substr = ''
for(var i = 1; i <= initialStr.length; i++) {
substr += initialStr[i - 1]; // form a substring
if(i % k == 0) { // once there are 3 symbols - reverse the substring
newstr += reverseSubStr(substr) + " "; // ... and add space
substr = ''; // then clean temp var
}
}
return newstr += substr; // add the remainder of the string - 'gs' - and return the result
}
var str = 'reversestrings';
console.log(reverseStr(str)); //ver sre tse nir gs
I like #Jozef 's approch but here is mine as well for those who are not much into Regex -
//Taking care of Tail Calling
function reverStrInChunk(str, k, r=''){
let index=0, revStr,
res = str.substring(index, k), remStr;
revStr = res.split("").reverse().join("");
remStr = str.substring(k, str.length);
r = r + revStr;
if(remStr.length>k){
return reverStrInChunk(remStr,k, r+" ");
}
else if(remStr.length<k) {
return r +" "+remStr;
}else{
return r +" "+ remStr.split("").reverse().join("");
}
}
var aStr = reverStrInChunk('reversestrings',3);//ver sre tse nir gs
console.log(aStr);

Nested Loop to add numbers

I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.

Javascript for loop sums

I want to find the sums of a set of numbers from a for loop
I currently have
var num = "";
for(var i = 1; i < 11; i +=1){
num = num + i;
}
console.log(num)
which gives me 12345678910 in the JS console
I want to produce 1+2+3+4+5+6+7+8+9+10=SUM
I have tried adding a "+" string:
num = num + i + "+";
but it gives me 1+2+3+4+5+6+7+8+9+10+
My question is how to add the "+" and "=" into the code and get the sum.
If you want the + to display AND the actual sum, then do this
var realSum = 0;
var num = "1";
for(var i = 2; i < 11; i +=1){
realSum = realSum + i;
num = num + "+" + i;
}
num = num + "=" + realSum;
Try this : http://jsfiddle.net/kx9b7qu7/2
Using Eval
var num = [];
for(var i = 1; i < 11; i +=1){
num.push(i)
}
var equation = num.join('+');
var sum = eval(equation);
console.log('Method 1: ',equation + '=' + sum)
Without using Eval
var num = [];
var sum = 0;
for(var i = 1; i < 11; i +=1){
num.push(i)
sum += i
}
var equation = num.join('+');
console.log('Method 2: ',equation + '=' + sum)
Make an util out of it for later use ;) There are also other ways that make use of functional approach (reduce, map) and things that aren't widely supported yet (generators, array comprehensions).
Here are some example functions for consideration and tweaking:
// kind of usual
var sumRange = function (from, to, step) {
var i,
sum = from,
str = from;
for (i = from + step; i <= to; i += step) {
sum += i;
str += '+' + i;
};
str += '=' + sum;
return str;
};
// sum of elements in arithmetic progression
var sumRangeAP = function (from, to, step) {
var i,
n,
str = from;
n = ((to - from) / step) + 1;
for (i = from + step; i <= to; i += step) {
str += '+' + i;
};
str += '=' + ((from + to) / 2) * n;
return str;
};
// memory efficiency (not creating hell a lot of strings) together with some functional stuff
// on the other hand it looks like assignment operators (+, +=) win with .join in terms of speed sometimes
// in many cases, I think, you may not give a shit about whether you use this or that
var sumRangeME = function (from, to, step) {
var i,
sum = from,
str = [from];
for (i = from + step; i <= to; i += step) {
str.push(i);
};
return str.join('+') + '=' + str.reduce(function (prevVal, curVal) { return prevVal + curVal; });
};
console.log(sumRange(0,20,1));
console.log(sumRangeAP(0,20,1));
console.log(sumRangeME(0,20,1));
console.log(sumRange(1,21,1));
console.log(sumRangeAP(1,21,1));
console.log(sumRangeME(1,21,1));
console.log(sumRange(7,36,1));
console.log(sumRangeAP(7,36,1));
console.log(sumRangeME(7,36,1));
In javascript + can also concatenate a string, if that's what seems best - it thinks you are putting two strings together so it concatenates them. Make num start as 0 instead, that should fix it.
Instead of var num="" try with var num=0, because this way the operator + is used as string concatenation. num=0 will do the job.
EDIT: I thought you wanted to see the "math" equation try the following:
var numbers = 0;
for (var i = 1; i < 11; i += 1){
numbers += i;
}
console.log(numbers);
Try this:
var numbers = [];
for (var i = 1; i < 11; i += 1){
numbers.push(i);
}
var string = numbers.join("+");
string += "=" + eval(numbers.join("+"));
console.log(string);
If you're really trying to concatenate then
num = num + "+" + i;

Fill pdf form with javascript (client-side only)

I need to fill a pdf form automatically in my angularjs webapp. The pdf form is generated outside the app so I can configure it as I want.
In my app, I just need to load the pdf, modify the form fields and flatten the file so it doesn't look like a form anymore.
Do you know any way to do it?
Edit:
I've found iText but it's a java library which won't work for my project (the app runs on tablets so I'm looking for something 100% HTML5)
There is now another solution that worked for me.
It's this JS package: https://github.com/phihag/pdfform.js
Also available on NPM: https://www.npmjs.com/package/pdfform.js
If you have troubles opening your PDF files, the best bet is to use the mozilla's PDF.js library which works with every PDF files I tried.
The only drawback as of today is that it's not working as expected with webpack. You have to import the JS files with a script tag.
I've found a solution...not perfect but it should fit most requirements. It doesn't use any server (perfect for privacy requirements) or library! First of all, the PDF must be version 1.5 (Acrobat 6.0 or later). The original pdf can be another version but when you create the fields you must save it as compatible for Acrobat 6.0 or later. If you want to make sure the format is right, you can check there
So let's say I have 'myform.pdf' file (with no form fields); I open it with Acrobat Pro (I have Acrobat Pro 11 but it should work with other versions). I add fields and pre-fill the field's value (not the field name!) with a 'code' (unique text string). This code will be find/replace with the string you want by the javascript function below so let say '%address%' (you can add multiple fields but use a different code to differenciate fields). If you want to have a flatten look of the field, set the field to read-only. To save it, go to File -> Save as other... -> Optimized PDF and choose "Acrobat 6.0 and later" under Make compatible with (top right of the pop-up).
Once you have your file saved, you can check that the format is right by opening it in a text editor and looking for your codes (in my case '%address%'). Count number of occurences, it should appear three times.
The following function does three things:
- Changes the fields content
- Recalculate the content's length
- Fix the cross reference tables
So now the function (look at the end for the final pdf blob):
#param certificate: your pdf form (format of this variable must be compatible with FileReader)
#param changes: the field changes, [{find: '%address%', replace: '2386 5th Street, New York, USA'}, ...]
// Works only for PDF 1.5 (Acrobat 6.0 and later)
var fillCertificate = function (certificate, changes) {
// replace a a substring at a specific position
String.prototype.replaceBetween = function(start, end, what) {
return this.substring(0, start) + what + this.substring(end);
};
// format number with zeros at the beginning (n is the number and length is the total length)
var addLeadingZeros = function (n, length) {
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
// Create the reader first and read the file (call after the onload method)
var reader = new FileReader();
// To change the content of a field, three things must be done; - change the text of the field, - change the length of the content field, - change the cross table reference
reader.onload = function(aEvent) {
var string = aEvent.target.result;
// Let's first change the content and the content's length
var arrayDiff = [];
var char;
for(var foo = 0; foo < changes.length; foo++) {
// Divide the string into a table of character for finding indices
char = new Array(string.length);
for (var int = 0; int < string.length; int++) {
char[int] = string.charAt(int);
}
// Let's find the content's field to change and change it everywhere
var find = changes[foo].find;
var replace = changes[foo].replace;
var lengthDiff = replace.length - find.length;
var search = new RegExp(find, "g");
var match;
var lastElements = [];
var int = 0;
var objectLenPos;
var objectLenEnd;
// Each time you change the content, compute the offset difference (number of characters). We'll add it later for the cross tables
while (match = search.exec(string)) {
arrayDiff.push({index: match.index, diff: lengthDiff});
lastElements.push({index: match.index, diff: lengthDiff});
// Find length object
if(int == 0){
var length = 0;
var index;
while(char[match.index - length] != '\r'){
index = match.index - length;
length++;
}
objectLenPos = index + 10;
length = 0;
while(char[objectLenPos + length] != ' '){
length++;
objectLenEnd = objectLenPos + length;
}
}
int++;
}
var lengthObject = string.slice(objectLenPos, objectLenEnd) + ' 0 obj';
var objectPositionStart = string.search(new RegExp('\\D' + lengthObject, 'g')) + lengthObject.toString().length + 2;
var length = 0;
var objectPositionEnd;
while(char[objectPositionStart + length] != '\r'){
length++;
objectPositionEnd = objectPositionStart + length;
}
// Change the length of the content's field
var lengthString = new RegExp('Length ', "g");
var fieldLength;
var newLength;
string = string.replace(lengthString, function (match, int) {
// The length is between the two positions calculated above
if (int > objectPositionStart && int < objectPositionEnd) {
var length = 0;
var end;
while (char[int + 7 + length] != '/') {
length++;
end = int + 7 + length;
}
fieldLength = string.slice(end - length, end);
newLength = parseInt(fieldLength) + lengthDiff;
if (fieldLength.length != newLength.toString().length) {
arrayDiff.push({index: int, diff: (newLength.toString().length - fieldLength.length)});
}
// Let's modify the length so it's easy to find and replace what interests us; the length number itself
return "Length%";
}
return match;
});
// Replace the length with the new one based on the length difference
string = string.replace('Length%' + fieldLength, 'Length ' + (newLength).toString());
string = string.replace(new RegExp(find, 'g'), replace);
}
// FIND xref and repair cross tables
// Rebuild the table of character
var char = new Array(string.length);
for (var int = 0; int < string.length; int++) {
char[int] = string.charAt(int);
};
// Find XRefStm (cross reference streams)
var regex = /XRefStm/g, result, indices = [];
while ( (result = regex.exec(string)) ) {
indices.push(result.index);
}
// Get the position of the stream
var xrefstmPositions = [];
for(var int = 0; int < indices.length; int++){
var start;
var length = 0;
while(char[indices[int] - 2 - length] != ' '){
start = indices[int] - 2 - length;
length++;
}
var index = parseInt(string.slice(start, start + length));
var tempIndex = parseInt(string.slice(start, start + length));
// Add the offset (consequence of the content changes) to the index
for(var num = 0; num < arrayDiff.length; num++){
if(index > arrayDiff[num].index){
index = index + arrayDiff[num].diff;
}
}
string = string.replaceBetween(start, start + length, index);
// If there is a difference in the string length then update what needs to be updated
if(tempIndex.toString().length != index.toString().length){
arrayDiff.push({index: start, diff: (index.toString().length - tempIndex.toString().length)});
char = new Array(string.length);
for (var int = 0; int < string.length; int++) {
char[int] = string.charAt(int);
};
}
xrefstmPositions.push(index);
}
// Do the same for non-stream
var regex = /startxref/g, result, indices = [];
while ( (result = regex.exec(string)) ) {
indices.push(result.index);
}
for(var int = 0; int < indices.length; int++){
var end;
var length = 0;
while(char[indices[int] + 11 + length] != '\r'){
length++;
end = indices[int] + 11 + length;
}
var index = parseInt(string.slice(end - length, end));
var tempIndex = parseInt(string.slice(end - length, end));
for(var num = 0; num < arrayDiff.length; num++){
if(index > arrayDiff[num].index){
index = index + arrayDiff[num].diff;
}
}
string = string.replaceBetween(end - length, end, index);
if(tempIndex.toString().length != index.toString().length){
arrayDiff.push({index: end - length, diff: (index.toString().length - tempIndex.toString().length)});
char = new Array(string.length);
for (var int = 0; int < string.length; int++) {
char[int] = string.charAt(int);
};
}
xrefstmPositions.push(index);
}
xrefstmPositions.reverse();
var firstObject, objectLength, end;
var offset;
// Updated the cross tables
for(var int = 0; int < xrefstmPositions.length; int++) {
var length = 0;
var end;
if(char[xrefstmPositions[int]] == 'x'){
offset = 6;
} else{
offset = 0;
}
// Get first object index (read pdf documentation)
while(char[xrefstmPositions[int] + offset + length] != ' '){
length++;
end = xrefstmPositions[int] + offset + length;
}
firstObject = string.slice(end - length, end);
// Get length of objects (read pdf documentation)
length = 0;
while(char[xrefstmPositions[int] + offset + 1 + firstObject.length + length] != '\r'){
length++;
end = xrefstmPositions[int] + offset + 1 + firstObject.length + length;
}
objectLength = string.slice(end - length, end);
// Replace the offset by adding the differences from the content's field
for(var num = 0; num < objectLength; num++){
if(char[xrefstmPositions[int]] == 'x'){
offset = 9;
} else{
offset = 3;
}
// Check if it's an available object
if (char[xrefstmPositions[int] + 17 + offset + firstObject.length + objectLength.length + (num * 20)] == 'n') {
var objectCall = (parseInt(firstObject) + num).toString() + " 0 obj";
var regexp = new RegExp('\\D' + objectCall, "g");
var m;
var lastIndexOf;
// Get the last index in case an object is created more than once. (not very accurate and can be improved)
while (m = regexp.exec(string)) {
lastIndexOf = m.index;
}
string = string.replaceBetween(xrefstmPositions[int] + offset + firstObject.length + objectLength.length + (num * 20), xrefstmPositions[int] + 10 + offset + firstObject.length + objectLength.length + (num * 20), addLeadingZeros(lastIndexOf + 1, 10));
}
if(num == objectLength - 1){
if (char[xrefstmPositions[int] + offset + firstObject.length + objectLength.length + ((num + 1) * 20)] != 't'){
xrefstmPositions.push(xrefstmPositions[int] + offset + firstObject.length + objectLength.length + ((num + 1) * 20));
}
}
}
}
// create a blob from the string
var byteNumbers = new Array(string.length);
for (var int = 0; int < string.length; int++) {
byteNumbers[int] = string.charCodeAt(int);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {type : 'application/pdf'});
// Do whatever you want with the blob here
};
reader.readAsBinaryString(certificate);
}
So the code is not clean at all but it works :)
Let me know if you have any question
pdf-lib was the best choice for me. Look, after trying many random solutions I found this lib that's very very simple to implement and, off-topic, has a great TS support (nowadays it means a lot 😬).
Fill form official example: https://pdf-lib.js.org/#fill-form
As far as I can see, there is no client-side application on tablets which would do that.
That means you will need server-side support, and iText is indeed one of the products out there. Another one is FDFMerge by Appligent, which does fill and can be set to flattening.

Loop to print iterations separated with a comma, with no comma at the end

I'm a student and am writing a JavaScript "for" loop that prints into innerHTML. Every concatenation of the string is added to the last followed by a comma. how do I make it so the comma is not printed after the last iteration? Just for piece of mind, the commas aren't part of the assignment, I'm just trying to add practical application. no jQuery tho please
window.onload = function(){
var mySeven = 0;
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i;
printSeven.innerHTML += i + ',' + ' ';
}
}
};
Thanks!
You should use join() instead. It's much cleaner and you don't need to worry about edge cases:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
printSeven.innerText = sevens.join(", ");
Or an approach that avoids the if() statement and unnecessary iterations:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i = 7; i <= 1000; i += 7){
sevens.push(i);
}
printSeven.innerText = sevens.join(", ");
And for the sake of understanding, here's how you could do this without join():
var printSeven = document.getElementById('multiples_seven');
var maxValue = 1000;
var list = "";
for (i = 7; i <= maxValue; i += 7){
list += i;
if(i + 7 <= maxValue){
list += ", ";
}
}
printSeven.innerText = list;
Use this function:
function reorderData(){
var sevens = Array();
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
var newDisplaySelectedArray = sevens.join(",");
jQuery( "#multiples_seven" ).val(newDisplaySelectedArray);
}
First off it is better to not manipulate the DOM inside a loop. You should construct your output in a string or array then add it to the DOM in a single operation :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven;
};
To delete the trailing comma you have two options : don't add it in the first place or remove it before adding it to the DOM.
Most other answers have concentrated on not adding it, here is a solution which removes it :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven.slice (0, -2);
};
A word of caution, if your for loop does not execute at least one iteration you may remove characters you want to display. In the generic case it is easier to build an array and use the join function as shown in other answers here.
It's easier to check if you are at the first item than if you are at the last, so simply add the commas before the number:
window.onload = function(){
var mySeven = 0;
var printSeven = '';
for (i = 1; i <= 1000; i++) {
if (i % 7 == 0){
mySeven += i;
printSeven += (printSeven.length > 0 ? ', ' : '') + i;
}
}
document.getElementById('multiples_seven') += printSeven;
};

Categories