Save JavaFX ScrollPane content to PDF file

2019-09-11 05:43发布

问题:

I'm using the below code to save the content of a ScrollPane in my JavaFx Application to a PDF file.

button.setOnMouseClicked(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {

File pdfFile = fileChooser.showSaveDialog(primaryStage);

try {
    BufferedImage bufImage = SwingFXUtils.fromFXImage(scrollPane.snapshot(new SnapshotParameters(), null), null);
    FileOutputStream out = new FileOutputStream(new File("../temp.jpg"));
    javax.imageio.ImageIO.write(bufImage, "jpg", out);
    out.flush();
    out.close();

    com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance("../temp.jpg");
    Document doc = new Document(new com.itextpdf.text.Rectangle(image.getScaledWidth(), image.getScaledHeight()));
    FileOutputStream fos = new FileOutputStream(pdfFile);
    PdfWriter.getInstance(doc, fos);
    doc.open();
    doc.newPage();
    image.setAbsolutePosition(0, 0);
    doc.add(image);
    fos.flush();
    doc.close();
    fos.close();


}
catch(Exception e)
{
     e.printStackTrace();
}

} });

In the scrollpane, I have a very long VBox which contains almost 40-50 labels. So, this code initially saves it to a jpg file and then adds it to a pdf file.

When the temp.jpg is created initially, due to its length, the jpg file looks very thin. It should be zoomed to see the actual content.

When the pdf file is written, it was blank except that it was lengthy as it would have been when the jpg is really converted to a PDF file.

Can anyone help me fix this ? to take the snapshot of the ScrollPane to PDF with its actual size/scale ?

回答1:

I have first scaled the image and then created document with scaled PageSize. This fixed the issue

com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance("../temp.jpg");
image.scalePercent(1);
Document doc = new Document(new com.itextpdf.text.Rectangle(image.getScaledWidth(), image.getScaledHeight()));
doc.open();
doc.add(image);