Create a gist now

Instantly share code, notes, and snippets.

import java.awt.Color;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.jfree.fx.FXGraphics2D;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class PDFGraphicsContextViewer extends Application {
public static void main(String[] args) {
launch(args);
}
int pdfScale = 1;
@Override
public void start(Stage primaryStage) throws Exception {
int width = 590;
int height = 840;
PDDocument doc = PDDocument.load(PDFGraphicsContextViewer.class.getResourceAsStream("sample.pdf"));
Pane pane = new Pane();
Canvas canvas = new Canvas();
canvas.setWidth(width);
canvas.setHeight(height);
renderPdf(canvas, doc);
pane.getChildren().add(canvas);
Scene scene = new Scene(pane, width, height);
primaryStage.setTitle(getClass().getName());
primaryStage.setScene(scene);
primaryStage.show();
}
protected void renderPdf(Canvas canvas, PDDocument doc) throws IOException {
PDFRenderer renderer = new PDFRenderer(doc);
//canvasからGraphicsContxtを取得して、FXGraphics2Dをインスタンス化
FXGraphics2D g2 = new FXGraphics2D(canvas.getGraphicsContext2D());
g2.clearRect(0, 0, (int) canvas.getWidth(), (int) canvas.getHeight());
//PDFのレンダリング。rendererの描画処理は直接canvasに対して行われます
renderer.renderPageToGraphics(0, g2, pdfScale);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment