How to execute the Windows 'printto' verb using Java? - java

In the past I have used the 'printto' verb to print PDFs from with a .Net application. It looked something like this:
ProcessStartInfo psi = new ProcessStartInfo(file);
psi.Verb = "printto"; // print to given printer
psi.Arguments = "LPT1";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.ErrorDialog = true;
Process.Start(psi);
How can I do this from a Java application? Or is there an alternative approach? Note that the target platform will always be Windows.

Please try this.
public void print() {
//The desktop api can help calling native applications in windows
Desktop desktop = Desktop.getDesktop();
try {
desktop.print(new File("yourFile.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
Please Note : This is the easy fix. You can also use java's Print API to achieve the same thing

Related

How to parse Unicode java applications Vdurmont emoji-java2.0.1 library

I'm using netbeans IDE for developing java desktop application with Vdurmont emoji-java2.0.1 Emoji library. Its working with my netbeans IDE development and sent emojis unicode another side its working fine (Showing fine and correct emoji with emotions). Problem: When i clean build and make a .jar with all necessary lib,
it showing this (😡 and ?) on another side web app Vdurmont emoji-java2.0.1 library didn't load or not working with myemojiapp.jar file. *please let me know if any need for this ?..
Object finalmsz = "";
msz = jtp.getText();
MyHtml2Text parser = new MyHtml2Text();
try {
parser.parse(new StringReader(msz));
} catch (IOException ee) {
//handle exception my exp
}
finalmsz = Imoji.parseToUnicode(parser.getText() + str);**
public static String parseToUnicode(String input) {
String result = input;
for (Emoji emoji : EmojiManager.getAll()) {
result = result.replace(emoji.getHtmlHexidecimal(),emoji.getUnicode());
}
return result;
}
Please note this parsing not working with my myemojiapp.jar file (showing this 😡 and ?)
but it works fine on my netbeans during development.

Java Printing Tray Selection Saga

While there are several questions regarding tray selection out there, none of them relate to my problem.
Here's the code I'm using to print:
private static void finalPrint(PDDocument pdoc, boolean pbStationary)
throws BigBangJewelException
{
PrintService lrefSvc;
PrinterJob lrefPJob;
Media lrefMedia;
HashPrintRequestAttributeSet lobjSet;
lrefSvc = getPrinter();
lrefPJob = PrinterJob.getPrinterJob();
try
{
lrefPJob.setPrintService(lrefSvc);
lrefPJob.setPageable(pdoc);
lrefMedia = null;
if ( pbStationary )
lrefMedia = getTray(lrefSvc);
if ( lrefMedia != null )
{
lobjSet = new HashPrintRequestAttributeSet();
lobjSet.add(lrefMedia);
lrefPJob.print(lobjSet);
}
else
lrefPJob.print();
}
catch (Throwable e)
{
throw new BigBangJewelException(e.getMessage(), e);
}
}
private static PrintService getPrinter()
throws BigBangJewelException
{
String lstrPrinter;
PrintService[] larrServices;
int i;
try
{
lstrPrinter = (String)Engine.getUserData().get("Printer");
larrServices = PrinterJob.lookupPrintServices();
for ( i = 0; i < larrServices.length; i++ )
{
if (larrServices[i].getName().indexOf(lstrPrinter) != -1)
return larrServices[i];
}
}
catch (Throwable e)
{
throw new BigBangJewelException(e.getMessage(), e);
}
throw new BigBangJewelException("Impressora definida (" + lstrPrinter + ") não encontrada.");
}
private static Media getTray(PrintService prefSvc)
{
Media[] larrMedia;
String lstrAux;
int i;
larrMedia = (Media[])prefSvc.getSupportedAttributeValues(Media.class, null, null);
if ( larrMedia == null )
return null;
for ( i = 0; i < larrMedia.length; i++ )
{
lstrAux = larrMedia[i].toString().toLowerCase();
if (lstrAux.contains("tray") && lstrAux.contains("3"))
{
return larrMedia[i];
}
}
return null;
}
The baffling thing is, this code used to work. The machine had a bunch of Xerox printers defined, and the code would correctly identify the wanted printer, and the wanted tray, and everything worked wonderfully.
Then, one day, overnight, it stopped working. It still finds the right printer, but now, it always prints to tray 1.
The only thing that changed was that an extra HP printer was added to the machine.
I can confirm that the code is finding the tray and sending it to the print job, but it's getting ignored.
Again, there are many questions out there regarding this issue, but my problem is that the code worked well for four years, then stopped working for no apparent reason.
Can anyone shed any light on this subject?
Edit: New information: Uninstalling the HP printer made the Xerox printers work right again. Why would installing one driver affect Java's ability to communicate with a different driver?
Edit 2: Further information: If we install the HP global printer driver instead of the specific printer driver, everything works correctly. I'll leave the question unanswered to see if anyone can come up with a good explanation before the bounty expires, then I'm going to put this edit in an answer and accept it.
If I got you question correctly, you the content of lobjSet is unchanged, yet it the print result is different, with the new driver installed.
I checked the code for PnterJob.print(PrintRequestAttributeSet) and was surprised that it completely ignores the attribute set.
So I looked at where the PrintService is coming from, the code is a little lengthy, but I guess it interacts somehow with the installed printer drivers to create appropriate instances. So the new driver changes this, returning a different PrintService. There is no way I can tell in what exact way this thing changes, but if you can recreate both scenarios (and it seems you can), it should be fairly easy to use a debugger to find the exact place where the behavior of the code changes.
The solution to our particular situation was to change the printer drivers for the HP printer.
Originally, we had installed the specific driver for the printer in question, which caused this behavior. Installing HP's global driver instead made the problem go away.
Unfortunately, we do not know why. Jens Schauder's answer contains clues as to how to go about finding out.

Simplest way to "unpack" obfuscated javascript from within a Java program

Let's say that you have a web page that only contains obfuscated Javascript in the form of an eval(...) function within a script tag.
Dean Edwards' online unpacker (link) correctly unpacks this Javascript.
I would like to write a simple Java class that loads the initial web page (I use HttpClient), extracts the eval(...) function from the HTML, and unpacks it, in order to obtain the de-obfuscated Javascript.
I've tried with Rhino, here's my code :
int start = html.indexOf("<script>eval") + "<script>".length();
int end = html.indexOf("</script>");
javascript = html.substring(start, end);
evaled = eval(javascript);
NativeFunction fEvaled = (NativeFunction) evaled;
String encodedSource = fEvaled.getEncodedSource();
log.info("encodedSource: " + encodedSource);
and the "eval" java function called:
private Object eval(String javascript){
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Object eval = null;
try {
eval = engine.eval(javascript);
} catch (ScriptException e) {
// TODO Auto-generated catch block
log.error("Exception evaluating javascript " + javascript, e);
}
return eval;
}
But, that doesn't work, the code returned is far from being the correct code (returned by Edwards' unpacker). I've inspected the Rhino variables, found nothing useful.
Am I doing something wrong ?
I'm open to any suggestion, for example if there's a command-line tool that will work I can make a system call.
I'm on Ubuntu.
Thanks.

Java grph library: Exception on toools.os.OperatingSystem.getLocalOS()

I'm using grph library for a university project (www.i3s.unice.fr/~hogie/grph/)
but i have a problem only on Linux with that library, when i create a new Graph object, i receive the following exception:
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.elendev.wesproject.graph.GraphFactory.main(GraphFactory.java:19)
Caused by: java.lang.NullPointerException
at toools.os.OperatingSystem.getLocalOS(OperatingSystem.java:47)
at grph.Grph.setCompilationDirectory(Grph.java:353)
at grph.Grph.<clinit>(Grph.java:246)
... 1 more
I tried to call directly getLocalOS function, with:
System.out.println(toools.os.OperatingSystem.getLocalOS());
and i receive the same exception. I cannot find information about that library, and the project launched on a macbook works perfectly.
The operating system i'm currently using is gentoo linux 32bit.
And the jdk version is: 1.7.0_65
Any idea of what could be the problem?
Not sure whether this can count as an answer, but it could at least help to solve the issue:
The exception comes from the toools.os.OperatingSystem.getLocalOS method. Although the .JAR file from the website that you mentioned has a whopping 39 megabytes, the source code of this class is not contained in it.
There seems to be no information available about this class at all. Neither Google nor Maven finds anything related to the toools package. One has to assume that it is an abandoned utility class that passed away a long time ago.
However, the method in question can be disassembled to the following code:
public static OperatingSystem getLocalOS()
{
if (localOS == null)
{
if (new RegularFile("/etc/passwd").exists())
{
if (new Directory("/proc").exists())
{
if (new RegularFile("/etc/fedora-release").exists()) {
localOS = new FedoraLinux();
} else if (ExternalProgram.commandIsAvailable("ubuntu-bug")) {
localOS = new UbuntuLinux();
} else {
localOS = new Linux();
}
}
else if (new Directory("/Applications").exists()) {
localOS = new MacOSX();
} else {
localOS = new Unix();
}
}
else if (System.getProperty("os.name").startsWith("Windows")) {
localOS = new Windows();
} else {
localOS = new OperatingSystem();
}
localOS.name = System.getProperty("os.name");
localOS.version = System.getProperty("os.version");
}
return localOS;
}
From this, you can possibly derive the conditions that must be met in order to properly detect your OS as a linux OS. Particularly, when there is a file named /etc/passwd, and a directory /proc, this should be sufficient to identify the OS as a Linux. You may want to give it a try...

Running a Java program with a .dll from Adobe AIR's native process

I would like to be able to operate a scanner from my AIR application. Since there's no support for this natively, I'm trying to use the NativeProcess class to start a jar file that can run the scanner. The Java code is using the JTwain library to operate the scanner. The Java application runs fine by itself, and the AIR application can start and communicate with the Java application. The problem seems to be that any time I attempt to use a function from JTwain (which relies on the JTwain.dll), the application dies IF AIR STARTED IT.
I'm not sure if there's some limit about referencing dll files from the native process or what. I've included my code below
Java code-
while(true)
{
try {
System.out.println("Start");
text = in.readLine();
Source source = SourceManager.instance().getCurrentSource();
System.out.println("Java says: "+ text);
}
catch (IOException e)
{
System.err.println("Exception while reading the input. " + e);
}
catch (Exception e) {
System.out.println("Other exception occured: " + e.toString());
}
finally {
}
}
}
Air application-
import mx.events.FlexEvent;
private var nativeProcess:NativeProcess;
private var npInfo:NativeProcessStartupInfo;
private var processBuffer:ByteArray;
private var bLength:int = 0;
protected function windowedapplication1_applicationCompleteHandler(event:FlexEvent):void
{
var arg:Vector.<String> = new Vector.<String>;
arg.push("-jar");
arg.push(File.applicationDirectory.resolvePath("Hello2.jar").nativePath);
processBuffer = new ByteArray;
npInfo = new NativeProcessStartupInfo;
npInfo.executable = new File("C:/Program Files/Java/jre6/bin/javaw.exe");
npInfo.arguments = arg;
nativeProcess = new NativeProcess;
nativeProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onStandardOutputData);
nativeProcess.start(npInfo);
}
private function onStandardOutputData(e:ProgressEvent):void
{
tArea.text += nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable);
}
protected function button1_clickHandler(event:MouseEvent):void
{
tArea.text += 'AIR app: '+tInput.text + '\n';
nativeProcess.standardInput.writeMultiByte(tInput.text + "\n", 'utf-8');
tInput.text = '';
}
protected function windowedapplication1_closeHandler(event:Event):void
{
nativeProcess.closeInput();
}
]]>
</fx:Script>
<s:Button label="Send" x="221" y="11" click="button1_clickHandler(event)"/>
<s:TextInput id="tInput" x="10" y="10" width="203"/>
<s:TextArea id="tArea" x="10" width="282" height="88" top="40"/>
I would love some explanation about why this is dying. I've done enough testing that I know absolutely that the line that kills it is the SourceManager.instance().getCurrentSource(). I would love any suggestions. Thanks.
When calling Java add this -Djava.library.path=location_of_dll to the command line
I have 0 experience with Air, but this reminded me of a Java issue I once spent some time figuring out. I don't have a suggestion on why the scanning doesn't work, but I think a stack trace would be your best friend right now.
I'm guessing you're relying on this line to capture and display it?
nativeProcess.standardOutput.readUTFBytes(nativeProcess.standardOutput.bytesAvailable);
However, you are writing IOExceptions to System.err - is there a nativeProcess.standardError you could read in Air? Alternatively, output everything to System.out.

Categories

Resources