Last active
April 21, 2024 05:05
-
-
Save Vzor-/b221e53911b2607919f68ac9d5e850ab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javafx.application.Platform; | |
import javafx.embed.swing.SwingFXUtils; | |
import javafx.print.JobSettings; | |
import javafx.print.PrintColor; | |
import javafx.scene.Node; | |
import javafx.scene.image.ImageView; | |
import java.awt.*; | |
import java.awt.image.BufferedImage; | |
import java.awt.print.*; | |
public class ColorTest implements Printable { | |
BufferedImage bufferedImage; | |
public static void main(String[] args) throws PrinterException { | |
ColorTest colorTest = new ColorTest(); | |
colorTest.genImg(); | |
// // awt prints in color even if the printer is configured for black and white | |
// PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet(); | |
// attributes.add(Chromaticity.COLOR); | |
// PrinterJob job = PrinterJob.getPrinterJob(); | |
// job.setJobName("Demo"); | |
// job.setPrintable(demo); | |
// // job.printDialog(); | |
// job.print(attributes); | |
// jfx does not print in color when the printer is configured for black and white | |
Platform.startup(()-> { | |
Node node = new ImageView(SwingFXUtils.toFXImage(colorTest.bufferedImage, null)); | |
javafx.print.PrinterJob jfxJob = javafx.print.PrinterJob.createPrinterJob(); | |
JobSettings settings = jfxJob.getJobSettings(); | |
settings.setJobName("Demo(jfx)"); | |
settings.setPrintColor(PrintColor.COLOR); | |
//jfxJob.showPrintDialog(null); | |
jfxJob.printPage(node); | |
jfxJob.endJob(); | |
Platform.runLater(Platform::exit); | |
}); | |
} | |
public void genImg() { | |
// Generate a Munching Square test image | |
bufferedImage = new BufferedImage(256, 64, BufferedImage.TYPE_INT_RGB); | |
for (int y = 0; y < 64; y++) { | |
for (int x = 0; x < 256; x++) { | |
int[] color = new int[]{(x|y)%256, (x|y)*2%256, (x|y)*4%256}; | |
bufferedImage.getRaster().setPixel(x, y, color); | |
} | |
} | |
} | |
@Override | |
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { | |
if (pageIndex != 0) return 1; | |
Rectangle r = graphics.getClipBounds(); | |
graphics.drawImage(bufferedImage, r.x, r.y, null); | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment