Print text File to specific printer in java - java

I have a text file, and I need to print it to a specific network printer. I know the name of the printer.
Until now I have made a Printable class to print my file (ticket).
public class TicketPrintPage implements Printable {
private File ticket;
public TicketPrintPage(File f) {
ticket = f;
}
public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
int interline = 12;
Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("CourierThai", Font.PLAIN, 10));
int x = (int) pf.getImageableX();
int y = (int) pf.getImageableY();
try {
FileReader fr = new FileReader(ticket);
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
y += interline;
g2.drawString(s, x, y);
}
} catch (IOException e) {
throw new PrinterException("File to print does not exist (" + ticket.getAbsolutePath() +") !");
}
return Printable.PAGE_EXISTS;
}
}
I call this TicketPrintPage this way :
public void printTicketFile(File ticket, int orientation) throws PrinterException {
if (!ticket.exists()) {
throw new PrinterException("Ticket to print does not exist (" + ticket.getAbsolutePath() + ") !");
}
PrinterJob pjob = PrinterJob.getPrinterJob();
// get printer using PrintServiceLookup.lookupPrintServices(null, null) and looking at the name
pjob.setPrintService(getPrintService());
// job title
pjob.setJobName(ticket.getName());
// page fomat
PageFormat pf = pjob.defaultPage();
// landscape or portrait
pf.setOrientation(orientation);
// Paper properties
Paper a4Paper = new Paper();
double paperWidth = 8.26;
double paperHeight = 11.69;
double margin = 16;
a4Paper.setSize(paperWidth * 72.0, paperHeight * 72.0);
a4Paper.setImageableArea(
margin,
//0,
margin,
//0,
a4Paper.getWidth()- 2 * margin,
//a4Paper.getWidth(),
a4Paper.getHeight()- 2 * margin
//a4Paper.getHeight()
); // no margin = no scaling
pf.setPaper(a4Paper);
// Custom class that defines how to layout file text
TicketPrintPage pages = new TicketPrintPage(ticket);
// adding the page to a book
Book book = new Book();
book.append(pages, pf);
// Adding the book to a printjob
pjob.setPageable(book);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
// No jobsheet (banner page, the page with user name, job name, date and whatnot)
pras.add(JobSheets.NONE);
// Printing
pjob.print(pras);
}
It works not so bad but :
- I doesn't work for more than one page of text (found some algorithms for that but well)
- I can't get to know when the printer is done printing, and if I try printing two or more tickets in a row the printer will return a Printer not ready message.
So the question again is : Isn't there a simple way to print a text file to a printer ?

JTextComponent#print should do the trick:
JTextPane jtp = new JTextPane();
jtp.setBackground(Color.white);
jtp.setText("text to print");
boolean show = true;
try {
jtp.print(null, null, show, null, null, show);
} catch (java.awt.print.PrinterException ex) {
ex.printStackTrace();
}
in this manner you can quickly print out even nice formatted text - just create a StyledDocument and attach it to JTextPane before printing.

I'm not sure if this solves your problem but I use the following to print a text file
FileInputStream textStream;
textStream = new FileInputStream(FILE_NAME);
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc mydoc = new SimpleDoc(textStream, flavor, null);
PrintService[] services = PrintServiceLookup.lookupPrintServices(
flavor, aset);
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
if(services.length == 0) {
if(defaultService == null) {
//no printer found
} else {
//print using default
DocPrintJob job = defaultService.createPrintJob();
job.print(mydoc, aset);
}
} else {
//built in UI for printing you may not use this
PrintService service = ServiceUI.printDialog(null, 200, 200, services, defaultService, flavor, aset);
if (service != null)
{
DocPrintJob job = service.createPrintJob();
job.print(mydoc, aset);
}
}
You may not need the ServiceUI, but I think you could use PrintService[] services to get a list of printers available for printing. And using an input stream and the Doc class you can print a file to a printer.

Related

java pdfbox printerjob wrong size on label

I create with my application a PDF file which has exactly the dimensions of the label. When I print this file with Adobe Reader, the result is from the top. When I print it in Java, not everything is printed.
= Adobe, 2. pdfbox
public static PrintService choosePrinter(String printerName) {
PrintService[] service = PrinterJob.lookupPrintServices(); // list of printers
PrintService printService = null;
int count = service.length;
for (int i = 0; i < count; i++) {
if (service[i].getName().equalsIgnoreCase(printerName)) {
printService = service[i];
i = count;
}
}
return printService;
}
public static void printPDF(String fileName, PrinterSetting printerSetting) throws IOException, PrinterException {
PDDocument pdf = PDDocument.load(new File(fileName));
PrinterJob job = PrinterJob.getPrinterJob();
// define custom paper
Paper paper = new Paper();
paper.setSize( printerSetting.getPageHeight(), printerSetting.getPageWidth()); // 1/72 inch
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
// custom page format
PageFormat pageFormat = new PageFormat();
pageFormat.setPaper(paper);
pageFormat.setOrientation(PageFormat.LANDSCAPE);
// override the page format
Book book = new Book();
// append all pages
PDFPrintable pdfPrintable = new PDFPrintable(pdf, Scaling.SHRINK_TO_FIT);
book.append(pdfPrintable, pageFormat, pdf.getNumberOfPages());
job.setPageable(book);
PrintService printService = choosePrinter(printerSetting.getPrinterName());
if(printService != null)
job.setPrintService(printService);
job.print();
}

Java code not able to print long receipt in thermal printer

My java thermal printer code not able to print long receipt(more than A4 sheet size). Its work fine normally, but in case where there is too much items in cart then it generate half print. My code is under mentioned-
public PrintReceipt(Map<String,String> hm){
/*
product details code..
*/
try{
input = new FileInputStream("C:/printer.properties");
prop.load(input);
printerName=prop.getProperty("receiptPrinter");
System.out.println("Printer Name "+printerName);
}catch(Exception exception){
System.out.println("Properties file not found");
}
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null,null);
for (int i = 0; i < pservices.length; i++) {
if (pservices[i].getName().equalsIgnoreCase(printerName)) {
job = PrinterJob.getPrinterJob();
PageFormat pf = job.defaultPage();
double margin = 1.0D;
Paper paper = new Paper();
paper.setSize(216D, paper.getHeight());
paper.setImageableArea(margin, margin, paper.getWidth() - margin * 1.5D, paper.getHeight() - margin * 1.5D);
pf.setPaper(paper);
job.setCopies(1);
pf.setOrientation(1);
job.setPrintable(this, pf);
try
{
job.print();
}
catch(PrinterException ex)
{
System.out.println("Printing failed");
}
}
}
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if(pageIndex > 0)
return 1;
Graphics2D g2d = (Graphics2D)graphics;
double width = pageFormat.getImageableWidth();
double height = pageFormat.getImageableHeight();
g2d.translate((int) pageFormat.getImageableX(),(int) pageFormat.getImageableY());
Font font = new Font("Monospaced",Font.BOLD,8);
g2d.setFont(font);
try {
/*
* Draw Image*
*/
int x=50 ;
int y=10;
int imagewidth=100;
int imageheight=50;
BufferedImage read = ImageIO.read(new File("C:/hotel.png"));
g2d.drawImage(read,x,y,imagewidth,imageheight,null); //draw image
g2d.drawString("-- * Resturant * --", 20,y+60);
g2d.drawLine(10, y+70, 180, y+70); //draw line
} catch (IOException e) {
e.printStackTrace();
}
try{
/*Draw Header*/
/*
product details code..
*/
/*Footer*/
//end of the receipt
}
catch(Exception r){
r.printStackTrace();
}
return 0;
}
Please let me know how can i generate long receipt print by correcting my code or if you have any better solution to do this.
Right here:
Paper paper = new Paper();
paper.setSize(216D, paper.getHeight());
You are creating a new Paper object and not setting its height.
Here is a link to the documentation of this class.
When creating a Paper object, it is the application's responsibility to ensure that the paper size and the imageable area are compatible
You need to set the height of the paper by calling paper.setSize(width, height) or it will use its default size property.
The dimensions are supplied in 1/72nds of an inch.
So both width and height will need to be provided in this format as doubles
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService printService[] = PrintServiceLookup.lookupPrintServices(
flavor, pras);
PrintService service = findPrintService(printerName, printService);
PDDocument document = PDDocument.load(bytes);
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(service);
job.setPageable(new PDFPageable(document));
job.print();
if (document != null) {
document.close();
}

Printing a text document using Java

Alright, I have made a program that makes a text file. The text file is a different size every time the program is ran. I simply just want to add a print button that allows the user to print out the text file to a printer. I made a button with an action listener that brings up my print class. It is almost working except it only prints one page with my text displayed in horizontal columns extremely small. I think my problem has something to do with my printJob setup. Any help would be greatly appreciated.
public class PrintingClass implements Printable {
// Global variables
int[] pageBreaks;
String [] textLines;
static String fileName;
public static void print(String filename){
fileName = filename;
PrintingClass object = new PrintingClass();
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(object);
Boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}
}
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
Font font = new Font("Monospaced", Font.PLAIN, 12);
FontMetrics metrics = g.getFontMetrics(font);
int lineHeight = metrics.getHeight();
if (pageBreaks == null) {
initTextLines();
int linesPerPage = (int)(pf.getImageableHeight()/lineHeight);
System.out.println("Lines per page = " + linesPerPage);
int numBreaks = (textLines.length-1)/linesPerPage;
System.out.println("number of pages = " + numBreaks);
pageBreaks = new int[numBreaks];
for (int b=0; b<numBreaks; b++) {
pageBreaks[b] = (b+1)*linesPerPage;
}
}
if (pageIndex > pageBreaks.length) {
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
* Since we are drawing text we
*/
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Draw each line that is on this page.
* Increment 'y' position by lineHeight for each line.
*/
int y = 0;
int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex-1];
int end = (pageIndex == pageBreaks.length)
? textLines.length : pageBreaks[pageIndex];
for (int line=start; line<end; line++) {
y += lineHeight;
g.drawString(textLines[line], 0, y);
}
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
/**
* This will initialize the textLines[] variable
* and read in my file
* #param fileName
*/
public void initTextLines(){
// Get file size
int fileSize = counter();
// Initialize textLine
textLines = new String[fileSize];
// Read text to set lines
BufferedReader file;
try {
file = new BufferedReader(new FileReader(fileName));
String line = null;
int x = 0;
while((line = file.readLine()) != null){
textLines[x] = line;
x++;
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* This will simply count the size of the file
* and return it
* #return
*/
public int counter(){
int count = 0;
try {
BufferedReader file = new BufferedReader(new FileReader(fileName));
while(file.readLine() != null){
count++;
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
return count;
}
}
Most of this code comes straight from Javas own tutorial page. Thank you.

Print HTML File in Java

I need to print a HTML File from my Java Application.
I have tried several methods.
Two of them are working, but not as expected.
Method 1:
Problem: The Print is cut of after three-quarter of the sheet.
try {
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = new PageFormat();
pageFormat.setOrientation(PageFormat.LANDSCAPE);
Paper paper = new Paper(); // Set to A4 size.
paper.setSize(594.936, 841.536); // Set the margins.
paper.setImageableArea(0, 0, 594.936, 841.536);
pageFormat.setPaper(paper);
XHTMLPanel panel = new XHTMLPanel();
panel.setDocument(new File("./documents/" + "Personalstamm"
+ ".html"));
printJob.setPrintable(new XHTMLPrintable(panel), pageFormat);
if (printJob.printDialog()) {
printJob.print();
}
} catch (Exception x) {
x.printStackTrace();
}
Method 2:
Problem: The printout is without the Stylesheet set in the HTML file.
PageFormat pageFormat = new PageFormat();
Paper a4paper = new Paper();
double paperWidth = 8.26;
double paperHeight = 11.69;
a4paper.setSize(paperWidth * 72.0, paperHeight * 72.0);
/*
* set the margins respectively the imageable area
*/
double leftMargin = 0.78; /* should be about 2cm */
double rightMargin = 0.78;
double topMargin = 0.78;
double bottomMargin = 0.78;
a4paper.setImageableArea(leftMargin * 72.0, topMargin * 72.0,
(paperWidth - leftMargin - rightMargin) * 72.0, (paperHeight
- topMargin - bottomMargin) * 72.0);
pageFormat.setPaper(a4paper);
pageFormat.setOrientation(PageFormat.LANDSCAPE);
DocumentRenderer documentRenderer = new DocumentRenderer(pageFormat,
"Report");
try {
FileInputStream stringReader = new FileInputStream(new File(
"./documents/" + "Personalstamm" + ".html"));
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument) htmlKit
.createDefaultDocument();
htmlKit.read(stringReader, htmlDoc, 0);
documentRenderer.print(htmlDoc);
} catch (Exception x) {
x.printStackTrace();
}
Does anybody have an idea how to solve the problem in one of these methods?
Or do anybody have a better way to print a file from Java?
You can't print your HTML with CSS. The best shot that you got is to use PDFs, that's what they are for. Create a PDF from the HTML using Java and print it
Now i am using Apache PDFBox - A Java PDF Library and it's nearly what i was looking for.
My Code:
public void printFile(String fileName) {
//Convert to PDF
try {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(new File("./documents/html/"+fileName+".html"));
renderer.layout();
String fileNameWithPath = "./documents/pdf/"+fileName+".pdf";
FileOutputStream fos = new FileOutputStream(fileNameWithPath);
renderer.createPDF(fos);
fos.close();
} catch (Exception x) {
x.printStackTrace();
}
//Print with Dialog
try {
PrinterJob printJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = new PageFormat();
pageFormat.setOrientation(PageFormat.LANDSCAPE);
Paper paper = new Paper();
paper.setSize(595, 842);
paper.setImageableArea(0, 0, 595, 842);
pageFormat.setPaper(paper);
PDDocument doc = PDDocument.load(new File("./documents/pdf/"+fileName+".pdf"));
printJob.setPrintable(new PDPageable(doc), pageFormat);
if (printJob.printDialog()) {
printJob.print();
}
doc.close();
} catch (Exception x) {
x.printStackTrace();
}
}
Using Jasper Reports might solve the problem.

Java Printing Font Stretch

I just got the printer to work in java how I need it too, but there's one last problem I need to solve. When it prints, the font's width is rather stretched, and not crisp and clear like it should be.
Here is my code my the actual drawing to the paper:
FontMetrics metrics = graphics.getFontMetrics(font);
int lineHeight = metrics.getHeight();
arrangePage(graphics, pageFormat, lineHeight);
if (page > pageBreaks.length){
return NO_SUCH_PAGE;
}
Graphics2D g = (Graphics2D) graphics;
g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g.setFont(font);
int y = 0;
int begin = 0;
if (page == 0){
begin = 0;
}else begin = pageBreaks[page-1];
int end = 0;
if (page == pageBreaks.length){
end = lines.length;
}else end = pageBreaks[page];
for (int line = begin; line < end; line++){
y += lineHeight;
g.drawString(lines[line], 0, y);
}
string = deepCopy;
return PAGE_EXISTS;
How do I get rid of the stretching? It can be noted that this is based off this tutorial:
http://docs.oracle.com/javase/tutorial/2d/printing/set.html
Any advice or help is greatly appreciated.
The default DPI is normal 72 DPI (I believe), which, on printed paper, is pretty terrible. You need to prompt the print API to try and find a printer with a better DPI.
Basically you need to use the print services API.
Try something like...
public class PrintTest01 {
public static void main(String[] args) {
PrinterResolution pr = new PrinterResolution(300, 300, PrinterResolution.DPI);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
aset.add(pr);
aset.add(OrientationRequested.PORTRAIT);
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(new Page());
try {
pj.print(aset);
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
public static class Page implements Printable {
#Override
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g.setFont(new Font("Arial", Font.PLAIN, 128));
FontMetrics fm = g.getFontMetrics();
int x = (int)(pageFormat.getWidth() - fm.stringWidth("A")) / 2;
int y = (int)((pageFormat.getHeight() - fm.getHeight()) / 2) + fm.getAscent();
g2d.drawString("A", x, y);
return PAGE_EXISTS;
}
}
}
You might find Working with Print Services and Attributes of some help...
I should warn you, this is going to print to the first print that it can find that meets the PrintRequestAttributeSet. You could also add in the print dialog to see what's it doing, but that's another level of complexity I can live without right now ;)
The above worked! To open a print dialog with it, use this:
PrinterJob job = PrinterJob.getPrinterJob();
TextDocumentPrinter document = new TextDocumentPrinter();
PrinterResolution pr = new PrinterResolution(300, 300, PrinterResolution.DPI);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
aset.add(pr);
aset.add(OrientationRequested.PORTRAIT);
job.setPrintable(document);
boolean doPrint = false;
if (showDialog){
doPrint = job.printDialog(aset);
}else doPrint = true;
if (doPrint){
try{
job.print();
}catch(PrinterException e){
e.printStackTrace();
}
}
The aset variable contains all of your new default values, and by plugging it into the printDialog, those are inputted into the printJob and consequently show up on the paper! They can be changed in the dialog, as well.

Categories