Web application - Write To .txt file with Javascript FileObject.Write - javascript

I'm trying to re-purpose some older java script code that I use in order to create a text file via an intranet web app. The following code creates text files that are picked up and processed by a third party application running on the same device...
<script>
function WriteTransferFile(location) {
var fileSystemObject = new ActiveXObject("Scripting.FileSystemObject");
var fileObject = fileSystemObject.CreateTextFile("C:\\transfer\\transfer.txt", true);
fileObject.Write(location);
fileObject.Close();
return location;
}
</script>
<script id="writetransfer">
function writetransfer() {
var Location = document.getElementById('lblCommand');
var Command = Location.innerHTML;
WriteTransferFile(Command);
}
</script>
This works fine for a single text string to be pasted into a text file, but I now need to create a file which takes 4 different fields from the web page and writes them on to consecutive lines. I've played around with the above but any attempt to add a second line of text overwrites the first line instead creating a new one below it. Desired output...
Field 1
Field 2
Field 3
Field 4
Any ideas how I might accomplish this?
I'm aware this probably isn't the sleekest solution, but there are no concerns regarding the suppression of active X security settings as this is for a closed system with access to local intranet only.
Thanks
Steve

Related

Write to a PDF using JS (pdfform.js)

I need to make an update to a script that is using pdfform.js in order to take data from html inputs and pass them into a fillable pdf file.
Basically all I need to do is to update the PDF file for the year 2022.
The problem is that my new PDF doesn't have fields where I can write like the old one:
PDF that has fillable inputs:
old pdf
My new PDF:
new pdf
I tried to add fields to my new pdf using Adobe Acrobat but the script is not able to write to them. I don't know exactly how to add the fields in order to have the same reference as the old ones.
<script type = "text/javascript"
src = "pdfform.pdf_js.dist.js" > < /script>
< script > $(document).ready(function() {
$("#descarca-pdf").on("click", function() {
event.preventDefault();
var a = new XMLHttpRequest;
a.open("GET", "Formular-230_Habitat-for-Humanity-Romania-2.pdf", !0), a.responseType = "arraybuffer", a.onload = function() {
if (200 == this.status) {
var a = this.response,
e = {
cnp: [$("#form-cnp").val()],
initiala: [$("#form-initiala").val()],
prenume: [$("#form-prenume").val()],
numar: [$("#form-numar").val()],
nume: [$("#form-nume").val()],
scara: [$("#form-scara").val()],
etaj: [$("#form-etaj").val()],
apartament: [$("#form-apartament").val()],
bloc: [$("#form-bloc").val()],
judet: [$("#form-judet").val()],
localitate: [$("#form-localitate").val()],
codpostal: [$("#form-codpostal").val()],
email: [$("#form-email").val()],
telefon: [$("#form-telefon").val()],
strada: [$("#form-strada").val()],
fax: [$("#form-fax").val()]
},
o = pdfform().transform(a, e),
t = new Blob([o], {
type: "application/pdf"
}),
r = document.createElement("a");
r.href = window.URL.createObjectURL(t), r.download = "Formular_230_Habitat_for_Humanity_Romania.pdf", r.click()
} else on_error("failed to load URL (code: " + this.status + ")")
}, a.send()
})
}); < /script>
Does anyone know any tool that I can use for this?
As far as I can tell you are trying to update a Government Form 230 which used to look like this
And you say you need to update those field for this year HOWEVER the Current Form uses a totally different structure, like this
Here we can see the difference in the two sets of field tags
The XFDF data fields structure as published can be found at
https://static.anaf.ro/static/10/Anaf/Declaratii_R/AplicatiiDec/structura_B230_D230_2020_27032020.pdf
and https://static.anaf.ro/static/10/Anaf/Declaratii_R/AplicatiiDec/structura_B230_D230_2022_12012022.pdf
The forms structure may be used for customised versions with a java library and both years forms have their own personalized .jars for each structure, so it is best to use the official ANAF J Soft available online.
You provide a sample of a modified custom version which has been dumbed down to be part flattened and part not ! thus to my view would not be compatible with your declaration it must match the government XFA format, however it was initially generated or modified using Adobe Forms Library Code, so has working fields in one part area, but they are not XFA structure like the official ANAF version they are declared as "You cannot save data...Please print..." to be simply printed and scanned as if it was a basic paper copy without intelligent fields, which defeats the whole reason for it being a fillable form in the first place. You may just as well use a word doc or any other editor form.
OK on looking through many different modified D230's including yours they seem to be from the same source "Codruţ Popa" who I assume is an ANAF designer so best to get a newer copy from them.

Get Element available under Dev Tools -> Resources -> Frames

I'm trying to do this by using a Tampermonkey Script. However I'm open to new approaches...
What I want to do is extract some data (data-video), from a specific <div>. However this data is not available under the HTML code of the page, but it's available under Dev Tools -> Resources and then on Frames.
Anyone knows if it's possible to get that information available under DevTools? And how can I do that?
Comparative between the two pages can be found here: "Original HTML PAGE" and "HTML PAGE under DevTools"
On the first hyperlink the id=video-canvas cannot be seen, however it's on the <object type="application/x-shockwave-flash(...)
As you state in your question the data you're looking for is available in DevTools under the "Resources" tab in the "Frames" folder. What you are looking at there is the Source HTML, similar to View Source.
The code you want, is what is getting replaced. It appears the site is using the JW Player Plugin, which is replacing the <div id="video-canvas"> with the appropriate HTML for the device / browser detected to play the video. With all of my browsers on my Mac, they are being forced to use the Flash, even when it's disabled. When using my iPhone, which can't play flash , and inspecting the page it uses JW's own custom video element. It appears that it must be storing the file location in memory since it is not in the generated markup.
I am able to run through the console in the dev tools and access their JS class. It appears i can call jwplayer._tracker , which has an object b . Object b has an object AlWv3iHmEeOzwBIxOUCPzg This object seems to be consistent each time i check between different browsers, you can use the for loop inmy first example to get the correct value but tirmming it down to .b Following that object is e and in e is the object http://i.n.jwpltx.com/v1.... really long string that appears to contain a url, so it will need to parsed.
So to get the HTML string i ran
for ( var loc in jwplayer._tracker.b.AlWv3iHmEeOzwBIxOUCPzg.e){
loc
}
so if we put that in a function to parse the string and return a value
function getSubURL(){
var initURL;
for ( var loc in jwplayer._tracker.b.AlWv3iHmEeOzwBIxOUCPzg.e){
initURL = loc;
}
//look for 'mp4:' this is in front of the file path
var start = initURL.indexOf("mp4%3A");
//look for the .mp4 for the end of the file name
var stop = initURL.indexOf(".mp4");
//grab the string between
//start+6 to remove characters used to find it
//and stop+4 to include characters used to find it
var subPath = (initURL.substring((start+6),(stop+4))).split("%2F").join("/");
return subPath;
}
//and run it
getSubURL();
it will return ciencia/astronomia/fimsol.mp4
you can run this from your console, but I am unaware of how you can use this in Tamper Monkey, but i think it gets ya a lot closer to what you wanted.
This is the approach I've used to solve my problem... I couldn't grab the code I want under Dev Tools, but I find a way to get the data from jwplayer with the function getPlaylistItem. And this is how I get the url filename of each video:
function getFilename(filename) {
var filename;
if(jwplayer().getPlaylistItem){
filename = jwplayer().getPlaylistItem()['file'];
}
else{
return filename;
}
filename = filename.substring(filename.indexOf("/mp4:") + 5);
return filename;
}

WP8 App misbehaving due to StreamWrite in JavaScript

I would like to save the results calculated on html page in a textfile using javascript.
<script type="text/javascript">
window.onload = function () {
var sw : StreamWriter = new StreamWriter("HTML_Results.txt");
sr.Write('xyz");
*** calculations ******
sr.Write (result);
}
</script>
by doing this, my WP8 App is misbehaving and not displaying images as usual. This app is an Image Fader (calculates FPS).
Also tried:
StreamWriter sr;
try {
sr = new StreamWriter("\HTML5\HTMLResults.txt");
sr.Write("xyz");
File.SetAttributes("HTML5\HTMLResults.txt", FileAttributes.Hidden);
} catch(IOException ex) {
console.write ("error writing"); //handling IO
}
The aim is to:
Extract calculated values of several html pages(after getting loaded
one by one) in a single text file.
A Resultant HTML that reads this
text file and displays results in a tabular format.
Is there a better way to this job or the above can be rectified and used? Appreciate help.
Perhaps I've misunderstood your code but it looks like you're trying to write Java within JavaScript scripting tags. You cannot write Java in an HTML document. As far as I know, client-side JavaScript (which given your <script> tags is I guess what you're trying to write) can't perform the kind of file I/O operations you seem to want here.
You need to use Node JS to use JavaScript for something like that and then you're talking server-side. The closest you can get on client-side is using the new localStorage feature in HTML5 (not supported by all browsers).

How to implement printing in web application

In my desktop application, I developed text-based reporting and printing through a batch file because the printing is in bulk size and some times we have to restrict printing a single copy like Fixed Deposit Receipts etc. We are using lqdsi 5235 dot-matrix printers working file. Present desktop application process as follows:
The Batchfile is like this:
Name of the Batchfile: Dosprint.bat
Type %1 > prn
For Network printing:
Name of the Batchfile: Netprint.bat
Type %1 > \\SharedComputer\SharedPrinterName
And in application I redirect the printing as follows
Public Function printFile(ByVal mFileNamePath As String) As Boolean
Shell(Application.StartupPath & "\Printer\dosprint.bat " & mFileNamePath, AppWinStyle.Hide)
Return True
End Function
Printing value is very high and thousands of papers to be print some times. It is very safe and I can control No.of copies and everything like Fixed Deposit Receipts etc.
Help me if there any way to implement the same process in web application.
if you mean how to run your batch file from a web application, you can do something like this:
System.Diagnostics.Process.Start(file.FullName) //where file is a FileInfo class
As long as the file is reachable by your web application (for instance located inside the bin folder) and
The account on which your app is running has sufficient permissions to execute the file.
UPDATE:
The proper way to handle printing scenarios is to create a page that renders the content in a simple and easy way to be printed.
For example, using a simple table for tabulated data, use white color for most of the presentation to avoid spending print cartridges unnecesarily, pictures that matches your needs in specific sizes like A4 or letter, etc. Then you can call this function in the body tag:
<body onload="window.print();">
<!--content specially designed for proper printing -->
</body>
Thanks to Mr. SachinKumar K, for his article FILE HANDLING AT CLIENT SIDE USING JAVASCRIPT in WWW.CODEPROJECT.COM. In this article he mentioned that the website has to be added to the trusted site list so that the ActiveX object can be created and run.
To the dos print, I followed the below system to get dos based printing from my website on client systems dot-matrix printer.
Configuration on client System: (Internet Explorer/browser configuration)
Open Internet Explorer --> Tools --> Internet Options -->Security (tab).
add the SERVER URL in Trusted Sites
Note: uncheck "Required server verification (https:) for all sites in this zone (if your website is not HTTPS) to allow addition the site.
Next enable ActiveX controls and Plug-ins using Custom Level Tab on the same page
//create a batch file ex: printme.bat. And type the following command in the batch file.
Type %1 > prn
//The Batch file contain only one command line as above. You may change prn keyword to LPT1 or shared printer like \system_name\printer
//If required, Grant IIS_IUSRS, IUSR permission to the folder contains the printme.bat file to access by the browser.
Web Page Tags definition and javascript implementation:
// use PRE tag. It stores raw data (ASCII) in un-formatted manner
<pre id="predata" runat="server" style="display:none;"></pre>
<asp:Button Text="Print Report" runat="server" ID="btnprint" Width="101px" CssClass="buttonstyle" BackColor="DarkSlateGray" ForeColor="Aqua" OnClientClick="dosprint()" />
<%-- JAVA SCRIPT FOR PRINTING --%>
<script>
function dosprint () {
var fso, tempfile,mdata;
var fname = { key: 'value' };
fso = new ActiveXObject("Scripting.FileSystemObject");
function CreateTempFile(fname) {
var tfolder, tfile, tname, fname, TemporaryFolder = 2;
tfolder = fso.GetSpecialFolder(TemporaryFolder);
tname = fso.GetTempName();
fname.key = tfolder + '\\' + tname;
tfile = tfolder.CreateTextFile(tname);
return (tfile);
}
tempfile = CreateTempFile(fname);
mdata = document.getElementById('<%= predata.ClientID %>').innerText;
tempfile.writeline(mdata);
tempfile.close();
objShell = new ActiveXObject("WScript.Shell");
comspec = objShell.ExpandEnvironmentStrings("%comspec%");
objExec = objShell.Exec('c:\\temp\\printme.bat ' + fname.key);
// give double back slash to get a back slash in path
}
</script>
In the above code the PRINTME.BAT batch file is exist on client systems c:\temp directory.
The above system is worked for me.
Thanks everybody and happy coding.

Using javascript to rename multiple HTML files using the <TITLE></TITLE> in each file

I have used HTTRACK to download Federal regulations from a government website, and the resulting HTML files are not intuitively named. Each file has a <TITLE></TITLE> tag set, that would serve nicely to name each file in a fashion that will lend itself to ebook creation. I want to turn these regulations into an ebook for my Kindle, so that I can have the regulations readily available for reference, rather than having to carry volumes of books with me everywhere.
My preferred text/hex editor, UltraEdit Professional 15.20.0.1026, has scripting commands enable through embedding of the JavaScript engine. In researching possible solutions to my problem, I found xmlTitleSave on the IDM UltraEdit website.
// ----------------------------------------------------------------------------
// Script Name: xmlTitleSave.js
// Creation Date: 2008-06-09
// Last Modified:
// Copyright: none
// Purpose: find the <title> value in an XML document, then saves the file as the
// title.xml in a user-specified directory
// ----------------------------------------------------------------------------
//Some variables we need
var regex = "<title>(.*)</title>" //Perl regular expression to find title string
var file_path = UltraEdit.getString("Path to save file at? !! MUST PRE EXIST !!",1);
// Start at the beginning of the file
UltraEdit.activeDocument.top();
UltraEdit.activeDocument.unicodeToASCII();
// Turn on regular expressions
UltraEdit.activeDocument.findReplace.regExp = true;
// Find it
UltraEdit.activeDocument.findReplace.find(regex);
// Load it into a selection
var titl = UltraEdit.activeDocument.selection;
// Javascript function 'match' will match the regex within the javascript engine
// so we can extract the actual title via array
t = titl.match(regex);
// 't' is an array of the match from 'titl' based on the var 'regex'
// the 2nd value of the array gives us what we need... then append '.xml'
saveTitle = t[1]+".xml";
UltraEdit.saveAs(file_path + saveTitle);
// Uncomment for debugging
// UltraEdit.outputWindow.write("titl = " + titl);
// UltraEdit.outputWindow.write("t = " + t);
My question is two-fold:
Can this JavaScript be modified to extract the <TITLE></TITLE> contents from an HTML file and rename the files?
If the JavaScript cannot be modified easily, is there a script/program/black magic/animal sacrifice that can accomplish the same thing?
EDIT:
I have been able to get the script to work as desired by removing the UltraEdit.activeDocument.unicodeToASCII(); line and changing the file extension to .html. My only issue now is that while this script works on single open files, it does not batch process the directory.
You can use just about any "scriptable" language to do something like this pretty quickly. Ruby is my favorite:
require 'fileutils'
dir = "/your/directory"
files = Dir["#{dir}/*.html"]
files.each do |file|
html = IO.read file
title = $1 if html.match /<title>([^<]+)<\/title>/i
FileUtils.mv file "#{dir}/#{title}.html"
puts "Renamed #{file} to #{title}.html."
end
Obviously if your UltraEdit script worked for you this might be obtuse, but for anybody running a different env, hopefully this is useful.
Does this not work out of the box?
I don't know anything about UltraEdit, but as far as a regex engine is concerned, if it can parse <title>(.*)</title> out of an XML document, it can do the exact same for HTML.
Just modify the final file title to .html instead of .xml
saveTitle = t[1]+".html";
Assuming you can get that script to work as it's intended (point being I don't know UltraEdit), I'm pretty confident that same process will work for HTML.
XML and HTML are both plain text, and that script is simply running a regular expression on the text to extract the title tags, which are the same in both; the only thing you need to do is change this line:
saveTitle = t[1]+".xml";
to this:
saveTitle = t[1]+".html";
After much searching and trial and error on the scripting side, I ran across a fantastic program for Windows that will do the renaming via TITLE tags: Flexible Renamer 8.3. The author's website is http://hp.vector.co.jp/authors/VA014830/english/FlexRena/, and it manages to handle every bit of what I needed. Many thanks to #coreyward and #Yuji for their fantastic advice on the scripting end of things.

Categories