12

I hava a javafx application where the user enters some details in test fields and it is shown on a listview. I now have a button to print using the printjob but everytime I hit the print button the printer prints garbage data like jhsjs6sh3#uhbsbkahi instead of the real values from the ListView. below is my codes for the print functon

public void print (final Node node) {
        Printer printer = Printer.getDefaultPrinter();
        PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
        final double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth();
        final double scaleY = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight();
        node.getTransforms().add(new Scale(scaleX, scaleY));

        PrinterJob job =PrinterJob.createPrinterJob();
        if (job != null ){

            boolean success = job.printPage(node);
            System.out.println("printed");
            if (success){
                System.out.println(success);
                job.endJob();
            }
        }

    }

@FXML 
 private void printOps(ActionEvent event){
 
 print(billingDataList);

}

I use a MacBook for my development and HP printer.

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
King
  • 1,885
  • 3
  • 27
  • 84
  • 3
    Why the `android` tag? I did not have a problem printing a `ListView` with the given code. I am guessing maybe it's a Mac problem, or you haven't posted the part of the code that is causing the problem. – SedJ601 Dec 07 '17 at 15:32
  • So that paper is not wasted trying to figure out a print problem, I always use `job.showPrintDialog(node.getScene().getWindow())`. This allows me to print to PDF instead of paper. So I would replace `if (job != null )` with `if(job != null && job.showPrintDialog(node.getScene().getWindow()))` until I know my print job is correct. – SedJ601 Dec 07 '17 at 15:36
  • I have posted the full code. And even if I save it as PDF it still shows garbage text – King Dec 07 '17 at 15:38
  • I think you missed the point on the reason to print to PDF while you are trying to troubleshoot a printing job. – SedJ601 Dec 07 '17 at 15:40
  • Try printing a different `Node` to see if anything happens. – SedJ601 Dec 07 '17 at 15:44
  • Every time I print a Node I get nothing in the console . – King Dec 07 '17 at 15:52
  • Given the fact that I just used the method you posted with zero problems and you can't print any `Node` with the same method, means that your problem lies elsewhere. – SedJ601 Dec 07 '17 at 15:53
  • Did you try my code with a printer and did it print please? – King Dec 07 '17 at 15:54
  • Your problem is probably due to a Driver or the Mac OS. Just guessing. – SedJ601 Dec 07 '17 at 15:54
  • Try taking a `SnapShot` of your node and then using `awt` to print it. https://stackoverflow.com/questions/31100226/how-to-print-on-printer-image-using-javafx8 – SedJ601 Dec 07 '17 at 15:57
  • do you override the `toString()` in the model on `ListView`? – mr mcwolf Dec 07 '17 at 16:20
  • I did not have any `toString()` in my model – King Dec 07 '17 at 16:34
  • @SedrickJefferson Can you help me modify the code above with your response because I tried it before and didn't work – King Dec 07 '17 at 16:35
  • what you describe is a call to `toString()` of a base class (`Object#toString()`). Try overwriting it and see if there will be a change (it should return the text you want to print). – mr mcwolf Dec 07 '17 at 16:38

1 Answers1

1

You will have to figure out the scaling. This prints using SnapShot and awt. Using code from here.

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;

/**
 *
 * @author blj0011
 */
public class JavaFXApplication61 extends Application
{

    @Override
    public void start(Stage primaryStage)
    {
        ListView<String> list = new ListView<>();
        ObservableList<String> items = FXCollections.observableArrayList("A", "B", "C", "D");
        list.setItems(items);

        VBox root = new VBox();

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction((event) ->
        {
            WritableImage image = list.snapshot(new SnapshotParameters(), null);
            File file = new File("nodeImage.png");

            try
            {
                ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);

                Image imageToPrint = new Image(file.toURI().toString());
                BufferedImage bufferedImage = SwingFXUtils.fromFXImage(imageToPrint, null);
                printImage(bufferedImage);
            }
            catch (IOException ex)
            {
                System.out.println(ex.toString());
            }
        });

        root.getChildren().add(btn);
        root.getChildren().add(list);
        Scene scene = new Scene(root, 1080, 720);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

    private void printImage(BufferedImage image)
    {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable((Graphics graphics, PageFormat pageFormat, int pageIndex) ->
        {
            // Get the upper left corner that it printable
            int x = (int) Math.ceil(pageFormat.getImageableX());
            int y = (int) Math.ceil(pageFormat.getImageableY());
            if (pageIndex != 0)
            {
                return NO_SUCH_PAGE;
            }
            graphics.drawImage(image, x, y, image.getWidth(), image.getHeight(), null);
            return PAGE_EXISTS;
        });
        try
        {
            printJob.print();
        }
        catch (PrinterException e1)
        {
            e1.printStackTrace();
        }
    }
}

enter image description here

SedJ601
  • 12,173
  • 3
  • 41
  • 59