The following is the CScript script I use for the programmatic printing of a Word document.
var err = 0;
var app = WScript.CreateObject("Word.Application");
try {
var filename = WScript.Arguments(0);
var enc = (filename.toLowerCase().indexOf(".txt") >= 0) || (filename.toLowerCase().indexOf(".htm")) ? 65001 : 1252;
var objDoc = app.Documents.Open(filename, false, true, false, " ", " ", false, " ", " ", 0, enc, true, false, 0, true);
objDoc.PrintOut(false, false, 0, "", "", "", 0);
} catch (e) {
err = 1;
} finally {
app.Quit(0);
}
WScript.Quit(err);
How can I modify it to prevent the spooling dialog box from being displayed? (Is this even possible?) A screen capture of what I mean by "spooling dialog box" is at http://imgur.com/qqtib.png.
We used to do a very similar type of thing when trying to print Word documents. We now use Aspose.Words for .NET. It works great. Much more control over printing without the problems of loading word.
Related
I found below code and trying to modify it to print an specific div element. Below code opens print dialog but shows empty screen. I dont know where to put my id of div element in the code.
print(){
var doc = new jsPDF("portrait", "mm", "a4");
doc.autoPrint();
const hiddFrame = document.createElement('iframe');
hiddFrame.style.position = 'fixed';
// "visibility: hidden" would trigger safety rules in some browsers like safariļ¼
// in which the iframe display in a pretty small size instead of hidden.
// here is some little hack ~
hiddFrame.style.width = '1px';
hiddFrame.style.height = '1px';
hiddFrame.style.opacity = '0.01';
const isSafari = /^((?!chrome|android).)*safari/i.test(window.navigator.userAgent);
if (isSafari) {
// fallback in safari
hiddFrame.onload = () => {
try {
hiddFrame.contentWindow.document.execCommand('print', false, null);
} catch (e) {
hiddFrame.contentWindow.print();
}
};
}
var blob = doc.output("blob");
window.open(URL.createObjectURL(blob), '_blank');
}
Im using this cordova plugin:
https://github.com/katzer/cordova-plugin-printer
$ionicPlatform.ready().then(function () {
var printerId = $scope.printData.printerUrl;
alert('print to: ' + printerId);
cordova.plugins.printer.pick(function(printerId) {
cordova.plugins.printer.print("<p>TEST PRINT</p>", { printerId: printerId, bounds:[20, 20, 0, 0] });
});
});
I want to know how to print directly to printer without any popup.
Using ng-cordova printer, this code prints directly to printer.
Make sure you have correct printer url. something like "ipp://192.168.../ipp"
var htmlContent = "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>Title</title> <link href='css/print.css' rel='stylesheet' /></head><body><div>test print</div></body></html>"
var options = {
name: 'print-job', // printjob name
printerId: $scope.PrinterUrl, // network url of the printer to use (iOS only)
//duplex: false, // default true (double sided) (iOS only)
landscape: false, // default false (portrait)
graystyle: true, // prints black and white (default), but true has better performance
bounds: {left:0, top:0, width:0, height:0}, // size and position of the print view (iPad only)
hidePaperFormat: true,
border: false,
hidePageRange: true
};
$cordovaPrinter.print(htmlContent, options).then(function(msg){
console.log('Print Ok: ' + msg);
});
I'm Calling onchange function from HTML. It works as expected for the first time. But Second time, its not. Not even the debugger is getting hitted in the function.
HTML
#Html.TextBoxFor(m => m.Attachment.AttachmentFile, new { type = "file", onchange = "GetAttachmentFileName()", style = "display:none" })
JavaScript
function GetAttachmentFileName() {
$("#Filesize").hide();
if ($("#Attachment_AttachmentFile").val() != null && $("#Attachment_AttachmentFile").val() != "") {
var filename = $("#Attachment_AttachmentFile").val().split('\\').pop().replace(" ", "");
$("#Attachment_StorageName").val(filename);
$("#filename").val(filename);
$("#attachmentFileerror span").css("display", "none");
var fileSize=0;
var maxFileSize = 10240000 // 10MB -> 10000 * 1024
fileSize = $("#" + "Attachment_AttachmentFile")[0].files[0].size //size in kb
if(fileSize>maxFileSize){
$("#Filesize").html("Please choose file less than 10MB");
$("#Filesize").css("display", "block");
$('#filename').val('');
}
else{
$("#Filesize").css("display", "none");
}
}
else
$("#Attachment_StorageName").val("");
}
You may want to consider explicitly clearing out the contents of your file <input> when the file that was added was too large. This should reset the onchange() event so that it will trigger again (as it will only be triggered if the actual file name is different) :
if(fileSize>maxFileSize){
$("#Filesize").html("Please choose file less than 10MB");
$("#Filesize").css("display", "block");
$('#filename').val('');
$("#Attachment_AttachmentFile").val('')'
}
Users upload images to this form by dropping a file on it.
Is there a way in to trigger drop with a File/Blob object programmatically? Something like MouseEvent.initMouseEvent() https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent
but like initDropEvent?
I am researching here:
https://dxr.mozilla.org/mozilla-central/source/obj-x86_64-unknown-linux-gnu/_tests/testing/mochitest/mochijar/chrome/mochikit/content/tests/SimpleTest/ChromeUtils.js?offset=200#254
https://dxr.mozilla.org/mozilla-central/source/browser/base/content/test/newtab/head.js?offset=0#690
https://dxr.mozilla.org/mozilla-central/source/browser/base/content/test/newtab/browser_newtab_bug765628.js#25
https://dxr.mozilla.org/mozilla-central/source/testing/mochitest/tests/SimpleTest/ChromeUtils.js#179 ----- this one is a mochitest and code from mochitests never ever work for me, so i think this one is useless as it needs some special environment i think
Based on this I ran this code from scratchpad witha tab with twitter loaded, and aftre clicking the "tweet" button:
// https://dxr.mozilla.org/mozilla-central/source/browser/base/content/test/newtab/head.js?offset=100#690
//https://dxr.mozilla.org/mozilla-central/source/browser/base/content/test/newtab/browser_newtab_bug765628.js#21
/**
* Creates a custom drag event.
* #param aEventType The drag event's type.
* #param aData The event's drag data (optional).
* #return The drag event.
*/
function createDragEvent(aContentWindow, aEventType, aData, aDataType) {
// aDataType text/x-moz-url, text/plain, etc
let dataTransfer = new (aContentWindow).DataTransfer("dragstart", false);
dataTransfer.mozSetDataAt(aDataType, aData, 0);
let event = aContentWindow.document.createEvent("DragEvents");
event.initDragEvent(aEventType, true, true, aContentWindow, 0, 0, 0, 0, 0,
false, false, false, false, 0, null, dataTransfer);
return event;
}
function sendTwitterDropEvent() {
var aContentWindow = gBrowser.contentWindow;
var aContentDocument = aContentWindow.document;
var btnNewTweet = aContentDocument.getElementById('global-new-tweet-button');
console.info('btnNewTweet:', btnNewTweet);
if (!btnNewTweet) {
throw new Error('global tweet button not found, probably not logged in');
}
btnNewTweet.click();
var inputAddPhoto = aContentDocument.getElementById('global-tweet-dialog').querySelector('input[type=file]');
if (!inputAddPhoto) {
throw new Error('add photo button not found! i have no idea what could cause this');
}
var formTweet = aContentDocument.getElementById('global-tweet-dialog-dialog').querySelector('form'); //<form.t1-form.tweet-form has-preview has-thumbnail dynamic-photos photo-square-4>
if (!formTweet) {
throw new Error('tweet form not found! i have no idea what could cause this');
}
console.info('formTweet:', (formTweet instanceof Ci.nsIDOMNode));
var ifaceReq = aContentWindow.QueryInterface(Ci.nsIInterfaceRequestor);
var windowUtils = ifaceReq.getInterface(Ci.nsIDOMWindowUtils);
var aDragData = 'site 99';
var aDragDataType = 'plain/text';
var event = createDragEvent(aContentWindow, "drop", aDragData, aDragDataType);
windowUtils.dispatchDOMEventViaPresShell(formTweet, event, true);
}
sendTwitterDropEvent();
This should populate the tweet input with "site 99" but it doesnt. I was testing with plain text then after I get that working I was thinking of moving to File/Blob.
Simplified non-twitter test case
Open tab with this: data:text/html,<input id=rawr>
Open scratchpad and run this code from scratchpad:
function createDragEvent(aContentWindow, aEventType, aData, aDataType) {
// aDataType text/x-moz-url, text/plain, etc
let dataTransfer = new (aContentWindow).DataTransfer("dragstart", false);
dataTransfer.mozSetDataAt(aDataType, aData, 0);
let event = aContentWindow.document.createEvent("DragEvents");
event.initDragEvent(aEventType, true, true, aContentWindow, 0, 0, 0, 0, 0,
false, false, false, false, 0, null, dataTransfer);
return event;
}
function sendTwitterDropEvent() {
var aContentWindow = gBrowser.contentWindow;
var aContentDocument = aContentWindow.document;
var formTweet = aContentDocument.getElementById('rawr');
if (!formTweet) {
throw new Error('tweet form not found! i have no idea what could cause this');
}
console.info('formTweet:', (formTweet instanceof Ci.nsIDOMNode), formTweet);
var ifaceReq = aContentWindow.QueryInterface(Ci.nsIInterfaceRequestor);
var windowUtils = ifaceReq.getInterface(Ci.nsIDOMWindowUtils);
var aDragData = 'site 99';
var aDragDataType = 'plain/text';
var event = createDragEvent(aContentWindow, "drop", aDragData, aDragDataType);
var rezDrop = windowUtils.dispatchDOMEventViaPresShell(formTweet, event, true);
console.info('rezDrop:', rezDrop);
}
sendTwitterDropEvent();
So, I've implemented plupload using flash runtime in MVC3.
It works perfectly, in the sense that it uploads using the correction Action and runs it all. However, I'd really like to be able to control the response, and handle it in plupload, but I can't seem to get any response through.
I've tried overriding fileUploaded, but I can't seem to get anything out of the arguments. I've tried return simple strings, json and what have you. I can't seem to get anything out on the client side. And of course being sent through flash, I can't even debug the requests with firebug :/
The same with the Error event, and throwing exceptions. It correctly interprets the exception as an error, but it's always that #IO ERROR with some code like 2038 or something coming out the other end. I can't show my exception string or anything at all. Can anyone help?
Bonus question: How would I send session/cookie data along with the plupload, so I can access the session in my action?
The following has worked for me:
[HttpPost]
public ActionResult Upload(int? chunk, string name)
{
var fileUpload = Request.Files[0];
var uploadPath = Server.MapPath("~/App_Data");
chunk = chunk ?? 0;
using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
return Json(new { message = "chunk uploaded", name = name });
}
and on the client:
$('#uploader').pluploadQueue({
runtimes: 'html5,flash',
url: '#Url.Action("Upload")',
max_file_size: '5mb',
chunk_size: '1mb',
unique_names: true,
multiple_queues: false,
preinit: function (uploader) {
uploader.bind('FileUploaded', function (up, file, data) {
// here file will contain interesting properties like
// id, loaded, name, percent, size, status, target_name, ...
// data.response will contain the server response
});
}
});
As far as the bonus question is concerned I am willing to answer it by don't use sessions, as they don't scale well, but because I know that you probably won't like this answer you have the possibility to pass a session id in the request using the multipart_params:
multipart_params: {
ASPSESSID: '#Session.SessionID'
},
and then on the server perform some hacks to create the proper session.
Look here:
$("#uploader").pluploadQueue({
// General settings
runtimes: 'silverlight',
url: '/Home/Upload',
max_file_size: '10mb',
chunk_size: '1mb',
unique_names: true,
multiple_queues: false,
// Resize images on clientside if we can
resize: { width: 320, height: 240, quality: 90 },
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
],
// Silverlight settings
silverlight_xap_url: '../../../Scripts/upload/plupload.silverlight.xap'
});
// Client side form validation
$('form').submit(function (e) {
var uploader = $('#uploader').pluploadQueue();
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function () {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
And in Controller:
[HttpPost]
public string Upload( ) {
HttpPostedFileBase FileData = Request.Files[0];
if ( FileData.ContentLength > 0 ) {
var fileName = Path.GetFileName( FileData.FileName );
var path = Path.Combine( Server.MapPath( "~/Content" ), fileName );
FileData.SaveAs( path );
}
return "Files was uploaded successfully!";
}
That's all...No chunk is needed in Controller...