I have a java code that sends PDF files to printers.
Java code goes something like this:
import java.awt.print.PrinterJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.pdmodel.PDDocument;
public class PrintPdf {
protected final Log logger = LogFactory.getLog(getClass());
public void print(String pdfFile, String printer, int copies) throws Exception {
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
PDDocument document = null;
try
{
document = PDDocument.load( pdfFile );
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService[] printServices = PrinterJob.lookupPrintServices();
PrintService myService = null;
if (printServices.length > 0)
{
for(PrintService service : printServices) {
if(service.getName().toLowerCase().contains(printer.toLowerCase())) {
myService = service;
break;
}
}
if (myService == null) {
throw new Exception("Printer not found " + printer);
} else {
logger.info("Printer found " + myService.getName());
}
} else {
throw new Exception("No print services found");
}
printJob.setPrintService(myService);
printJob.setCopies(copies);
document.silentPrint( printJob );
}
finally {
if( document != null ) {
document.close();
}
}
}
This java is called from batch file. I've scheduled a windows task to run the file every X minutes. Scheduled Task is run with a user that has admin rights. All this is run on a Windows 2003 server.
Printers are set up using a TCP/IP address.
The problem: When the user is logged in, the Task runs and can send PDF files to the printers.
When the user is not logged in, the Task runs but java returns an error:
java.awt.print.PrinterException: Invalid name of PrintService
Java program successfully lists available Print Services in the loop, just before the print command, but for some reason is not able to print the document while the user is not logged in.
Could anyone, please, give me some advice on what might be the problem here?
EDIT:
Exception occurs in the line:
printJob.setPrintService(myService);
The solution to this problem was to upgrade the existing java on the OS from version 6u45 to 7u21.
Related
I have created a java application to send/receive the topic messages using Azure Service Bus java SDK and it is working perfectly fine if I run it as a Java Application.
I exported the application as jar along with all the dependency jars to the {ColdFusionInstallation}\cfusion\lib and restarted ColdFusion Application Server.
I am able to create the class objects and see their definitions while dumping but when I trying to call any particular method from the class, it's taking forever.
<cfset objSender = createObject( "java", "com.test.Sender" ).init()>
<cfset objSender.sendAsync( JavaCast( "string", "cftest" ) )>
Sender.java
package com.test;
import java.util.concurrent.CompletableFuture;
import org.apache.log4j.Logger;
import com.microsoft.azure.servicebus.IMessage;
import com.microsoft.azure.servicebus.ITopicClient;
import com.microsoft.azure.servicebus.Message;
import com.microsoft.azure.servicebus.TopicClient;
import com.microsoft.azure.servicebus.primitives.ConnectionStringBuilder;
import com.microsoft.azure.servicebus.primitives.ServiceBusException;
public class Sender {
private final String namespaceConnectionString = "Endpoint=sb.......";
private final String namespaceTopicName = "test";
private static Logger logger = Logger.getRootLogger();
public CompletableFuture<Void> sendAsync( String message ) {
// Get client
ITopicClient topicClient = this.createTopicClient( this.namespaceTopicName );
// Send Async
CompletableFuture<Void> future = topicClient.sendAsync(
new Message( message )
).thenRunAsync( () -> {
try {
topicClient.close();
} catch (Exception e) {
logger.info( "Unable to close topic client!" );
}
} );
return future;
}
private ITopicClient createTopicClient( String topicName ) throws RuntimeException {
// Create client for topic
ITopicClient topicClient = null;
try {
// Create
topicClient = new TopicClient(
new ConnectionStringBuilder( this.namespaceConnectionString, topicName )
);
} catch ( InterruptedException | ServiceBusException e ) {
logger.info( "Unable to client for topic: " + topicName );
throw new RuntimeException( "Unable to create client for topic: " + topicName );
}
return topicClient;
}
}
I am not sure what is wrong as it is working when running directly.
Any suggestions greatly appreciated!
I am writing a program that are working with adresses and I want the final output to be sent to a printer. As most of the adresses are located in northen Europe I need to be able to handle some special characters. However I seem to be unable to do this when printing.
When writing to the terminal or to a *.txt file everything works fine but on the printed pages I get gibberish.
This is basicly what I am trying to do:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.print.*;
public class PrintExample {
public static void main(String[] args) throws PrintException,IOException {
String testData = "ÅÄÖ, åäö";
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
InputStream is = new ByteArrayInputStream(testData.getBytes("UTF-8"));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(is, flavor, null);
job.print(doc, null);
is.close();
}
}
Does anyone have a clue as to what's wrong?
i am running a virtual machine with VMware 9.0. I added the printers via the Settings tab in the VM. To see that my printers are availabe on my vm i wrote a little program:
import java.io.PrintStream;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
public class ShowPrinter {
public static void main(String[] args) {
PrintService lookupDefaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
if (lookupDefaultPrintService != null)
System.out.println("default: " + lookupDefaultPrintService.getName());
else {
System.out.println("default: null");
}
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (PrintService service : services)
if (service != null)
System.out.println("- " + service.getName());
else
System.out.println("- null");
}
}
This works well and i get some printers listed (including the one i want to use). I wrote a little program which should print something:
package virtualMachinePrinter;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocFlavor.INPUT_STREAM;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
public class MyPrinter {
public static void main(String[] args) throws IOException {
File file = new File("C:/temp/printtest.txt");
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(inputStream, flavor, null);
try {
job.print(doc, null);
} catch (PrintException e) {
e.printStackTrace();
}
inputStream.close();
System.out.println("Printing done...");
}
}
On my local machine this works just well, and if i change the default printer, it prints to it. On the virtual machine this works not as intended. The XPS document writer doesn't even start. If i try the same with pdf-printer, the page setup opens at least (but nothing is printed). If i start the little programm above inside a web-application on a Tomcat 7, it doesn't print anything. Independent of which default printer is used. In both cases the print order is added to the printing queue. But only outside of a Tomcat something is printed. Inside the Tomcat nothing is printed. I am using no security manager in my Tomcat.
Two actions solved this problem:
1. I had to use 32-bit version of Java. This fixed the problem printing with XPS document writer.
2. I had to update my printer drivers. This fixed the problem printing with the printer.
I have a web application using PHP. One of the functionality is to silently print a receipt to two or more printers directly without prompting the printer dialog box. I have coded the applet as below and it prints directly to any printer specified in the code.
import javax.swing.JApplet;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.print.PrintService;
import com.sun.pdfview.PDFFile;
import javax.swing.JOptionPane;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
public class PDFApplet extends JApplet {
private PrinterJob pjob = null;
//Called when this applet is loaded into the browser.
public void init() {
try {
FileInputStream fis = new FileInputStream("C:\\app\\receipt.pdf");
byte[] pdfContent = new byte[fis.available()];
fis.read(pdfContent, 0, fis.available());
initialize(pdfContent, "Test Print PDF");
//PDFApplet printPDFFile = new PDFApplet(fis, "Test Print PDF");
print();
} catch (Exception e) {}
}
private void initialize(byte[] pdfContent, String jobName) throws IOException, PrinterException {
ByteBuffer bb = ByteBuffer.wrap(pdfContent);
// Create PDF Print Page
PDFFile pdfFile = new PDFFile(bb);
PDFPrintPage pages = new PDFPrintPage(pdfFile);
// Create Print Job
pjob = PrinterJob.getPrinterJob();
PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
pjob.setJobName(jobName);
Book book = new Book();
book.append(pages, pf, pdfFile.getNumPages());
pjob.setPageable(book);
// to remove margins
Paper paper = new Paper();
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
pf.setPaper(paper);
}
public void print() throws PrinterException {
String argPrintServiceName = "HP LaserJet Professional P1102";
// Send print job to default printer
PrintService[] printServices = PrinterJob.lookupPrintServices();
int i;
for (i = 0; i < printServices.length; i++) {
if (printServices[i].getName().equalsIgnoreCase(argPrintServiceName)) {
pjob.setPrintService(printServices[i]);
break;
}
}
if (i == printServices.length) {
//throw new PrinterException("Invalid print service name: " + argPrintServiceName);
JOptionPane.showMessageDialog(this, "Cannot print to " + argPrintServiceName);
}
pjob.print();
}
}
However when I embed it in an html page, then the applet does not print anymore. I have added the necessary printing permissions to java.policy but it still does not print.How can I solve this since it has taken me about a week already.
Thanks,
Sam
Digitally sign the applet using a certificate authenticated by a trusted authority (e.g. Verisign). It will prompt the user, they can select 'always trust', and thereafter the applet will be able to do printing unprompted & without further user intervention (assuming the code does not invoke a print dialog).
I am creating one GUI in swing Java. I have to use one button " Print " which will directly start printing the file I have set without opening the default Print dialog box.
I have to check first whether printner is attached to my computer or not ?
May be using PrintServiceLookup?
Implementations of this class provide lookup services for print services (typically equivalent to printers) of a particular type.
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices =PrintServiceLookup.lookupPrintServices(flavor, aset);
if (pservices.length > 0) {
DocPrintJob pj = pservices[0].createPrintJob();
//....
}
Note: the number of PrintService should be at least one iff there is a printer. Potentially at least 2 if there is an actual printer, since you can have pure software printers installed on your computer. See also this thread.
Depending on the platform and jdk, it can have some bug, but otherwise, the following method is supposed to at least list the printers:
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import java.text.*;
import javax.print.attribute.standard.*;
public class ShowPrinters {
public ShowPrinters() {
}
public static void main(String[] args) {
DocFlavor myFormat = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] services =PrintServiceLookup.lookupPrintServices(myFormat, aset);
System.out.println("The following printers are available");
for (int i=0;i<services.length;i++) {
System.out.println(" service name: "+services[i].getName());
}
}
}
In this eclipse code source, you have see the use of PrinterState to check if the printer is actually connected:
AttributeSet attributes = new HashPrintServiceAttributeSet(
new PrinterName(printerName, Locale.getDefault()));
PrintService[] services = PrintServiceLookup.lookupPrintServices(
DocFlavor.SERVICE_FORMATTED.PRINTABLE,
attributes);
PrintService printService = services[0];
PrintServiceAttributeSet printServiceAttributes = printService.getAttributes();
PrinterState printerState = (PrinterState) printServiceAttributes.get(PrinterState.class);
Check if printerState is not null. Note: this might not be always enough (see this thread).