Print existing pdf file directly to client default printer [duplicate] - asp.net

A coworker and I were having a discussion about what is and isn't possible within the browser.
Then a question came up that neither of us could answer with certainty.
Can you create a webpage such that when you navigate to it, it engages the client-side printer and attempts to print a document. For instance, whenever you visit my personal website, you'll be treated to a print out of a picture of me, smiling.
Now, this is a hideous idea. I'm aware. But the discussion intrigued me as to if it could be done, and how. My friend insisted that the best you could do was pop up the print dialog for the user, they would have to click print themselves.
Would it be possible to bypass this step? Or just some fancy script to move the mouse over the print button and click on it? Or use an activeX control to interface with a Printer API directly?

You have to prompt the user to print the current page, there's no way to bypass this step (possibly in activeX for IE). That said, there's two different ways you could prompt the user to print images of you smiling when the page is loaded.
Here's how to do it in JavaScript.
window.onload = function() {
var img = window.open("me-smiling.png");
img.print();
}
And here's how to do it in css/javascript/html (assuming your picture has the id 'me-smiling'):
CSS:
#media print {
* {
display:none;
}
img#me-smiling {
display:block;
}
}
Javascript:
window.onload = function() { window.print() }

The only solution to avoid print dialog that I found was creating a variable on Mozilla Firefox to set auto-print. Maybe is not the best solution if you need to use other browser, but in my case, I only need to print a report automatically and it works:
1- Open Firefox and type "about:config" in the address bar
2- Right click on any preference and select "New" > "Boolean"
3- Add a variable called "print.always_print_silent" with "true" value
4- Restart Firefox.
Hope help you!

AttendStar created a free add-on that suppresses the dialog box and removes all headers and footers for most versions of Firefox.
https://addons.mozilla.org/en-US/firefox/addon/attendprint/
With that feature on you can use $('img').jqprint(); and jqprint for jquery will only print that image automatically called from your web application.

As far as I know, there is no way to print a document directly, without some client intervention, like setting browser flags.
In our current project we need to print directly to the default printer, but at least with Chrome you can do it easily with additional startup arguments.
To print directly to the OS default printer you can use:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir=c:\tmp --kiosk-printing http://www.contoso.com
Another option, which may also be useful, is tos use the native print dialog instead of chromes print preview.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --user-data-dir=c:\tmp --disable-print-preview http://www.contoso.com
Note, that window.print() and/or Ctrl-P behave accordingly the mentioned settings.
I know, that this does not exactly answers the OPs question, but I think it somewhat related, and for web based enterprise applications this is a quite common use case. Maybe someone find it useful.
For Firefox I recommend Seamless Print Addon

You can't bypass the print dialog, as far as I know. That would be a pretty obvious security flaw if the browser allowed that. But you can bring up the print dialog with "window.print()".

I think at best you would need an ActiveX component using base windows API to obtain a device context for the default printer and try and print an embedded image using assumed values for the printer settings.

To print to the default printer automatically without seeing a print dialog prompt, I've shared some code in the following question that works in IE7, IE8 and IE9:
Bypass Printdialog in IE9

From lot of search from last few days,
I've found a best possible solution.
Till date Chrome do not support direct printing from javascript.
It has launched USB and serial API which might help.
But currently I'm using a JavaApplet solution which is open source.
https://github.com/qzind/qz-print - build
While I'm getting error in building it. I preferred a Prebuilt - QZ Print Plugin 1.9.3
desktop app, which works great.
Download it from here: https://qz.io/download/
Code Example:
/***************************************************************************
* Prototype function for printing an HTML screenshot of the existing page
* Usage: (identical to appendImage(), but uses html2canvas for png rendering)
* qz.setPaperSize("8.5in", "11.0in"); // US Letter
* qz.setAutoSize(true);
* qz.appendImage($("canvas")[0].toDataURL('image/png'));
***************************************************************************/
function printHTML5Page() {
$("#qz-status").html2canvas({
canvas: hidden_screenshot,
onrendered: function() {
if (notReady()) { return; }
// Optional, set up custom page size. These only work for PostScript printing.
// setPaperSize() must be called before setAutoSize(), setOrientation(), etc.
qz.setPaperSize("8.5in", "11.0in"); // US Letter
qz.setAutoSize(true);
qz.appendImage($("canvas")[0].toDataURL('image/png'));
//qz.setCopies(3);
qz.setCopies(parseInt(document.getElementById("copies").value));
// Automatically gets called when "qz.appendFile()" is finished.
window['qzDoneAppending'] = function() {
// Tell the applet to print.
qz.printPS();
// Remove reference to this function
window['qzDoneAppending'] = null;
};
}
});
}
Complete example can be found here:
https://gist.github.com/bkrajendra/c80de17b627e59287f7c

This is the best solution that I have found for firefox:
There is this awesome add-on Seamless Print.
It works like charm.

Related

Alfresco Aikau debugging

In Alfresco Share the Search page is implemented with Aikau.
I'm interested in the more general question, is it possible to Debug Aikau widgets?
I have founds some links on this matter, but they talk more about logging and not actual javascript debugging:
http://docs.alfresco.com/5.1/tasks/dev-extensions-share-tutorials-debugging.html
https://github.com/Alfresco/Aikau/blob/master/tutorial/chapters/Tutorial4.md
Suppose I have the following Aikau widget alfresco/search/AlfSearchResult and the following method inside it:
/**
* This function is called to create a
* [SearchResultPropertyLink]{#link module:alfresco/renderers/SearchResultPropertyLink} widget
* to render the displayName of the result. It can be overridden to replace the default widget
* with a reconfigured version.
*
* #instance
*/
createDisplayNameRenderer: function alfresco_search_AlfSearchResult__createDisplayNameRenderer() {
// jshint nonew:false
var config = {
id: this.id + "_DISPLAY_NAME",
currentItem: this.currentItem,
pubSubScope: this.pubSubScope,
propertyToRender: "displayName",
renderSize: "large",
newTabOnMiddleOrCtrlClick: this.newTabOnMiddleOrCtrlClick,
defaultNavigationTarget: this.navigationTarget
};
if (this.navigationTarget)
{
config.navigationTarget = this.navigationTarget;
}
new SearchResultPropertyLink(config, this.nameNode);
}
Is there any way I could insert a breakpoint and stop execution at the line where this.currentItem is used in order for me to evaluate it's properties?
Yes, there are several ways in which you can debug Aikau... the first thing to do is to make sure that you're running with "client-debug" mode enabled (either in Share or in your custom Aikau client).
For example, in Share you'd want to update the /WEB-INF/classes/alfresco/share-config.xml file to change:
<config>
<flags>
<client-debug>false</client-debug>
...to be...
<config>
<flags>
<client-debug>true</client-debug>
You'll need to restart Share for the changes to take effect. You'll see then that you have a "Debug Menu" item in the main header menu bar. If you open this you can enable logging by toggling "Debug Logging" and "Show All Logs" to be true.
This will result in logging output appearing in your browser developer tools console. You can also fine tune the logging output to only show errors or warning and to provide a RegEx expression to match certain logging output.
With client debug enabled the JavaScript source being loaded by the browser will be uncompressed. This will make it easier for you to add break points.
Because Surf aggregates all of the required module source code into a single resource (for performance and caching reasons) you will want to find the Aikau source file - the easiest way to do this is to use "CTRL-P" (in Chrome) to open a resource and type "surf" into the box that appears - this will always find the Aikau source code first.
Firebug for Firefox handles finding across resources better, so you can just used "CTRL-F" and then paste in the line you want to break on.
You can add breakpoints in this resource as you normally would and the browser will break on them.
As well as setting break points you can also use the DebugLog widget. This can be toggled from the "Debug Menu" and shows all the publications and subscriptions that are being made.
It is also possible to directly include and configure the alfresco/services/LoggingService and the alfresco/logging/DebugLog widgets in your page as you are developing. We take this approach for all our unit test pages. This can be a handy approach during development and they can be removed when you're finished developing.
This presentation although quite old, also contains some useful debugging tips (see slide 56 onwards).

Is it possible to add a section with some informtion in browser using crossrider?

I am trying to develop an extension which will show some information(about 15 words) in a small section below the extensions icons in the browser using crossrider?. I searched about it and it seems that browser only supports extensions icons and bookmarks. So is it possible to add such kind of section?? Im new to browser extension development and not sure about its possibility.
The nearest you can get to this is to use a browser action/button and use the tooltip (a.k.a. title) to display the information when the mouse hovers over the button. For example, in your background.js file your code would look something like:
appAPI.ready(function($) {
appAPI.browserAction.setResourceIcon('icons/icon.jpg');
appAPI.browserAction.setTitle('Information displayed on mouse hover');
appAPI.browserAction.onClick(function() {
alert('Hello world!');
});
});
For more information, see appAPI.browserAction.
[Disclosure: I am a Crossrider employee]

Changing Window Title in Internet Explorer via Flex-Actionscript

I am looking for a way to dynamically set the window title for a flex application in Internet Explorer. The most best way to do this is to call javascript from actionscript to set the window title via an "ExternalInterface."
ExternalInterface.call("eval(window.document.title = 'New Title')");
ExternalInterface.call("alert", "Hello ExternalInterface");
This works fine in browsers other than IE, and it even works in IE when accessing the flex application's swf file through an html wrapper.
ttp://localhost:8080/ChangeTitle/ChangeTitle.html
However, I need to access the .swf directly from the browser..
ttp://localhost:8080/ChangeTitle/ChangeTitle.swf
This causes the External interface call to change the window title to not work, but the alert still shows.
So the question is... why don't I just use the html wrapper? ... The answer: because the project is set up specifically to avoid using the html wrapper.
This is related to a known IE bug - http://bugs.adobe.com/jira/browse/FP-240
If anyone could suggest a work-around for this issue it would be greatly appreciated.
Thanks
Don't use ExternalInterface for this; use the BrowserManager class. You can first initialize it with a title:
var browser:IBrowserManager = BrowserManager.getInstance();
browser.init("", "my title");
Later you can adjust the title later on:
browser.setTitle("my new title");
I have several applications that use this and work perfectly in IE (though I haven't tested IE6).
More info on this topic: http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf64e50-7ff4.html

How do you debug printable CSS?

I use Firebug and IE Developer Toolbar all the time to debug tricky CSS problems. But occasionally, a tricky bug comes up that only appears when you go to print the page.
What techniques/tools do you use to diagnose problems like this? Is there a way to get more use out of traditional CSS debugging tools in print view?
Updated: I already use a PDF printer to avoid wasting paper; my problem is that I can't right-click on the printed DOM. Some of the other answers below are quite helpful, thanks. :-)
Just found a comment by lee-penkman about a new feature in Firefox here: Press Shift-F2 in Firefox to open the browser console (not the javascript console), then enter media emulate print. Works absolutely great!
Update Sept. 2018: Starting with Firefox 62, the developer console has disappeared. There doesn't seem to be a way to activate print style emulation now.
Update Nov. 2019: It seems that in Firefox 69, there is again a new button for print style emulation. See the other answer on this page: https://stackoverflow.com/a/58015662/195476
In Chrome 51:
Open devtools (CTRL + F12 or CTRL + SHIFT + I) and click on the ... menu, click More Tools > Rendering settings to open the Rendering tab of the developer console (alternatively, if the console is open just navigate to this tab).
In that tab, select and check the box for Emulate Media: print.
I use the WebDeveloper plugin and the CSS --> Display CSS by Media Type --> Print to view the CSS as it would when printed. Firebug's inspection utilities work with the CSS as filtered by the plugin.
In Firefox 69, I found a button to simulate print media. Just open the Developer Tools (F12) and click on Inspector. The toggle button is the leftmost icon that's in the highlighted section in the screenshot below, the one that looks like a sheet of paper.
I use Firefox and the developer toolbar.
I use the real time css edit tool in the task bar, it's pretty usefull to modify your css on the fly on see the results in real time.
I also use the outline feature, which the div and stuff like that on mouse over, on your website. Really helpful to find div.
For the print problem, go to CSS -> Display CSS style by media -> print
There are a lot of other tool available in this one, I probably use about 10% of it.
Try maybe you find something usefull.
In chrome developer tools (F12 \ Ctrl(cmd on mac) + Shift + C):
In the emulation tab (From Chrome 32 onward IMHO), there is a tab for 'Media'.
There you can check the media emulation checkbox and select the media you would like to emulate ('print', 'screen' etc.)
How about just listing your print CSS last, and removing the "print" condition from your CSS link or import statement? Then you're debugging the print CSS in the browser window.
I use the Adobe PDF virtual printer, because it's the closest thing to a real printer you'd get, without wasting ink and paper.
Anyway, it's recommended to have a separate CSS for prints, with much simpler graphics and less of the images you use just for design purposes.
I always used web developer toolbar (as described in the other answers), but Firebug seems to miss some styles from time to time. So I added a Bookmark to my browser and added the following Javascript as URL of the bookmark. Now I can simply switch to print style by clicking the bookmark:
javascript:(function(){var%20h,a,f;a=document.getElementsByTagName('link');for(h=0;h<a.length;h++){f=a[h];if(f.rel.toLowerCase().match(/stylesheet/)&&f.href&&(f.media=='print'||f.media=='screen')){var%20g=f.href.replace(/(&|%5C?)forceReload=\d+/,'');if(f.media.toLowerCase().match(/screen/))f.media="dontshow";if(f.media.toLowerCase().match(/print/))f.media="all";f.href=g+(g.match(/\?/)?'&':'?')+'forceReload='+(new%20Date().valueOf());}}})()
The code above finds all stylesheet links, tests if it is media=print and if so it changes it to media=all (and hides all media=screen by replacing it with media=dontshow) and reloads the stylesheets by adding a time token to the URL. The basic reload script is from someone else, I added media part.
This works great for me!
This would be the more readable version of the JavaScript URL above for explanation:
javascript: (function() {
var h, a, f;
a = document.getElementsByTagName('link');
for (h = 0; h < a.length; h++) {
f = a[h];
if (f.rel.toLowerCase().match(/stylesheet/) && f.href && (f.media == 'print' || f.media == 'screen')) {
var g = f.href.replace(/(&|\?)forceReload=\d /, '');
if (f.media.toLowerCase().match(/screen/)) f.media = "dontshow";
if (f.media.toLowerCase().match(/print/)) f.media = "all";
f.href = g(g.match(/\?/) ? '&' : '?')
'forceReload=' (new Date().valueOf());
}
}
})()
Print to Microsoft XPS Document Writer if you don't want to pay money. Or use SnagIt if you've got the funds (free trial on site).

Why is my javascript function not found by the page it is embedded in?

I have a page that has a simple javascript in the header portion of the page:
<script type="text/javascript">
function doLogout() {
var conf = confirm("Really log out?");
if (conf === true) { //changed == to === for boolean comparison
$.post("logout.aspx");
}
}
</script>
It uses jQuery to do an AJAX post to my logout page. The only issue right now is that when I click on the link (logout) to fire this function, nothing happens. I checked FireBug's console, and it told me that the function is not defined. This has happened to me before, but I think I botched a bunch of code to fix it sometimes.
Does anyone know the proper way to fix this issue?
Edit
After doing a lot of googling and trying different things, I found this very concise and informative post. Apparently, as the linked article states, the way the script is referenced in the web site is important as it won't run properly otherwise! Hopefully this information will be useful for more people.
This can also occur if there is a syntax error earlier in your javascript code. Often this will just be interpreted as the function not existing (nor any function AFTER the error). Check the code above this code (if there is any) and this code for syntax errors.
A way to tell if the cache error is it is to open Firebug and view the Script source. If the page was cached, you won't see your code. If it loaded but has syntax errors, the code will show, though it won't "find" it.
Things to test:
1) Can you call this function from something else? Like add a <script> at the bottom of the page to call it?
2) Does the page validate? Sometimes I get screwy javascript errors if there is some busted HTML like a missing </b>
3) I've been starting to wrap my javascript in <![CDATA[ ]]> just incase I've got goofy chars in my javascript.
4) I assume you've tested this in other browsers and have the same behavior, right?
5) If you haven't installed it already, install the Web Developer firefox addon. It has a nifty toolbar menu that will disable the cache for you so everything reloads.
6) As weird as it sounds, I once hit a javascript issue that was because of how my text editor was saving UTF-8 files. I forget the details, but it was adding some byte-order-mark or something that upset the browser.
I've had this occur when the page had been cached and so it didn't load the new script in. So to fix it clear all private data from Firefox. Not sure if that helps but it sure happened to me a bunch.
Other ideas for you to test:
is the function defined in the DOM tab in FireBug?
if you call doLogout() from the FireBug console, what happens?
I assume this is not the only script on that page. Make sure that some later script is not modifying doLogout to something else
I had the same issue and tried all that's been suggested here without success.
The only way I fixed it was by discovering that in the <script src="jquery.js"> tag I was using in the head of the page I forgot to close it with its </script> causing the page to ignore all Javascript functions. So please check that your includes look like:
<script src="jquery.js"></script>
I hope that helps. Ross.
If you are using DevExpress controls these links may help you: How to register and execute a JavaScript downloaded to the client via a callback and How to register and execute a JavaScript downloaded to the client via a callback (standalone JS file) and Executing javascripts from user controls dynamically created through ASPxCallback panels
The issue might occur if you have NoScript. You should check and make sure it's not blocking said script.
I had this issue and discovered the problem was just a wrong case letter inside the name.
Call: filterCheckbox()
vs
function filterCheckBox() {}
problem: lowercase "box" vs uppercase "Box".
So check if the name is exactly the same.

Resources