Skip to content

Instantly share code, notes, and snippets.

@Vzor-
Last active July 21, 2022 14:54
Show Gist options
  • Save Vzor-/fe9ab75588f3c216360068e94c6a7672 to your computer and use it in GitHub Desktop.
Save Vzor-/fe9ab75588f3c216360068e94c6a7672 to your computer and use it in GitHub Desktop.
import javax.print.PrintServiceLookup;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.*;
public class PrintTest {
private static double docWidth = 2.25 * 72;
private static double docHeight = 1.25 * 72;
public static void main(String[] args) throws PrinterException {
//On JDK 11 this property 'fixes' the issue by forcing the use of PSPrinterJob
//System.setProperty("java.awt.printerjob", "sun.print.PSPrinterJob");
new PrintTest().print();
}
public void print() throws PrinterException {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(PrintServiceLookup.lookupDefaultPrintService());
PageFormat page = job.getPageFormat(null);
Paper paper = page.getPaper();
paper.setSize(docWidth, docHeight);
paper.setImageableArea(0, 0, docWidth, docHeight);
page.setPaper(paper);
job.setJobName("test");
Book book = new Book();
book.append(new ImagePrintable(page, makeImg()), page);
job.setPageable(book);
job.print(null);
}
private BufferedImage makeImg() {
BufferedImage i = new BufferedImage((int)docWidth, (int)docHeight, BufferedImage.TYPE_INT_RGB );
for(int x = 0; x < (int)docWidth; x++){
for(int y = 0; y < (int)docHeight; y++){
i.setRGB(x, y, (x*x/8 + y*y/8));
}
}
return i;
}
private class ImagePrintable implements Printable {
private double x, y, width;
private BufferedImage image;
public ImagePrintable(PageFormat page, BufferedImage image) {
this.x = page.getImageableX();
this.y = page.getImageableY();
this.width = page.getImageableWidth();
this.image = image;
}
@Override
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex == 0) {
int w = (int)Math.min(width, image.getWidth());
int h = w * image.getHeight() / image.getWidth();
g.drawImage(image, (int) x, (int) y, w, h, null);
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment