I would like to print a jframe when clicking a button.
So i tried this code. If I click the print button, I get a printer dialog and when I tell it to print, it just prints a blank document, i don't know why. Any help?
public static class Printer implements Printable {
final Component comp;
public Printer(Component comp){
this.comp = comp;
}
#Override
public int print(Graphics g, PageFormat format, int page_index)
throws PrinterException {
if (page_index > 0) {
return Printable.NO_SUCH_PAGE;
}
// get the bounds of the component
Dimension dim = comp.getSize();
double cHeight = dim.getHeight();
double cWidth = dim.getWidth();
// get the bounds of the printable area
double pHeight = format.getImageableHeight();
double pWidth = format.getImageableWidth();
double pXStart = format.getImageableX();
double pYStart = format.getImageableY();
double xRatio = pWidth / cWidth;
double yRatio = pHeight / cHeight;
Graphics2D g2 = (Graphics2D) g;
g2.translate(pXStart, pYStart);
g2.scale(xRatio, yRatio);
comp.paint(g2);
return Printable.PAGE_EXISTS;
}
}
and in the button action performed
JFrame yourComponent = new ODietListJFrame();
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.LANDSCAPE);
PageFormat postformat = pjob.pageDialog(preformat);
//If user does not hit cancel then print.
if (preformat != postformat) {
//Set print component
pjob.setPrintable(new Printer(yourComponent), postformat);
if (pjob.printDialog()) {
try {
pjob.print();
} catch (PrinterException ex) {
Logger.getLogger(ODietListJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Thanks for help.
Related
I want to print an image on thermal printer, but when I use this code, the image gets smaller. How can I change the size of the image that I'm going to print?
public void printPhoto() throws Exception {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
pras.size();
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.PNG, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
PrintService ps = findPrintService("POS-58", pss);
System.out.println("Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
FileInputStream fin = new FileInputStream("D:\\QRCODE\\test.png");
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.PNG, null);
job.print(doc, pras);
fin.close();
}
Can anyone help me? This is for our school project. Thanks a lot.
I change my code to this
private static BufferedImage image;
public void PrintLogo(){
try {
image = ImageIO.read(new File("C:\\Users\\ADMIN\\Desktop\\logothermal.png"));
System.out.println(image.getWidth() + "x" + image.getHeight());
PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.defaultPage();
Paper paper = pf.getPaper();
// 86X54mm
double width = fromCMToPPI(7.6);
double height = fromCMToPPI(3.4);
paper.setSize(width, height);
paper.setImageableArea(
fromCMToPPI(0.1),
fromCMToPPI(0.1),
width - fromCMToPPI(0.1),
height - fromCMToPPI(0.1));
pf.setOrientation(PageFormat.PORTRAIT);
pf.setPaper(paper);
PageFormat validatePage = pj.validatePage(pf);
System.out.println("Valid- " + dump(validatePage));
pj.setPrintable(new MyPrintable(), validatePage);
try {
pj.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
public static double fromPPItoCM(double dpi) {
return dpi / 72 / 0.393700787;
}
public static double fromCMToPPI(double cm) {
return toPPI(cm * 0.393700787);
}
public static double toPPI(double inch) {
return inch * 72d;
}
public static String dump(Paper paper) {
StringBuilder sb = new StringBuilder(64);
sb.append(paper.getWidth()).append("x").append(paper.getHeight())
.append("/").append(paper.getImageableX()).append("x").
append(paper.getImageableY()).append(" - ").append(paper
.getImageableWidth()).append("x").append(paper.getImageableHeight());
return sb.toString();
}
public static String dump(PageFormat pf) {
Paper paper = pf.getPaper();
return dump(paper);
}
public static class MyPrintable implements Printable {
#Override
public int print(Graphics graphics, PageFormat pageFormat,
int pageIndex) throws PrinterException {
System.out.println(pageIndex);
int result = NO_SUCH_PAGE;
if (pageIndex < 1) {
Graphics2D g2d = (Graphics2D) graphics;
System.out.println("[Print] " + dump(pageFormat));
double width = pageFormat.getImageableWidth();
double height = pageFormat.getImageableHeight()/2;
System.out.println("Print Size = " + fromPPItoCM(width) + "x" +
fromPPItoCM(height));
g2d.translate((int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY());
Image scaled = null;
if (width > height) {
scaled = image.getScaledInstance((int)Math.round(width), -1,
Image.SCALE_SMOOTH);
} else {
scaled = image.getScaledInstance(-1, (int)Math.round(height),
Image.SCALE_SMOOTH);
}
g2d.drawImage(scaled, 0, 0, null);
result = PAGE_EXISTS;
}
return result;
}
}
I'm nervous about asking this because I'm scared I'll get told off. I am trying to print a JPanel that is about 4 pages long. It could be more, the data is from a JDBC MySql query, that could end up being many more that 4. The JPanel I am trying to print is full of other JPanels (with competitors race details on them) that I have added via a ListArray..
Anyway, I have scoured all day through stackoverflow and have found may examples of code that I have tried to implement. The printable class only prints the first page, so I have tried to implement the pageable class, but I just can't seem to get it right. I have tried to implement the Book class but don't know how to add my JPanel to the book. I have looked here, here and many more (I'm only allowed to post 2 links).
Here is my current code (that I got off one of the answers that #madprogrammer gave) -
int printButton = JOptionPane.showOptionDialog(null, scrollPane, "Race Winners", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, // no Icon
null, //do not use a custom Icon
options, //the titles of buttons
options[0]); //default button title
if (printButton == 0) {
try {
printComponent(pane, true);
//printComponentToFile(pane, false);
} catch (PrinterException exp) {
exp.printStackTrace();
}
public static void printComponent(JComponent comp, boolean fill) throws PrinterException {
PrinterJob pjob = PrinterJob.getPrinterJob();
//pjob.setPageable(comp);
PageFormat pf = pjob.defaultPage();
pf.setOrientation(PageFormat.PORTRAIT);
PageFormat postformat = pjob.pageDialog(pf);
if (pf != postformat) {
//Set print component
//pjob.setPageable(comp);
pjob.setPrintable(new ComponentPrinter(comp, fill), postformat);
if (pjob.printDialog()) {
pjob.print();
}
}
}
public static void printComponentToFile(Component comp, boolean fill) throws PrinterException {
Paper paper = new Paper();
paper.setSize(8.3 * 72, 11.7 * 72);
paper.setImageableArea(18, 18, 559, 783);
PageFormat pf = new PageFormat();
pf.setPaper(paper);
pf.setOrientation(PageFormat.PORTRAIT);
BufferedImage img = new BufferedImage(
(int) Math.round(pf.getWidth()), (int) Math.round(pf.getHeight()),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fill(new Rectangle(0, 0, img.getWidth(), img.getHeight()));
ComponentPrinter cp = new ComponentPrinter(comp, fill);
try {
cp.print(g2d, pf, 0);
} finally {
g2d.dispose();
}
try {
ImageIO.write(img, "png", new File("Page-" + (fill ? "Filled" : "") + ".png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static class ComponentPrinter implements Printable, Pageable {
private Component comp;
private boolean fill;
int numPages;
PageFormat format;
public ComponentPrinter(Component comp, boolean fill) {
this.comp = comp;
this.fill = fill;
}
#Override
public int print(Graphics g, PageFormat format, int page_index) throws PrinterException {
numPages = (int) Math.ceil(comp.getHeight() / format.getImageableY());
System.out.print(numPages);
if (page_index > 0) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) g;
g2.translate(format.getImageableX(), format.getImageableY());
//g2.translate(format.getImageableX(), format.getImageableY()- page_index*comp.getPreferredSize().height);
double width = (int) Math.floor(format.getImageableWidth());
double height = (int) Math.floor(format.getImageableHeight());
if (!fill) {
width = Math.min(width, comp.getPreferredSize().width);
height = Math.min(height, comp.getPreferredSize().height);
}
comp.setBounds(0, 0, (int) Math.floor(width), (int) Math.floor(height));
if (comp.getParent() == null) {
comp.addNotify();
}
comp.validate();
comp.doLayout();
comp.printAll(g2);
if (comp.getParent() != null) {
comp.removeNotify();
}
return Printable.PAGE_EXISTS;
}
#Override
public int getNumberOfPages() {
// TODO Auto-generated method stub
return numPages;
}
#Override
public PageFormat getPageFormat(int arg0) throws IndexOutOfBoundsException {
return format;
}
#Override
public Printable getPrintable(int arg0) throws IndexOutOfBoundsException {
// TODO Auto-generated method stub
return this;
}
}
This all works, but only prints the first page. I would REALLY appreciate a nudge in the right direction with this as I'm stumped. TIA :-)
This is how you print a Component (JPanel) on multiple pages:
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.*;
import javax.swing.RepaintManager;
public class PrintMultiPageUtil implements Printable, Pageable {
private Component componentToBePrinted;
private PageFormat format;
private int numPages;
public PrintMultiPageUtil(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
// get total space from component
Dimension totalSpace = this.componentToBePrinted.getPreferredSize();
// calculate for DIN A4
format = PrinterJob.getPrinterJob().defaultPage();
numPages = (int) Math.ceil(totalSpace .height/format.getImageableHeight());
}
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
// show page-dialog with default DIN A4
format = printJob.pageDialog(printJob.defaultPage());
printJob.setPrintable(this);
printJob.setPageable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if ((pageIndex < 0) | (pageIndex >= numPages)) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY() - pageIndex * pageFormat.getImageableHeight());
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
}
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
#Override
public int getNumberOfPages() {
// TODO Auto-generated method stub
return numPages;
}
#Override
public PageFormat getPageFormat(int arg0) throws IndexOutOfBoundsException {
return format;
}
#Override
public Printable getPrintable(int arg0) throws IndexOutOfBoundsException {
// TODO Auto-generated method stub
return this;
}
}
numPages
I changed the expression for numPages to:
(int) Math.ceil(page.height/format.getImageableHeight())
This divides the total height (height of the jpanel) through the height of one page, thus calculating the number of all pages.
g2d.translate
I did the following change: In this line:
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY() - pageIndex * pageFormat.getImageableHeight());
Changed componentToBePrinted.getPreferredSize().height to pageFormat.getImageableHeight(). A positive value for the first or the second parameter of g2d.translate moves the graphic to the right or down respectively.
.getImageableX() and .getImageableY() help position the graphic so that it doesn't overlap with the padding.
For pageIndex greater than 0, - pageIndex * pageFormat.getImageableHeight() moves the image pageIndex-times the page-height to the top. So the area, that the pageIndex refers to is printed.
original broken source:: https://community.oracle.com
Here is my original answer.
I'm trying to make a Java class in which a JFrame that contains JLabels will be printed on a full A5 page (The JFrame is set to be the size of an A5 page)
in order to do so I've used this class
http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/2d/printing/examples/PrintUIWindow.java
with this class that I've written
public class test2 extends PrintUIWindow {
public test2(JFrame f) {
super(f);
// TODO Auto-generated constructor stub
}
/**
* #param args
*/
public static void main(String[] args)
{
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f=new JFrame ("hello");
f.setLayout(null);
f.setSize(420,595);
JLabel test=new JLabel ("issuer");
f.add(test);
test.setBounds(new Rectangle(new Point(310, 50), test.getPreferredSize()));
f.setBackground(Color.white);
f.setVisible(true);
PrintUIWindow p=new PrintUIWindow (f);
p.actionPerformed(null);
}
}
the problem is that instead of printing the whole JFrame onto the page, it prints just a part of it and the rest is off the borders of the page
what could fix this problem?
Have a look at this
I also found this:
public static class Printer implements Printable {
final Component comp;
public Printer(Component comp) {
this.comp = comp;
}
#
Override
public int print(Graphics g, PageFormat format, int page_index)
throws PrinterException {
if (page_index > 0) {
return Printable.NO_SUCH_PAGE;
}
// get the bounds of the component
Dimension dim = comp.getSize();
double cHeight = dim.getHeight();
double cWidth = dim.getWidth();
// get the bounds of the printable area
double pHeight = format.getImageableHeight();
double pWidth = format.getImageableWidth();
double pXStart = format.getImageableX();
double pYStart = format.getImageableY();
double xRatio = pWidth / cWidth;
double yRatio = pHeight / cHeight;
Graphics2D g2 = (Graphics2D) g;
g2.translate(pXStart, pYStart);
g2.scale(xRatio, yRatio);
comp.paint(g2);
return Printable.PAGE_EXISTS;
}
}
To Print the frame using Printer class try this:
JFrame yourComponent = new JFrame();
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.LANDSCAPE);
PageFormat postformat = pjob.pageDialog(preformat);
if (preformat != postformat) {
pjob.setPrintable(new Printer(yourComponent), postformat);
if (pjob.printDialog()) {
pjob.print();
}
}
i currently have an issue with my printerjob, it works great for portrait images, but for landscape images, it cuts part of the image and fills in a white space instead.
This is my code
EDIT
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
BufferedImage bufferedImage = ImageIO.read(new File("house.jpg"));
boolean isLandscape = bufferedImage.getWidth() > bufferedImage.getHeight();
PrinterJob printerJob = PrinterJob.getPrinterJob();
printerJob.setPrintService(printService);
printerJob.setCopies(copies);
PageFormat pageFormat = printerJob.defaultPage();
pageFormat.setOrientation(isLandscape ? PageFormat.LANDSCAPE : PageFormat.PORTRAIT);
Paper paper = new Paper();
paper.setSize(pageFormat.getWidth(), pageFormat.getHeight());
paper.setImageableArea(0.0, 0.0, paper.getWidth(), paper.getHeight());
pageFormat.setPaper(paper);
printerJob.setPrintable(new Printable(){
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException{
if (pageIndex == 0) {
Graphics2D g2 = (Graphics2D)graphics;
double xScale = 1;
double xTranslate = 0;
double yScale = 1;
double yTranslate = 0;
double widthScale = (pageFormat.getImageableWidth() / bufferedImage.getWidth()) * xScale;
double heightScale = (pageFormat.getImageableHeight() / bufferedImage.getHeight()) * yScale;
AffineTransform affineTransform = AffineTransform.getScaleInstance(widthScale, heightScale);
affineTransform.translate(xTranslate, yTranslate);
g2.drawRenderedImage(bufferedImage, affineTransform);
g2.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY());
return PAGE_EXISTS;
}else return NO_SUCH_PAGE;
}
}, pageFormat);
printerJob.print();
This allows me to print portrait pictures to fit the given paper and without borders (fit to paper), i need it to do the same for landscape pictures please.
This are examples of what happens when i try with a portrait and landscape image so u see what i mean. The images should always fit to the paper size and borderless, which in this case is 10x15cm,
Portrait image:
Landscape image:
Don't use PageFormat#getWidth or PageFormat#getHeight, use PageFormat#getImageableWidth and PageFormat#getImageableHeight instead
From the JavaDocs
Return the height/width, in 1/72nds of an inch, of the imageable area of the page. This method takes into account the orientation of the page.
You should also translate the printer Graphics by the ImageableX/Y...
g2.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY());
Runnable example
This is a simple runnable example. This code was able to take the original (left) and print it both in portrait and landscape without issue...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class PrintTest100 {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
try {
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Print Component ");
PageFormat pf = pj.defaultPage();
// pf.setOrientation(PageFormat.LANDSCAPE);
// pf = pj.validatePage(pf);
pj.setPrintable(new ImagePrintable(ImageIO.read(new File("..."))), pf);
if (!pj.printDialog()) {
return;
}
try {
pj.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
}
public static class ImagePrintable implements Printable {
private int currentPage = -1;
private Image cachedScaledImage = null;
private BufferedImage master;
public ImagePrintable(BufferedImage master) {
this.master = master;
}
public double getScaleFactor(int iMasterSize, int iTargetSize) {
double dScale = 1;
if (iMasterSize > iTargetSize) {
dScale = (double) iTargetSize / (double) iMasterSize;
} else {
dScale = (double) iTargetSize / (double) iMasterSize;
}
return dScale;
}
public double getScaleFactorToFit(BufferedImage img, Dimension size) {
double dScale = 1;
if (img != null) {
int imageWidth = img.getWidth();
int imageHeight = img.getHeight();
dScale = getScaleFactorToFit(new Dimension(imageWidth, imageHeight), size);
}
return dScale;
}
public double getScaleFactorToFit(Dimension original, Dimension toFit) {
double dScale = 1d;
if (original != null && toFit != null) {
double dScaleWidth = getScaleFactor(original.width, toFit.width);
double dScaleHeight = getScaleFactor(original.height, toFit.height);
dScale = Math.min(dScaleHeight, dScaleWidth);
}
return dScale;
}
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int result = Printable.NO_SUCH_PAGE;
if (pageIndex == 0) {
result = Printable.PAGE_EXISTS;
Graphics2D graphics2D = (Graphics2D) graphics;
graphics2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
int width = (int) Math.round(pageFormat.getImageableWidth());
int height = (int) Math.round(pageFormat.getImageableHeight());
if (currentPage != pageIndex || cachedScaledImage == null) {
currentPage = pageIndex;
double scaleFactor = getScaleFactorToFit(new Dimension(master.getWidth(), master.getHeight()), new Dimension(width, height));
int imageWidth = (int) Math.round(master.getWidth() * scaleFactor);
int imageHeight = (int) Math.round(master.getHeight() * scaleFactor);
cachedScaledImage = master.getScaledInstance(imageWidth, imageHeight, Image.SCALE_SMOOTH);
}
double x = ((pageFormat.getImageableWidth() - cachedScaledImage.getWidth(null)) / 2);
double y = ((pageFormat.getImageableHeight() - cachedScaledImage.getHeight(null)) / 2);
graphics2D.drawImage(cachedScaledImage, (int) x, (int) y, null);
graphics2D.setColor(Color.RED);
graphics2D.drawRect(0, 0, width - 1, height - 1);
}
return result;
}
}
}
nb: I had an issue with Yosemite, trying to figure out how to change the print orientation from the dialog, in the end, I gave up and forced it by changing the PageFormat from the PrintJob. I've used this same type of code in countless applications without issues before...
Updated
Original Image: 1920x1200
I would like to know if there is a proper way of printing a BufferedImage in Java.
Basically I have created a photo manipulation program which works fine, I can save images etc.
But my real goal is to send it to the printer software so that you can select the amount of pages you want to print and page type.
So my shortened question is, how do I send a buffered image to the printer so that a printer selection screen will popup etc and then be able to print?
If anyone can show me an example of this, it would be greatly appreciated.
Here's one from one of my Java projects. This code will scale and print one image on a printer page.
You call it like this:
printButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
//Start a Thread
new Thread(new PrintActionListener(image)).start();
}
});
Here's the Runnable:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
public class PrintActionListener implements Runnable {
private BufferedImage image;
public PrintActionListener(BufferedImage image) {
this.image = image;
}
#Override
public void run() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(new ImagePrintable(printJob, image));
if (printJob.printDialog()) {
try {
printJob.print();
} catch (PrinterException prt) {
prt.printStackTrace();
}
}
}
public class ImagePrintable implements Printable {
private double x, y, width;
private int orientation;
private BufferedImage image;
public ImagePrintable(PrinterJob printJob, BufferedImage image) {
PageFormat pageFormat = printJob.defaultPage();
this.x = pageFormat.getImageableX();
this.y = pageFormat.getImageableY();
this.width = pageFormat.getImageableWidth();
this.orientation = pageFormat.getOrientation();
this.image = image;
}
#Override
public int print(Graphics g, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (pageIndex == 0) {
int pWidth = 0;
int pHeight = 0;
if (orientation == PageFormat.PORTRAIT) {
pWidth = (int) Math.min(width, (double) image.getWidth());
pHeight = pWidth * image.getHeight() / image.getWidth();
} else {
pHeight = (int) Math.min(width, (double) image.getHeight());
pWidth = pHeight * image.getWidth() / image.getHeight();
}
g.drawImage(image, (int) x, (int) y, pWidth, pHeight, null);
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}
}
}