Taking a screenshot of a scene or a portion of a scene in JavaFx 2.2

守給你的承諾、 提交于 2019-11-27 08:14:08

问题


I've managed to make a WritableImage using

WritableImage snapshot = obj.getScene().snapshot(null);

Now I would like to output this screenshot on a pdf file. I've already managed to output text to a pdf using Apache pdfbox library using the following code:

PDDocument doc = null; PDPage page = null;

   try{
       doc = new PDDocument();
       page = new PDPage();

       doc.addPage(page);
       PDFont font = PDType1Font.HELVETICA_BOLD;

       PDPageContentStream content = new PDPageContentStream(doc, page);
       content.beginText();
       content.setFont( font, 12 );
       content.moveTextPositionByAmount( 100, 700 );
       content.drawString("Hello World");

       content.endText();
       content.close();
      doc.save("PDFWithText.pdf");
      doc.close();
    } catch (Exception e){
    System.out.println(e);
    }

How can I do this when using WritableImage rather that using basic String texts?

Also, how can I take a screenshot of certain nodes within a scene?

Thanks


回答1:


Taking a screenshot of a scene

You already have working code for this in your question.

WritableImage snapshot = stage.getScene().snapshot(null);

Taking a screenshot of a . . . portion of a scene in JavaFx 2.2

Taking a snapshot of Node is similar to taking snapshot of a Scene, you just use the snapshot methods on the Node rather than the scene. First place your Node in a Scene, and then snapshot the Node.

WritableImage snapshot = node.snapshot(null, null);

The first parameter which may be passed to the node.snapshot call is some configuration for SnapshotParameters (which you probably don't need, but you can investigate them to see if they are required or useful for your case).


Now I would like to output this screenshot on a pdf file. How can I do this when using WritableImage rather that using basic String texts?

I have not used the pdfbox toolkit you reference in your question. Likely the toolkit works with awt based images rather than JavaFX images, so you will need to convert your JavaFX snapshot image to an awt buffered image using SwingFXUtils.fromFXImage.

To actually get the awt encoded image into a pdf file, consult the documentation for your pdfbox toolkit. Kasas's answer to Add BufferedImage to PDFBox document would seem to provide a code snippet for this operation. Looks like the relevant code (and I haven't tried this) is:

PDPageContentStream content = new PDPageContentStream(doc, page);
PDXObjectImage ximage = new PDJpeg(doc, bufferedImage);
content.drawImage(ximage, x, y);


来源:https://stackoverflow.com/questions/18024498/taking-a-screenshot-of-a-scene-or-a-portion-of-a-scene-in-javafx-2-2

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