I would like to find difference between two fields using JavaScript in iText.
I am able to find the sum of them using below code:
PdfStamper stamperResult = new PdfStamper(readersectionResult, new FileOutputStream(RESULT_NEW));
stamperResult .addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"total2\")')");
Is there any way to find the difference using 'AFSimple_Calculate' similar to what I did in the above code snippet?
Thanks for editing! I tried your suggestion but it does not seem to work for some reason.
stamperResult.addJavaScript(" var total1 = this.getField(\"value1\"); var total2 = this.getField (\"value2\"); var subtr = this.getField(\"total\"); subtr.value = total1.value - total2.value;");
I separated newlines by spaces and added right escape characters.
I was also thinking of using a different logic for subtraction using AF methods : like this
stamperResult.addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"-total2\")')");
In the above code I was trying to add -(negative value) to total 2 so that it will be subtracted from total1 though the AF method is still 'SUM'.
But that does not work.
The below simple code seem to work :
stamperResult.addJavaScript("var nameField = this.getField('total');" +
"nameField.setAction('Calculate'," +
"'subtract()');" +
"" +"function subtract(){this.getField('total').value
= (this.getField('total_1').value -this.getField('total_2').value); }");
I updated your question because it contained many spelling errors. I didn't edit the code snippet because I don't know what the original code snippet is like. In any case: I think something went wrong during the copy/paste process, as I don't think your code snippet compiles in its current state.
In any case: as far as I know the AF-methods (the AF stands for Adobe Forms) may not be present in every viewer, and as far as I know Adobe didn't implement a way to subtract values from each other in the AFSimple_Calculate method.
For these two reasons, you may prefer regular JavaScript instead of using a pre-canned function that may or may not be pre-canned.
This regular JavaScript may look like this:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var subtr = this.getField("difference");
subtr.value = total1.value - total2.value;
I'm not sure if that answers your question. Maybe you just want:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var namefield = total1.value - total2.value;
You can put these lines inside a String using the right escape characters and replacing the newlines by spaces or newline characters.
Of course, you need to trigger this code somewhere. Below you'll find an example that puts the negative value of the content of a value1 field into a value2 field.
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("js.pdf"));
document.open();
writer.addJavaScript("function makeNegative() { this.getField('value2').value = -(this.getField('value1').value); } ");
Rectangle rect1 = new Rectangle(40, 740, 200, 756);
TextField value = new TextField(writer, rect1, "value1");
value.setBorderColor(GrayColor.GRAYBLACK);
value.setBorderWidth(0.5f);
PdfFormField field = value.getTextField();
field.setAdditionalActions(PdfName.BL, PdfAction.javaScript("makeNegative();", writer));
writer.addAnnotation(field);
Rectangle rect2 = new Rectangle(40, 710, 200, 726);
TextField neg = new TextField(writer, rect2, "value2");
neg.setBorderColor(GrayColor.GRAYBLACK);
neg.setBorderWidth(0.5f);
writer.addAnnotation(neg.getTextField());
document.close();
}
Note that I used a Blur action. This means the method will be triggered as soon as you select another field after filling out the value1 field.
Related
I have an HTML document which contains this text somewhere in it
function deleteFolder() {
var mailbox = "CN=John Urban,OU=Sect-1,DC=TestServer ,DC=acme,DC=com";
var path = "/Inbox/";
//string of interest: "CN=John Urban,OU=Sect-1,DC=TestServer ,DC=acme,DC=com"
I just want to extract this text and store it in a variable in C#. My problem is that string of interest will slightly change each time the page is loaded, something like this:
"CN=John Urban,OU=Sect-1,DC=TestServer ,DC=acme,DC=com"
"CN=Jane Doe,OU=Sect-1,DC=TestServer ,DC=acme,DC=com"
etc....
How do I extract that ever changing string, without regular expression?
Is it always a function deleteFolder() which has its first line as var mailbox = "somestring"? And you are interested in somestring?
Based on the requirements you told us, could just search your string containing the HTML for var mailbox =" and then the next " and take all text between these two occurrences.
var htmlstring= "..."; //
var i1 = htmlstring.IndexOf("var mailbox = \"");
var i2 = i1 >= 0 ? htmlstring.IndexOf("\"", i1+15) : -1;
var result = i2 >= 0 ? htmlstring.Substring(i1+15, i2-(i1+15)): "not found";
VERY, VERY ugly, not maintainable, but without more information, I can't do any better. However Regex would be much nicer!
Hello I'm yet again stuck on d3...
I'd like to know how to use a thousand seperator on a variable all the examples I've managed to find seem to be on static data.
This is what I've tried so far:
d3.csv("OrderValueToday.csv", function(obj) {
var text = 'Today = £';
var totalSales = text + d3.format(",") + obj[0].Today;
svgLabel = d3.select("#label").append("h2")
.text (totalSales);
});
However it just outputs a load a stuff on the webpage this is it:
Today = £function (n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a; if(0>p){var c=Zo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}20000
So all I want is to be able to make the totalSales value have thousand separators so like 20,000 everything else I've tried doesnt do anything. I've read this https://github.com/mbostock/d3/wiki/Formatting but didnt see what I could do for my scenario.
Any help would be greatly appreciated. Cheers
Specifying a d3.format returns a formatting function, which you must then call as a function, passing in the number to be formatted as an argument:
var myNumber = 22400;
d3.format(',')(myNumber); // returns '22,400'
Sometimes you will see a format function stored as a variable like this:
var commaFormat = d3.format(',');
commaFormat(1234567); // returns '1,234,567'
In your case, you could do the following:
var totalSales = text + d3.format(',')(obj[0].Today);
I am having to pickup from where someone in the business left off many years ago with an aging texting system.
It was built using ASP classic and sends a string to an API that then texts out, all this is neither here nor there. The problem i have is no JS experience, I am am a SQL Developer and did a little bit of ASP Classic (VBScript) years ago.
This piece of JScript picks up information from several form boxes and then places them in a string which is then passed to variable on a processing page to text out. The fields 'QValue, Indemnity and Excess' are all numeric. The Cover is text and it is replacing the cover text with 'NaN' now I understand this is for 'Not A Number' well that is exactly what it is, not a number but I want the text string.
Here is the snippet of code in question:
<script type="text/javascript">
function changeMessageText()
{
var messagetxt = document.getElementById('message').value
var QValue = document.getElementById('QValue').value
var Cover = document.getElementById('Cover').value
var Excess = document.getElementById('Excess').value
var Indem = document.getElementById('Indemnity').value
var messagetxt=messagetxt.replace("[QValue]", + QValue)
var messagetxt=messagetxt.replace("[Cover]", + Cover2)
var messagetxt=messagetxt.replace("[Excess]", + Excess)
var messagetxt=messagetxt.replace("[Indem]", + Indem)
document.getElementById('messageText').innerHTML = messagetxt;
}
</script>
Cheers.
When you do string.replace(searchvalue,newvalue), there is no need of + before the newValue
var messagetxt=messagetxt.replace("[QValue]", QValue)
//cover or cover2 whichever appropriate
var messagetxt=messagetxt.replace("[Cover]", Cover)
var messagetxt=messagetxt.replace("[Excess]", Excess)
var messagetxt=messagetxt.replace("[Indem]", Indem)
Is it normal that you use Cover2 in the replace where you read the input value and store it in the Cover variable ?
Those are two different variables and from the code you provided, we can only assume that Cover2 is initialized with NaN (which might not be the case, it can be copy/paste error).
Here is how you do it:
var messagetxt = document.getElementById('message').value;
var QValue = document.getElementById('QValue').value
var Cover = document.getElementById('Cover').value
var messagetxt=messagetxt.replace("[QValue]", QValue)
var messagetxt=messagetxt.replace("[Cover]", Cover)
document.getElementById('messagetxt').innerHTML = messagetxt;
Here is a working example of this: http://jsfiddle.net/F24cr/
Enjoy
I'm struggling with a ExtJS 4.1.1 grid that has editable cells (CellEditing plugin).
A person should be able to type a mathematic formula into the cell and it should generate the result into the field's value. For example: If a user types (320*10)/4 the return should be 800. Or similar if the user types (320m*10cm)/4 the function should strip the non-mathematical characters from the formula and then calculate it.
I was looking to replace (or match) with a RegExp, but I cannot seem to get it to work. It keeps returning NaN and when I do console.log(e.value); it returns only the originalValue and not the value that I need.
I don't have much code to attach:
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
console.log(str);
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
var numCalc = Number(eval(strCalc));
console.log(numCalc);
return numCalc;
},
Which returns: str=321 strCalc=null numCalc=0 when I type 321*2.
Any help appreciated,
GR.
Update:
Based on input by Paul Schroeder, I created this:
onGridValidateEdit : function(editor,e,opts) {
var str = e.record.get(e.field).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
console.log(typeof numCalc);
console.log(numCalc);
return numCalc;
},
Which calculates the number, but I am unable to print it back to the grid itself. It shows up as "NaN" even though in console it shows typeof=number and value=800.
Final code:
Here's the final code that worked:
onGridValidateEdit : function(editor,e,opts) {
var fldName = e.field;
var str = e.record.get(fldName).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
e.record.set(fldName,numCalc);
},
Lets break this code down.
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
What listener is this code being used in? This is very important for us to know, here's how I set up my listeners in the plugin:
listeners: {
edit: function(editor, e){
var record = e.record;
var str = record.get("your data_index of the value");
}
}
Setting it up this way works for me, So lets move on to:
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
at which point strCalc=null, this is also correct. str.match returns null because your regex does not match anything in the string. What I think you want to do instead is this:
var strCalc = str.replace(/[^0-9+*-]/g, "");
console.log(strCalc);
This changes it to replace all characters in the string that aren't your equation operators and numbers. After that I think it should work for whole numbers. I think that you may actually want decimal numbers too, but I can't think of the regex for that off the top of my head (the . needs to be escaped somehow), but it should be simple enough to find in a google search.
I have the following code in an html page in a Javascript tag:
var adOpenDynamic = 2
var adLockOptimistic = 3
var conn_str = 'Provider=Microsoft.Jet.OLEDB.4.0; Data Source=G:/path_to_myDB.mdb'
var conn = new ActiveXObject("ADODB.Connection")
conn.open(conn_str)
and this is a the beginning of a function that is called from the onload event of the html :
var PassNbrAppel = new Array();
var i=1
var rsPass = new ActiveXObject("ADODB.Recordset")
SQLpass = 'SELECT Avis.[Numéro Passerelle], Count(Avis.[Numéro Passerelle]) AS [CompteDeNuméro Passerelle] FROM Avis WHERE (((Avis.[Date Appel])>#10/19/2011# And (Avis.[Date Appel])<#11/07/2011#) AND (Avis.[Numéro Passerelle] IS NOT NULL)) GROUP BY Avis.[Numéro Passerelle] ORDER BY Val(Avis.[Numéro Passerelle]);'
rsPass.open(SQLpass, conn, adOpenDynamic, adLockOptimistic)
rs2arr(rsPass,arrPass)
rs.close()
I get the following error message (translated from french): "no value given for one or more of the required parameters" and the line number is pointing to rsPass.open(SQLpass, conn, adOpenDynamic, adLockOptimistic)
I keep on re-checking to see if there is a mistake in the code but I can't seem to find anything wrong...
I took bits of code from here
The problem was the special characters in my SQL statement. Instead of trying to make it work with the "é" I changed the feild names so they dont have special characters. So much for French pride...