Can't print text file using Java 8 in Windows 7 - java

I've created a report and exported it as a text file, to print in a matrix printer, however, the result of the job is a blank page. I did the same in ubuntu and it is printing correctly.
Is it a Java bug?
This is a example code I did to show you the problem:
public class PrintError extends Application {
public static void main(String args[]) {
launch(args);
}
public void start(Stage stage) throws PrintException {
PrinterJob printerJob = PrinterJob.createPrinterJob();
printerJob.showPrintDialog(stage);
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(new Copies(printerJob.getJobSettings().getCopies()));
printRequestAttributeSet.add(new JobName("test", Locale.getDefault()));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc mydoc = new SimpleDoc(ClassLoader.class.getResourceAsStream("/should-be-printed.txt"), flavor, null);
DocPrintJob job = getPrintService(printerJob.getPrinter().getName()).createPrintJob();
job.print(mydoc, printRequestAttributeSet);
}
private PrintService getPrintService(String name) {
for (PrintService printService : java.awt.print.PrinterJob.lookupPrintServices()) {
if (name.equalsIgnoreCase(printService.getName())) {
return printService;
}
}
return null;
}
}
This example was created in JavaFx 8 and is running in Java build 1.8.0-b132 in Windows 7.
I've also created a simple project at github

From the documentation:
Recommended DocFlavors
The Java Print Service API does not define any mandatorily supported DocFlavors. …
When you have a PrintService instance, you can use the method getSupportedDocFlavors() to find out which flavors it supports.
When you find out that none of the DocFlavor. INPUT_STREAM. TEXT_PLAIN_… flavors is in the list, it doesn’t help to use AUTOSENSE as that simply means “best guess” and it’s unlikely that a PrintService will guess a type it doesn’t support, instead, it’s more likely that the data will be misinterpreted as one of the formats it supports.
On my Windows machine, none of the provided PrintServices supports printing plaintext…

If anyone else comes across a similar problem (Printing blank in Windows 7 but working in Windows 10 in my case), but the DocFlavor is set correctly (i.e. One supported by a chosen print service)...
I was able to solve my issue by updating the JRE from 32-bit 8u101 to 64-bit 8u121.

Related

Java Printing - Spooling in Printing Queue

I want to print a pdf file to a printer using java-based software specifically Netbeans. When I ran my code below, I saw that the document is in printing queue with a file name "Java Document" with a Spooling status.
The questions are:
I want to know why my printer is not printing the document even if it is in queue?
Is it because of the code or is it because of my printer?
Here is my code:
public String gonnaGo(String newfile) throws FileNotFoundException, PrintException, IOException{
System.out.println("Hello!" + newfile);
InputStream is;
is = new BufferedInputStream(new FileInputStream(newfile)); //The new file will be the one to be printed
Doc doc = new SimpleDoc(in, DocFlavor.INPUT_STREAM.AUTOSENSE,null);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
// Locate the default print service for this environment.
System.out.println("Default printer: " + PrintServiceLookup.lookupDefaultPrintService().getName());
//Check if the file directory of the file to be printed is included
PrintRequestAttributeSet params = new HashPrintRequestAttributeSet(); //ADD PRINTING PROPERTIES HERE
params.add(new Copies(1));
DocPrintJob printJob = service.createPrintJob(); //used to determine whether the print job is finished
printJob.addPrintJobListener(new JobCompleteMonitor());
service.createPrintJob().print(doc, params);
System.out.println("Exiting app");
is.close();
return null;
}
This is the output and it does not print anything. My printer is already connected. I use Canon ip2770 series, Epson Stylus TX117, and HP Deskjet 2510 series with the latest drivers.

Get number of sheets in Open Office with Java

I am using Java to automate the creation and modification of Open Office Calc documents.
I was wondering how to get the number of sheets in a spreadsheet. I can't seem to find any Count, Length, size or similar functions.
Here is my code. Thanks in advance!
public static void openDocument(String filename)
{
try
{
// Get the remote office component context
xContext = Bootstrap.bootstrap();
// Get the remote office service manager
XMultiComponentFactory xMCF = xContext.getServiceManager();
// Get the root frame (i.e. desktop) of openoffice framework.
oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
// Desktop has 3 interfaces. The XComponentLoader interface provides ability to load components.
XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,
oDesktop);
PropertyValue[] loadProps = new PropertyValue[0];
xSpreadsheetComponent = xCompLoader.loadComponentFromURL(getUpdatedPath(filename), "_blank", 0, loadProps);
xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, xSpreadsheetComponent);
xSpreadsheetDocument = (XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class,
xSpreadsheetComponent);
xSpreadsheets = xSpreadsheetDocument.getSheets();
// Need code here to get number of sheets
}
catch (Exception e)
{
e.printStackTrace();
}
This is more of a comment (since I do not know the correct syntax for Java - maybe you need to do a .queryInterface on xSpreadsheets?), but posting as an answer to include an image. Using Bernard Marcelly's object inspection tool XRay (http://bernard.marcelly.perso.sfr.fr/index2.html) shows that an XSpreadsheets object has a method .getCount(). I tested this method using OpenOffice Basic and it works as expected.
I solved my issue using this:
int numberOfSheets = xSpreadsheets.getElementNames().length;

java.awt.print.PrinterException: Printer is not accepting job

I am facing java.awt.print.PrinterException: Printer is not accepting job..Exception in my jsp page when sending documents to print dyanamically................
String pdfFile = "D://Records.pdf";
boolean silentPrint = false;
String printerindx = "1";
String password = "";
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
if (pdfFile == null) {
System.out.println("No PDF file available");
}
PDDocument document = null;
try {
document = PDDocument.load(pdfFile);
if (document.isEncrypted()) {
document.decrypt(password);
}
PrinterJob printJob = PrinterJob.getPrinterJob();
if (printerindx != null) {
PrintService[] printServices = PrinterJob.lookupPrintServices();
for (PrintService printService : printServices) {
if (printService.getName().equals("HP LaserJet P1007") {
System.out.println("Printer found ....");
printJob.setPrintService(printService);
System.out.println(printService);
}
}
}
document.print(printJob);
} finally {
if (document != null) {
document.close();
}
}
System.out.println("Printing Completed...");
whats going wrong ?
According to this: openjdk bug it is an error in printing libraries, and you have some options:
Use different JRE where error is fixed.
Repeat printing until it will not throw, people with similar problem say it often worked on first repeat.
Use hack from here: hack, see ForcedAcceptPrintService class
What Failed
I've previously attempted the solution from Piro's third suggestion, but I received the same error that the succeeding poster (post #10) experienced.
What Worked
I performed the bytecode hack, which overwrites the Win32PrintService getPrinterIsAcceptingJobs() method to always return a status of "ACCEPTING_JOBS." This worked perfectly for my needs: The printer is always seen as available and even if it's actually offline, print jobs are queued for whenever it comes back online. The only thing I had to do differently was grab an older version of Javassist (3.18) from GitHub since I'm compiling with Java 7. Attempting to compile with the latest version (3.20) -- which is built with Java 8 -- gave me the following error:
java.lang.UnsupportedClassVersionError: sun/print/Win32PrintService : Unsupported major.minor version 52.0
For anyone else unfamiliar with the compilations necessary to create the PrintServiceFixer.jar, here are the steps I took:
Copied javassist.jar to <JAVA_HOME>\jre\lib\ext
Compiled Win32PrintServiceFixer.java (from within <JAVA_HOME>\jre\lib)
javac -classpath .\rt.jar -bootclasspath ext\javassist.jar Win32PrintServiceFixer.java
Created PrintServiceFixer.jar file:
java -cp .;.\ext\javassist.jar Win32PrintServiceFixer
Copied PrintServiceFixer.jar from <JAVA_HOME>\jre\lib\target to the directory where I store my program's library/JAR files.
Ran my program
java -jar -Xbootclasspath/p:path\to\my\program's\libs\PrintServiceFixer.jar MyPrintingProgram.jar

Printer Availablity

Here i have coded to get a list of devices and i will check each devices status
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++) {
PrintService printService = services[i];
PrintServiceAttributeSet printServiceAttributes = printService.getAttributes();
PrinterState printerState =
(PrinterState)printServiceAttributes.get(PrinterState.class);
if (printerState != null){
System.out.println(services[i].getName() + " is online");
} else {
System.out.println(services[i].getName() + " is offline");
}
}
But the problem is each and every time i got a status "Offline" even that printer is Switched on or Switched off
I recently had the same problem getting another attribute from a PrintService.
In fact, it always returns null because the method has never been implemented in the Java class, and that's the case for a lot of attributes.
If you really want to get these information, you will have to use the windows Print Spooler DLL or, if your printer is a net printer, query these informations via SNMP.

How to print PDF from java application

I have to print a PDF file using java application. I have tried such approach:
FileInputStream psStream = new FileInputStream("<path to file>");
PrintService service = getPrinterByName("some printer name");
if (service != null) {
DocPrintJob printJob = service.createPrintJob();
Doc document = new SimpleDoc(psStream, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
try {
printJob.print(document, null);
} catch (PrintException e) {
e.printStackTrace();
}
}
private PrintService[] getPrintersList() {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);
return services;
}
private PrintService getPrinterByName(String name) {
PrintService[] list = getPrintersList();
if (list.length > 0) {
for (PrintService service : list) {
if (service.getName().contains(name)) {
return service;
}
}
}
return null;
}
When I tested this on fake printer (I used PDFCreator as a printer) everything was OK, but when I tried to print on physical printer, nothing happend.
Then I used PDFBox. Document was printed, but with strange dots between words, in places where they should not be.
So, maybe someone have experience with printing PDF from java applications and can share this information?
Sending a PDF file directly to a printer will only work for printers that support the PDF format natively. This will be supported by any virtual PDF printer, but not by most of the hardware printers out-there. If you want to print a PDF file reliably, you need to use a library to render its content into the printer.
Take look then at this question in SO:
Which Java based PDF rendering library should I use for printing?
Update:
The link above is broken but there is no replacement for it other that doing a google search. Unfortunately stack-overflow owners decided that questions related to library recommendations are not welcome.

Categories