Rucrazia's Blog

Model - JAVAFX에서 Print(인쇄) 하는 방법 본문

기술 - Coding/Java

Model - JAVAFX에서 Print(인쇄) 하는 방법

DoyoungJ 2017. 9. 20. 14:49

JAVAFX를 이용해서 printer를 제어하는 것은 어려우면서도 쉽습니다.

한 장의 이미지만 인쇄하는 것은 많은 예제가 나와있는데, 여러개를 인쇄하는 방법은 찾기 어려웠습니다.

 

밑에 부분 코드가 Print를 하게되는 직접적인 코드입니다.

job.printPage(pageLayout, node.get(i))를 통해 print 할 콘텐츠를 넣게 됩니다.

테스트용 코드로 했기 때문에, 간단하게 2장을 한번에 인쇄하기 위하여 for문을 이용해서 print 작업을 넣었습니다.

 

if (proceed)
    {
        for(int i =0; i<2; i++) {
            success = job.printPage(pageLayout, node.get(i));
        }
    }
    if (success)
    {
        job.endJob();
    }

 

 

전체 코드

Global 변수


private int imageHSize = 1920;
private int imageVSize = 1410;
private int imageHSizeStatic = 2000;
private int imageVSizeStatic = 1000;

Main 함수


String filenameWord = String.format("png-%d.%s", 1, "png");
String workingDirectory = System.getProperty("user.dir");
String imgPath = workingDirectory + File.separator + filenameWord;

File file = new File(imgPath);
Image image = new Image(file.toURI().toString(), imageHSizeStatic, imageVSizeStatic, false, true);
ImageView imv = new ImageView();
ImageView imvs = new ImageView();

imv.setImage(image);
Printer printer = Printer.getDefaultPrinter();
PageLayout pageLayout
= printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);

imv.setFitWidth(pageLayout.getPrintableWidth());
imv.setFitWidth(pageLayout.getPrintableHeight());


String filenameWord2 = String.format("png-%d.%s", 2, "png");
String imgPath2 = workingDirectory + File.separator + filenameWord2;
System.out.println(filenameWord2);
File file2 = new File(imgPath2);
Image image2 = new Image(file2.toURI().toString(), imageHSizeStatic, imageVSizeStatic, false, true);
ImageView imv2 = new ImageView();
imv2.setImage(image2);
imv2.setFitWidth(pageLayout.getPrintableWidth());
imv2.setFitWidth(pageLayout.getPrintableHeight());

 

PrinterJob job = PrinterJob.createPrinterJob();



List<ImageView> imvList = new ArrayList<>();
imvList.add(imv);
imvList.add(imv2);

printSetup(imvList, primaryStage);


private void printSetup(List<ImageView> node, Stage owner)
{
// Create the PrinterJob
PrinterJob job = PrinterJob.createPrinterJob();

if (job == null)
{
return;
}
// Show the print setup dialog
boolean proceed = job.showPrintDialog(owner);



Printer printer = job.getPrinter();
PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
double scaleX = pageLayout.getPrintableWidth() / node.get(0).getBoundsInParent().getWidth();
double scaleY = pageLayout.getPrintableHeight() / node.get(0).getBoundsInParent().getHeight();
node.get(0).getTransforms().add(new Scale(scaleX, scaleY));
node.get(1).getTransforms().add(new Scale(scaleX, scaleY));


boolean success = false;

if (proceed)
{
for(int i =0; i<2; i++) {
success = job.printPage(pageLayout, node.get(i));
}
}
if (success)
{
job.endJob();
}


}