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.
Related
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
In addition to the question here:
Open Explorer window from Website
I'm also having trouble with this, especially because I need to integrate a function into the link that eventually will open in file explore.
Bacially, we have a very simple intranet webpage, to control our cases etc.
Each case has some files in in a folder on the server, but to avoid to many subfolders in one folder, we split them in groubs of 200!
\ip\fileserver\cases\"split-folder"\subfolder
I what to open the folder clicking on the case on our webpage.
The split-folder..is defined in ranges with case-numbers for evey 200 cases (sager in danish)
Like this
\25000-25199\25001
\25200-25399\25399
\25400-25599\25422 or 25555 etc . .
The math to calculate the "split-folder" is simple enough with a script but getting this into a link that will open file explore is not that easy.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction(25555)">Try it</button>
<p id="sagslink"></p>
<script>
function myFunction(sagnr) {
var a = Math.floor(sagnr/200)*200
var b = Math.floor(a+199);
var x = "file://///192.168.15.133/Filserver2016/sager/" + a + '-' + b + "/"+sagnr;
document.getElementById("sagslink").innerHTML = x;
}
</script>
Simple link that Works in IE..but not in firefox og chrome.
sager-full-path
But I can not generate a useful link merging the to!
I have tried evey possible way described here to no awail:
JavaScript function in href vs. onclick
Perhaps I need to revice the function to give the actual link in sted. I also don't what a button but just a generat CASE-Number...that serves as link!
Further more! We mount \\192.168.1.133\Fileserver2016 as Z:
So for our various programs, that use the Z drive path, I would like to open file-explore with the mount path and not the ablosoute path.
We can use IE if nessarry..but I would like i to work on firefox and chrome also
Can this be done!
Ok. So we got it working...sort of ;O)
Our intranet webpage runs in ASP
So the code runs serverside.
Here is the code that works in IE-11.
<%
strSagsNR = rsSag("sagsNR")
Function folderlink(FSagsNR)
a = int(strsagsNR/200)*200
b = int(a+199)
folderlink = "file:///Z:/sager/" & a & "-" & b & "/" & strSagsNR
End Function[enter image description here][1]
%>
To ensure the solution works properly locally and when connected with VPN.
It's necessary to add the server ip to IE-11 Internet security - local Intranet - Webplaces - Advanced
as BOTH FILE AND HTTP! See image.
Security setting in IE
Then you should avoid the remark about this file is dangerous and may harm you computer, and File explore will pop up on the correct path ;O)
I have not found any solution for Chrome or Firefox.
i'm trying to migrate from feedly as it is unacceptable (at least to me) that a search query is (fully) enabled only by a pro version.
Anyhow, to export my lengthy list of "saved for later" i found some lovely scripts:
Simple script that exports a users "Saved For Later" list out of Feedly as a JSON string and feedly-to-pocket. where i am instructed to:
You must switch off SSL (http rather than https) or jQuery won't load!
so i though i did by adding (ubuntu 14.04/chrome 40 x64)
--ssl-version-min=tls1
to my /usr/share/applications/google-chrome.desktop file (all lines starting with Exec=). However when i try to run it in the browser console i get
This request has been blocked; the content must be served over HTTPS.
So, any suggestions? (also, excuse me for noobness)
Go to your Feedly "saved" list and scroll down until all articles have loaded.
Open console and paste the following Javascript into it:
function loadJQuery() {
script = document.createElement('script');
script.setAttribute('src', '//code.jquery.com/jquery-2.1.3.js');
script.setAttribute('type', 'text/javascript');
script.onload = loadSaveAs;
document.getElementsByTagName('head')[0].appendChild(script);
}
function loadSaveAs() {
saveAsScript = document.createElement('script');
saveAsScript.setAttribute('src', 'https://cdn.rawgit.com/eligrey/FileSaver.js/5733e40e5af936eb3f48554cf6a8a7075d71d18a/FileSaver.js');
saveAsScript.setAttribute('type', 'text/javascript');
saveAsScript.onload = saveToFile;
document.getElementsByTagName('head')[0].appendChild(saveAsScript);
}
function saveToFile() {
// Loop through the DOM, grabbing the information from each bookmark
map = jQuery(".entry.quicklisted").map(function(i, el) {
var $el = jQuery(el);
var regex = /Published:(.*)(.*)/i;
return {
title: $el.attr("data-title"),
url: $el.attr("data-alternate-link"),
summary: $el.find(".summary")[0].innerHTML,
time: regex.exec($el.find("span.ago").attr("title"))[1]
};
}).get(); // Convert jQuery object into an array
// Convert to a nicely indented JSON string
json = JSON.stringify(map, undefined, 2);
var blob = new Blob([json], {type: "text/plain;charset=utf-8"});
saveAs(blob, "FeedlySavedForLater" + Date.now().toString() + ".txt");
}
loadJQuery()
Source: Feedly-Export-Save4Later
Not javascript but here is how I saved a html page with all the links and excerpts...
Open the saved pages in feedly in chrome
scroll down so they are all there
inspect any element (the top article is a good choice) so it opens the generated html
find the div id="section0_column0" node
right-click & copy it
paste into Notepad++
this html is untidy so carry on...
Do a Regex find & replace
find: (?s)<div id=.+?_main.+?>.+?(<a href=")(.+?)(").+?sans-serif">(.+?)</span>.+?</div>.+?</div>.+?</div>
replace: <div>$1$2$3>$2</a></div> <div> $4<br /> <br /></div>
save the html page.
open it in Chrome
Posted the question in the jquery forum and the solution was rather simple (remove http from attribute string)
line 34 should be
script.setAttribute('src', '//code.jquery.com/jquery-latest.min.js');
So to close the loop - for a full searchable/archived list of links not only by title/url but context also(!) you can:
Follow the instructions in https://github.com/ShockwaveNN/feedly-to-pocket (with the correction suggested by kind stranger jakecigar and you also have to register a pocket app (obtain consumer key) for the ruby script to work)
Export html list from your pocket account
Import pocket list to a Kifi library
and at last feedly-free with my personal search engine
I know I'm a bit late to the party but Ive been hunting around for a few days to find a reasonably simple solution. None of which have been listed clearly or concisely on stack overflow or elsewhere on the web. I have in fact found a much easier way to do this.
Use this java script from this Gist just as it instructs https://gist.github.com/ShockwaveNN/a0baf2ca26d1711f10e2 (Note this is referenced above and found through the link #gep shared in step one)
Once the JS as completed running it will download a text file. (It does still run successfully and on large numbers, I just exported almost 2500 articles)
Create a blank test.json in SublimeText.
Copy all entries from your exported text file into this json file
Weirdly it does seem you need to copy and past as I tried just renaming the text file and when I did that I received errors on the next step
Make sure you are signed into pocket
Go here: https://getpocket.com/import/springpad
Select your newly created test.json
Upload
Note: On large uploads the import page fails to refresh (this did not seem to be an issue as all my articles did make it into my account)
This allows you to directly upload json into your pocket account. Thus no more messing around with random supposed other fixes. I hope this make it a lot easier for everyone in the future.
The title of this question may be slightly misleading, but I'm not sure what the best title would be (since I can't guess at a solution yet).
Basically the system I am developing relies heavily on canvas graphs. These graphs are generated through javascript, and are made using data pulled via ajax from an API server.
The tricky part is, I'd like to be able to email these graphs to users of this system, without them actually having to go to the web page at all. So while I'm aware that it is possible to get the Base64 value of an image generated with javascript in a browser, what about if no one is there to run that javascript?
I'd like to keep the graphs generated in javascript/canvas, rather than making them in a common server-side graphics library (GD, ImageMagick). The Canvas graphs are dynamic, and allow for interaction via javascript. Though I don't want that functionality in the email notification, I do want them to be identical otherwise (at least in appearance).
So the question is, how can I get these graphs into an email?
At this point, my only guess is that I'd need to literally make a website that does AJAX requests for "graphs to render", renders these graphs, and sends the results to the server. Then I'd need a "server" that just sits there on that web page and churns out graphs. Is that the only solution here?
I used phantomJs (like node.js but different) serverside to run exactly the same code as client side, and get the same result. all you need is one single exe-file (like a webkit stand alone web brower)
The following program (in Perl, but should be feasible to translate to you favourite language) takes some data, inserts into a web-page (could be ajax'ed) and either sends that web page to the client, or stores it as a temporary file, and starts PhantomJs on the same page. Then ask PhantomJs to generate a jpg, that is then picked up (and in this case sendt to the client).
#!/usr/bin/perl
use strict;
use File::Temp;
$|=1;
#this script returns a graph, either as html +js web page to render client side,
#or renders the same page server side, and returns the jpg image.
#files needed:
#.\phantom_srv_client.pl #this script
#.\phantomjs.exe #the webkit runtime stand alone file, from http://phantomjs.org/
#.\Scripts\excanvas.min.js #canvas simulator for IE8-
#.\Scripts\jquery.min.js #jQuery as we know it
#.\Scripts\jquery.jqplot.min.js #graph library on top of jQuery from http://www.jqplot.com/ (Flot or any can be used)
#do we want client side rendering (html + js), or server side rendering (jpg)
#jpg seems to render nicer than png on some pages?
use CGI;
my $show_as_jpg = CGI::param("jpg");
#path to javascript libraries (jQuery etc).
#Must be absolute file location for server rendering, relative for web
use FindBin;
my $script_path = $show_as_jpg
? $FindBin::Bin."/Scripts"
: './Scripts';
#data to send to graph (two sets)
my $data = [[2,5,4], [6,4,5]];
#use json to get this as a javascript text
my $json_data;
eval {require JSON; $json_data=JSON::to_json($data)};
#in case JSON is not installed, get the json/javascript data manually (just for demo)
$json_data ||= "[[2,5,4], [6,4,9]]"; #here 9 at the end to see a difference
#The following is the web page that renders the graph, client or server side
#(links to scripts must be abolute to work serverside, as temp-files may go anywhere, $script_path keeps track of that)
#$json_data is the Perl data structure converted to JSON (aka javascript, but not)
my $graph_html =qq|
<!DOCTYPE html>
<html>
<head>
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="$script_path/excanvas.min.js"></script><![endif]-->
<script class="include" type="text/javascript" src="$script_path/jquery.min.js"></script>
<script class="include" type="text/javascript" src="$script_path/jquery.jqplot.min.js"></script>
<script class="code" type="text/javascript" language="javascript">
jQuery(document).ready(function(){
/*data from perl (\$json_data) inserted here */
var data = $json_data;
jQuery.jqplot("chart1", data );
});
</script>
</head>
<body>
<div id="chart1" style="width:600px; height:400px;"></div>
<a href='?jpg=1'>View as jpg</a>
</body>
</html>
|;
#this is the javascript that tells PhantomJs what to do (ie open a doc and render it to bitmap)
my $phantom_doc_js =qq|
var system = require('system');
//read from commandline which files to open, and write to
var open_doc = system.args[1];
var return_doc = system.args[2];
var page = require('webpage').create();
page.open(open_doc, function () {
page.render(return_doc);
phantom.exit();
});
|;
#see if we shall render this page serverside
if ($show_as_jpg) {
#get temporary filenames with related file handlers
#where to put phantomjs script (generic so could be a static file)
my ($phantom_doc_filehandler, $phantom_doc_filename) = File::Temp::tempfile( SUFFIX => '.js', TMPDIR => 1);
#where to put web page with data to render and ref to javascripts etc
my ($phantom_graph_filehandler, $phantom_graph_filename) = File::Temp::tempfile(SUFFIX => '.html', TMPDIR => 1);
#also get a filename with no handler, so phantomjs can return the jpg file. Extention must be .jpg!
my (undef, $image_filename) = File::Temp::tempfile( SUFFIX => '.jpg',TMPDIR => 1, OPEN => 0);
#store file content and close files
print $phantom_doc_filehandler $phantom_doc_js; close $phantom_doc_filehandler;
print $phantom_graph_filehandler $graph_html; close $phantom_graph_filehandler;
#now call PhantomJs with filenames to read from and write to.
#Next version should support piping, which would simplify a lot
#use absolute path to phantomjs.exe in case web-server does not use current path
system($FindBin::Bin.'\\phantomjs', $phantom_doc_filename, $phantom_graph_filename, $image_filename) == 0
or die "system failed: $?";
#read the entire image file
my $img = slurp_file($image_filename);
print "Content-Type: image/jpeg\nPragma: no-cache\n\n".$img;
#The temp files are no more needed
unlink $phantom_doc_filename, $phantom_graph_filename, $image_filename;
} else { # just render client side
print "Content-Type: text/html\nPragma: no-cache\n\n".$graph_html;
}
#slurp is not always std perl
sub slurp_file{
my $filename = shift;
my $string;
local $/ = undef;
open FILE, $filename or die "Couldn't open file: $!";
binmode FILE;
$string = <FILE>;
close FILE;
return $string;
}
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.