Java Print program with Specifications? - java

I want a java program for windows in which I can also send the print specification like Layout Orientation,Number of copies,Pages from and to,etc along with the file path to be printed.
M using This Code ,It works bt I can't provide the print Specifications?
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class PrintFile {
public static void fileToPrint(File fis) {
try {
Desktop desktop = null;
if (Desktop.isDesktopSupported())
{
desktop = Desktop.getDesktop();
}
desktop.print(fis);
System.out.print("Printing Document");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}

Check out Java Print Service API
The javax.print.attribute and javax.print.attribute.standard packages define print attributes which describe the capabilities of a print service, specify the requirements of a print job, and track the progress of the print job.
For example, if you would like to use A4 paper format and print three copies of your document you will have to create a set of the following attributes implementing the PrintRequestAttributeSet interface:
PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
attr_set.add(MediaSizeName.ISO_A4);
attr_set.add(new Copies(3));
Then you must pass the attribute set to the print job's print method, along with the DocFlavor.
MediaSize.ISO.A4 or MediaSize.ISO_A4 doesn't work. Instead MediaSizeName.ISO_A4 is correct.

Related

How to rewrite one specific line of a text file in java

The image below shows the format of my settings file for a web bot I'm developing. If you look at line 31 in the image you will see it says chromeVersion. This is so the program knows which version of the chromedriver to use. If the user enters an invalid response or leaves the field blank the program will detect that and determine the version itself and save the version it determines to a string called chromeVersion. After this is done I want to replace line 31 of that file with
"(31) chromeVersion(76/77/78), if you don't know this field will be filled automatically upon the first run of the bot): " + chromeVersion
To be clear I do not want to rewrite the whole file I just want to either change the value assigned to chromeVersion in the text file or rewrite that line with the version included.
Any suggestions or ways to do this would be much appreciated.
image
You will need to rewrite the whole file, except the byte length of the file remains the same after your modification. Since this is not guaranteed to be the case or to find out is too cumbersome here is a simple procedure:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Lab1 {
public static void main(String[] args) {
String chromVersion = "myChromeVersion";
try {
Path path = Paths.get("C:\\whatever\\path\\toYourFile.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
int lineToModify = 31;
lines.set(lineToModify, lines.get(lineToModify)+ chromVersion);
Files.write(path, lines, StandardCharsets.UTF_8);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Note that this is not the best way to go for very large files. But for the small file you have it is not an issue.

JUnit test for tess4J application

I want to test my method to see if it will read the file correctly. I just can't seem to wrap my head around JUnit Testing. Can someone show me how to correctly write a JUnit test for this code:
import java.io.File;
import net.sourceforge.tess4j.*;
import net.sourceforge.tess4j.util.LoadLibs;
public class ImageTest {
public static String imageService(String filePath) {
File imageFile = new File("tessImage.png");
ITesseract instance = new Tesseract();
//Let tessdata be extracted in case you dont have tessdata folder
File tessDataFolder = LoadLibs.extractTessResources("tessdata");
//Set the tessdata path
instance.setDatapath(tessDataFolder.getAbsolutePath());
instance.setLanguage("eng");
try {
String result = instance.doOCR(imageFile);
return result;
} catch (TesseractException e) {
System.err.println(e.getMessage());
return "this is an error" ;
}
}
}
Forword: your exception handling is horrific. Don't return an error message when your caller is expecting the OCR string. Stick to the JAVA style. In case of an error - throw an EXCEPTION!
Next: you never actually use the "filePath" parameter. This is clearly a bug.
You first need to ask yourself WHAT to test. Is it the "imageService" method you want to test? Then create a second class and from there, you would test your method. Within this test class, you would take an example file, call your imageService and compare the result with what you would expect. Those kind of comparisons are done with Assert-statements. Please check the jUnit docs for more detail.

Alt-codes only work in Java string when run within Netbeans

I have a small java program that reads a given file with data and converts it to a csv file.
I've been trying to use the arrow symbols: ↑, ↓, → and ← (Alt+24 to 27) but unless the program is run from within Netbeans (Using F6), they will always come out as '?' in the resulting csv file.
I have tried using the unicodes, eg "\u2190" but it makes no difference.
Anyone know why this is happening?
As requested, here is a sample code that gives the same issue. This wont work when run using the .jar file, just creating a csv file containing '?', however running from within Netbeans works.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Sample {
String fileOutName = "testresult.csv";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
Sample test = new Sample();
test.saveTheArrow();
}
public void saveTheArrow() {
try (PrintWriter outputStream = new PrintWriter(fileOutName)) {
outputStream.print("←");
outputStream.close();
}
catch (FileNotFoundException e) {
// Do nothing
}
}
}
new PrintWriter(fileOutName) uses the default charset of the JVM - you may have different defaults in Netbeans and in the console.
Google Sheet uses UTF_8 according to this thread so it would make sense to save your file using that character set:
Files.write(Paths.get("testresult.csv"), "←".getBytes(UTF_8));
Using the "<-" character in your editor is for sure not the desired byte 0x27.
Use
outputStream.print( new String( new byte[] { 0x27}, StandardCharsets.US_ASCII);

Print job submitted to printer, but didn't print anything. Java

I have problem with Java print service. I need to print a simple text document, to my default printer. I use HP Deskjet as my printer on Windows machine, all driver installed. This is the source code I use:
import java.io.*;
import javax.print.*;
public class PrintTest {
public static void main(String[] args) throws IOException {
File file = new File("print.txt");
InputStream is = new BufferedInputStream(new FileInputStream(file));
//Discover the default print service.
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
//Doc flavor specifies the output format of the file.
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
// Create the print job
DocPrintJob job = service.createPrintJob();
//Create the Doc
Doc doc = new SimpleDoc(is, flavor, null);
//Order to print
try {
job.print(doc, null);
} catch (PrintException e) {
e.printStackTrace();
}
is.close();
System.out.println("Printing done....");
}
}
I can see the print job on printer queue for several milisecond before its gone. But nothing get printed. I have heard it's because Java Print Service in JDK 1.6 is still buggy. But I'm not entirely sure. Any ideas why?
I know it is a very late answer but I had the same problem on Windows with PDFs (not text). It seems that printers may not be able to deal with native PDFs, so the job is accepted but nothing happens (no error too). I solved this by using a third-party lib, Apache PdfBox, and it worked like a charm.
I wrote some code example by answering a similar question https://stackoverflow.com/a/39271053/935039.

PrintServiceLookup.lookupDefaultPrintService() returns null

PrintServiceLookup.lookupDefaultPrintService() returns NULL as I have a printer installed and set to default printer.
If I am using this in a simple program it works fine, but when I try to use it in my applet-based program it returns NULL.
Please send me some good solution for this problem.
In order to access the printer (or any resource on the host computer for that matter) the jar file in which the applet code resides has to be signed, and the user must accept the signer as a trusted party.
To sign the jar file, use the jarsigner program, which is part of he JDK. Jarsigner uses its own keystore, so if you have your own certificate, you must import the certificate to a keystore first. It can generate certificates as well, in the case you don't have any other certificate to sign the jar file with.
Documentation of the jarsigner tool can be found here.
Note that newer Java runtimes do ask the user if (s)he allows the code to access the printer, but I found that regardless of the answer, code in an unsigned jar file is prevented from accessing resources.
This code is working in an signed applet in windows with 1.7.0_55:
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
...
HashDocAttributeSet docAttr=new HashDocAttributeSet();
HashPrintRequestAttributeSet reqAttr=new HashPrintRequestAttributeSet();
try {
PrintService pserv = PrintServiceLookup.lookupDefaultPrintService();
if (pserv == null) {
System.out.println("ERROR-01: no default print service");
}
System.out.println("Printer: " + pserv.getName());
DocPrintJob job = pserv.createPrintJob();
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
String content = makeZplLabel();
Doc doc = new SimpleDoc(content.getBytes(), flavor, docAttr);
job.print(doc, reqAttr);
} catch (Exception e) {
System.out.println("ERROR-02:" + e.getMessage());
}
You must change the security settings for java applets first. By default, java applets cannot print.
Make sure that printer.conf defines <DefaultPrinter name> instead of <Printer name>. JVM seems to only find a default printer that is defined like this.
This code snippet could help out to quickly verify if it works:
import javax.print.PrintServiceLookup;
public class checkDefaultPrinter {
public static void main(String[] args) {
System.out.println(PrintServiceLookup.lookupDefaultPrintService());
}
}
In windows, make sure the Print Spooler service is running. Also, You can test this code while applying the solution
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
public class JavaPrintBug {
public static void main(String[] args) {
// returns an empty array unless a user has opened system printer settings
// only short time ago or an adminstrator has set cupsctl WebInterface=yes
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
System.out.println("Number of printers available: " + printServices.length); // zero
// returns null unless a user has opened system printer settings only
// short time ago or an adminstrator has set cupsctl WebInterface=yes
PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
if(null != defaultPrintService) { // will not be entered
System.out.println("Default printer: " + defaultPrintService.getName());
}
// before entering this loop make sure that NO user has opened system
// printer settings only short time ago and NO administrator has set
// cupsctl WebInterface=yes (hWebInterface=no)!
while(null == PrintServiceLookup.lookupDefaultPrintService()) {
// while trapped in here, open system printer settings or set
// cupsctl WebInterface=yes and the loop will be left.
// In Windows, enable the Print Spooler service
}
System.out.println("Workaround worked!");
}
}
Reference: https://bugs.openjdk.org/browse/JDK-8178715

Categories

Resources