java PrinterJob not printing to fit paper - java

i am stuck currently when printing a jpeg file with the default printer. In my program when i select an image from a folder, i need to print it using the printer default settings (paper size, margins, orientation).
Currently i got this:
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
final BufferedImage image = ImageIO.read(new File("car.jpg"));
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintService(printService);
printJob.setPrintable(new Printable(){
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException{
if (pageIndex == 0) {
graphics.drawImage(image, 0, 0, (int)pageFormat.getWidth(), (int)pageFormat.getHeight(), null);
return PAGE_EXISTS;
else return NO_SUCH_PAGE;
}
}
printJob.print();
The default settings for my printer right now for size is: 10 x 15 cm (4 x 6 in)
but when i set my program to print the given image, it displays only a small section of the paper.
Please help me out.
EDIT
thanks everyone for their help, i managed to find the answer posted by another user at Borderless printing

Make sure that you are, first, translating the Graphics context to fit within inthe imagable area...
g2d.translate((int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY());
Next, make sure you are using the imageableWidth and imageableHeight of the PageFormat
double width = pageFormat.getImageableWidth();
double height = pageFormat.getImageableHeight();
and not the width/height properties. Many of these things get translated from different contexts...
graphics.drawImage(image, 0, 0, (int)width, (int)height, null);
The getImageableWidth/Height returns the page size within the context of the page orientation
Printing pretty much assumes a dpi of 72 (don't stress, the printing API can handle much higher resolutions, but the core API assumes 72dpi)
This means that a page of 10x15cm should translate to 283.46456664x425.19684996 pixels. You can verify this information by using a System.out.println and dumping the results of getImageableWidth/Height to the console.
If you're getting different settings, it's possible that Java has overridden the default page properties
For example...
Fit image into the printing area
Setting print size of a jLabel and put a jRadiobutton on the print
You have two choices...
You could...
Show the PrintDialog and ensure that the correct page settings are selected
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new PrinterResolution(300, 300, PrinterResolution.DPI));
aset.add(new MediaPrintableArea(0, 0, 150, 100, MediaPrintableArea.MM));
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(new PrintTask()); // You Printable here
if (pj.printDialog(aset)) {
try {
pj.print(aset);
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
Or you could...
Just manually set the paper/page values manually...
public static void main(String[] args) {
PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.defaultPage();
Paper paper = pf.getPaper();
// 10x15mm
double width = cmsToPixel(10, 72);
double height = cmsToPixel(15, 72);
paper.setSize(width, height);
// 10 mm border...
paper.setImageableArea(
cmsToPixel(0.1, 72),
cmsToPixel(0.1, 72),
width - cmsToPixel(0.1, 72),
height - cmsToPixel(0.1, 72));
// Orientation
pf.setOrientation(PageFormat.PORTRAIT);
pf.setPaper(paper);
PageFormat validatePage = pj.validatePage(pf);
pj.setPrintable(new Printable() {
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
// Your code here
return NO_SUCH_PAGE;
}
}, validatePage);
try {
pj.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
// The number of CMs per Inch
public static final double CM_PER_INCH = 0.393700787d;
// The number of Inches per CMs
public static final double INCH_PER_CM = 2.545d;
// The number of Inches per mm's
public static final double INCH_PER_MM = 25.45d;
/**
* Converts the given pixels to cm's based on the supplied DPI
*
* #param pixels
* #param dpi
* #return
*/
public static double pixelsToCms(double pixels, double dpi) {
return inchesToCms(pixels / dpi);
}
/**
* Converts the given cm's to pixels based on the supplied DPI
*
* #param cms
* #param dpi
* #return
*/
public static double cmsToPixel(double cms, double dpi) {
return cmToInches(cms) * dpi;
}
/**
* Converts the given cm's to inches
*
* #param cms
* #return
*/
public static double cmToInches(double cms) {
return cms * CM_PER_INCH;
}
/**
* Converts the given inches to cm's
*
* #param inch
* #return
*/
public static double inchesToCms(double inch) {
return inch * INCH_PER_CM;
}

It looks like you are printing the image with dimensions based on the PageFormat, rather than the actual image's dimensions, your drawImage() method should look something like this
graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null)

Related

Writing Graphics2D to BufferedImage - Poor Font resolution

So I'm trying to create labels for a generalized purpose by drawing to a Graphics2D object in a BufferedImage and then using ImageIO.write() to write this to a file. Unfortunately I'm encountering an issue where I can't figure out how to make the quality of the Font not 'blurred' (i can't think of the word in English, the edges are a bit cut or jagged, sort of indicative of low render resolution I guess). Is there a way to set it so that the Font renders at a certain DPI/Quality/Resolution?
This is what I get when I render the image. Notice the barcode I generated separately is not 'blurred' per se but the Font is.
/**
*
* #param data Array of Strings passed into label, where data[0] is the string to be barcoded
* #param titles Array of Strings passed into label parallel to data array, containing appropriate titles
* #throws IOException If
* #throws WriterException
*/
public static File createSeedBag(String[] titles,String[] data, Font[] fonts) throws IOException, WriterException{
/**
* TODO: Array of Fonts to customize Font
* Size customization
*/
BufferedImage theLabel;
BufferedImage theBarcode;
Graphics2D theGraphics;
File imageFile,
theFile;
FontMetrics titleMetrics,
theMetrics;
int width = 300;
int height = 450;
theLabel = new BufferedImage(width,height, BufferedImage.TYPE_BYTE_GRAY);
imageFile = LabelPrinter.writeBarCode(data[0], BarcodeSpecs.LARGE);
theGraphics = theLabel.createGraphics();
theGraphics.setPaint(Color.WHITE);
theGraphics.fillRect(0, 0, theLabel.getWidth(), theLabel.getHeight());
theGraphics.setPaint(Color.BLACK);
theGraphics.drawRect(0, 0, theLabel.getWidth()-1, theLabel.getHeight()-1);
/**
* Font objects
*/
fonts[0] = new Font("Bodoni 72", Font.BOLD, 40);
theGraphics.setFont(fonts[0]);
/**
* 1) Read Image File and set to bottom of label
*
* 2)
*/
theBarcode = ImageIO.read(imageFile);
theGraphics.drawImage(theBarcode, 1, height - 61, null);
titleMetrics = theGraphics.getFontMetrics(fonts[0]);
theGraphics.drawString(data[data.length-1], (width/2) - ((titleMetrics.stringWidth(data[data.length-1])) / 2), 50);
fonts[1]= new Font("Bodoni 72",0,20);
theMetrics = theGraphics.getFontMetrics(fonts[1]);
int stringHeight = theMetrics.getAscent();
theGraphics.setFont(fonts[1]);
for(int i = 1; i< data.length; i++) {
theGraphics.drawString(titles[i] + ": " + data[i], 5, 50 + (stringHeight * (i+1)));
}
theFile = new File("currentLabel.png");
ImageIO.write(theLabel, "png", theFile);
imageFile.deleteOnExit();
return theFile;
}

Java: Setting printable width (Pageformat)

I am attempting to print from my java application to a receipt printer,
the width of the receipt is 58mm, it seems that the margin is incorrect and printing with a margin of 1 inch on either side. This results in only 3 letters/numbers being printed and not the full line.
I can print from notepad successfully as I have manually adjusted the margin to 1.97mm on either side which seems to do the trick.
My code is as follows;
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
Font font = new Font("MONOSPACED", Font.PLAIN, 10);
FontMetrics metrics = g.getFontMetrics(font);
int lineHeight = metrics.getHeight();
if (pageBreaks == null) {
initTextLines();
int linesPerPage = (int)(pf.getImageableHeight()/lineHeight);
int numBreaks = (textLines.length-1)/linesPerPage;
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.setFont(new Font("MONOSPACED", Font.PLAIN, 10));
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;
}
I would also be grateful if you could help me align the text to the right hand side of the receipt to keep it uniformed with out other systems, however my main issue is the margin if that is sorted I will be over the moon :)
Thank You!
p.s. I am new to printing from java and have struggled, might have redundant code from copying online sources. I have adjusted the font so it is smaller, that did not help much.
I have figured out a workaround to get the desired results, just adding spaces before the text seems to work out well, I have also adjusted the code as follows;
public void print() throws PrintException, IOException {
String defaultPrinter =
PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
InputStream is = new ByteArrayInputStream(printableAmounts.getBytes("UTF8"));
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc doc = new SimpleDoc(is, flavor, null);
DocPrintJob job = service.createPrintJob();
PrintJobWatcher pjw = new PrintJobWatcher(job);
job.print(doc, pras);
pjw.waitForDone();
is.close();
}
Seems to be a temporary solution but if nothing else comes up it will become permanent.

Issue with printing long receipts with java print() on thermal printer

I cannot print a thermal receipt (8cm) beyond (almost) A4 height paper size. Program only prints till (some default almost) A4 size is reached. and rest of receipt is lost.
Everything works fine with smaller receipts. problem occurs only with long receipts, where bill is cut short. I dynamically set paper height counting the lines to print. I also tried setting paper size and imageablearea to big size manually but in vain.
I tried to use Print.Book class object as well with no improvement.
(Note: Another program written in another language, prints same bill fine on same printer)
Please let me know if I am missing something or how to remove this limitation.
public void printReciept()
{
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(new BillPrintable(),getPageFormat(pj));
try {
pj.print();
}
catch (PrinterException ex) {
ex.printStackTrace();
}
}
public PageFormat getPageFormat(PrinterJob pj)
{
PageFormat pf = pj.defaultPage();
Paper paper = pf.getPaper();
double middleHeight =this.productList.size()*1.0; //dynamic----->change with the row count of jtable
double headerHeight = 5.0; //fixed----->but can be mod
double footerHeight = 5.0; //fixed----->but can be mod
double width = convert_CM_To_PPI(8); //printer know only point per inch.default value is 72ppi
double height = convert_CM_To_PPI(headerHeight+middleHeight+footerHeight);
paper.setSize(width, height);
paper.setImageableArea(
0,
10,
width,
height - convert_CM_To_PPI(1)
); //define boarder size after that print area width is about 180 points
pf.setOrientation(PageFormat.PORTRAIT); //select orientation portrait or landscape but for this time portrait
pf.setPaper(paper);
return pf;
}
public class BillPrintable implements Printable {
#Override
public int print(Graphics graphics, PageFormat pageFormat,int pageIndex)
throws PrinterException
{
String title[] = {"Product Name","Disc","Rate","Qty","AMT"};
int result = NO_SUCH_PAGE;
if (pageIndex == 0) {
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate((int) pageFormat.getImageableX(),(int) pageFormat.getImageableY());
***** Below will be Code to print bill records *****
}
}

Resizing image to fit frame

A part of my application is working as a tutorial. For that purpose I got JPanels that display a JLabel that has an image as content. Although when the image is larger than what fits the screen it will just cut what doesn't fit. What I need to do is resize the image so that I will fit the space the JLabel is given. Also tried using JScrollPanes but didn't make any difference(although I prefer to resize image).
I tried getting a scaled instance of the image using
Image scaledImg = myPicture.getScaledInstance(width, height, Image.SCALE_SMOOTH);
but it didn't make any difference.
This is the current code :
private JLabel getTutorialLabel(int type) {
String path = "/Images/Tutorial/test" + type + ".png";
try {
BufferedImage tutorialPic = ImageIO.read(getClass().getResource(path));
// int height = (int) (screenDim.height * 0.9);
// int width = (int) (screenDim.width * 0.9);
// Image scaledImg = myPicture.getScaledInstance(width, height, Image.SCALE_SMOOTH);
JLabel picLabel = new JLabel(new ImageIcon(tutorialPic));
return picLabel;
} catch (IOException ex) {
Logger.getLogger(Tutorial.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
How I get the image to display properly?
Please note that there are other components displayed along with the JLabel(JMenuBar and some buttons on bottom of screen) so I need to image to fill the space JLabel is given.
Edit: updated the method
You could try this method in the Java Helper Library.
Or, here's the method itself:
/**
* This method resizes the given image using Image.SCALE_SMOOTH.
*
* #param image the image to be resized
* #param width the desired width of the new image. Negative values force the only constraint to be height.
* #param height the desired height of the new image. Negative values force the only constraint to be width.
* #param max if true, sets the width and height as maximum heights and widths, if false, they are minimums.
* #return the resized image.
*/
public static Image resizeImage(Image image, int width, int height, boolean max) {
if (width < 0 && height > 0) {
return resizeImageBy(image, height, false);
} else if (width > 0 && height < 0) {
return resizeImageBy(image, width, true);
} else if (width < 0 && height < 0) {
PrinterHelper.printErr("Setting the image size to (width, height) of: ("
+ width + ", " + height + ") effectively means \"do nothing\"... Returning original image");
return image;
//alternatively you can use System.err.println("");
//or you could just ignore this case
}
int currentHeight = image.getHeight(null);
int currentWidth = image.getWidth(null);
int expectedWidth = (height * currentWidth) / currentHeight;
//Size will be set to the height
//unless the expectedWidth is greater than the width and the constraint is maximum
//or the expectedWidth is less than the width and the constraint is minimum
int size = height;
if (max && expectedWidth > width) {
size = width;
} else if (!max && expectedWidth < width) {
size = width;
}
return resizeImageBy(image, size, (size == width));
}
/**
* Resizes the given image using Image.SCALE_SMOOTH.
*
* #param image the image to be resized
* #param size the size to resize the width/height by (see setWidth)
* #param setWidth whether the size applies to the height or to the width
* #return the resized image
*/
public static Image resizeImageBy(Image image, int size, boolean setWidth) {
if (setWidth) {
return image.getScaledInstance(size, -1, Image.SCALE_SMOOTH);
} else {
return image.getScaledInstance(-1, size, Image.SCALE_SMOOTH);
}
}

Fix text stretching when printing to a receipt printer with Java

I am printing to some Epson receipt printers by implementing the Java Printable and placing my code into the print method. To draw the text to the printer I use Graphics2D.drawString. I am also drawing a rect to the printer to see how to compares to the text size when printing to other printers. When printing to the receipt printer the text on the paper is about double the width of printing to a laser printer or the XPS writer virtual print. Is this a problem with the way Java draws text to the Graphics2D object? I have the newest version of Java installed of 6 update 20.
Any Ideas of what to look into would be helpful.
Thanks.
Here the code I am using. With this example I am seeing the letter 'c' on the right edge of the rect when sending it to a XPS writer and if I print it to my receipt printer the 6 is on the right edge of the rect and you can tell the text is much wider then it should be. The rect seems to be the correct size.
I have tried changing the page and margin sizes but it does not seem to fix my text problem. I got these paper sizes and margins from how Microsoft Word is auto detecting the printer. Word prints the text correctly to the receipt printer.
public static void main(String[] args) {
PageFormat format = new PageFormat();
Paper paper = new Paper();
double paperWidth = 3.25;
double paperHeight = 11.69;
double leftMargin = 0.19;
double rightMargin = 0.25;
double topMargin = 0;
double bottomMargin = 0.01;
paper.setSize(paperWidth * 72.0, paperHeight * 72.0);
paper.setImageableArea(leftMargin * 72.0, topMargin * 72.0,
(paperWidth - leftMargin - rightMargin) * 72.0,
(paperHeight - topMargin - bottomMargin) * 72.0);
format.setPaper(paper);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.PORTRAIT);
PrinterJob printerJob = PrinterJob.getPrinterJob();
Printable printable = new ReceiptPrintTest();
format = printerJob.validatePage(format);
printerJob.setPrintable(printable, format);
try {
printerJob.print(aset);
}
catch (Exception e) {
e.printStackTrace();
}
}
public class ReceiptPrintTest implements Printable {
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex < 0 || pageIndex >= 1) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
Font font = new Font("Arial",Font.PLAIN, 14);
g2d.setFont(font);
g2d.drawString("1234567890abcdefg", 50, 70);
g2d.drawRect(50, 0, 100, 50);
return Printable.PAGE_EXISTS;
}
Have you tried setting the font using setFont?

Categories