Save JavaFX ScrollPane content to PDF file

这一生的挚爱 提交于 2019-12-25 04:53:24

问题


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);


来源:https://stackoverflow.com/questions/29941817/save-javafx-scrollpane-content-to-pdf-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!