Printing problem!
Hello guys!I'm trying to both print to printer and at the same time produce an image that I will need later on.
Both must be in good quality.
How ever I created a class (ObjectToPrint) that extends from JPanel and implements Printable.
I override:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.RED);
g2d.drawString("Hola amigos!", 20, 20);
g2d.drawString("How are you doing!", 20, 40);
g2d.drawString("Merry X-mas!", 20, 60);
}
In print I can print it nice with the code below, but when producing the image (at the same time) it is disaster.
public int print(Graphics graphics, PageFormat pageFormat, int pageNr) throws PrinterException
{
if(pageNr > 0)
{
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
//Works fine with good quality
paintComponent(g2d);
// Works bad with poor quality
/*
int width = (int)Math.round(pageFormat.getImageableWidth()) ;
int height = (int)Math.round(pageFormat.getImageableHeight());
offScreenCanvas = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D offScreenG2 = offScreenCanvas.createGraphics();
paintComponent(offScreenG2);
g2d.drawImage(offScreenCanvas, 0, 0, main);
*/
return PAGE_EXISTS;
}
FYI I print the printable like:
final PrinterJob printJob = PrinterJob.getPrinterJob();
final PageFormat pageFormat = printJob.defaultPage();
objectToPrint = new ObjectToPrint(instance, pageFormat);
final Paper paper = pageFormat.getPaper();
paper.setImageableArea(PRINT_MARGIN, PRINT_MARGIN, paper.getWidth(), paper.getHeight());
pageFormat.setPaper(paper);
printJob.setPrintService(printer);
printJob.setPrintable(objectToPrint, pageFormat);
//HashPrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
//PrinterResolution pr = new PrinterResolution(300, 300, ResolutionSyntax.DPI);
//set.add(pr);
//printJob.print(set);
printJob.print();
If you guys got any idea how to get the image nice too it would be great!
Best reagrds!
/Fredrik from sweden