Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import java.awt.Color;
import java.awt.geom.AffineTransform;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.jfree.fx.FXGraphics2D;
import javafx.application.Application;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class DraggablePDFGraphicsContextViewer extends Application {
public static void main(String[] args) {
launch(args);
}
int pdfScale = 100;
@Override
public void start(Stage primaryStage) throws Exception {
int width = 590;
int height = 840;
PDDocument doc = PDDocument.load(DraggablePDFGraphicsContextViewer.class.getResourceAsStream("sample.pdf"));
Pane pane = new Pane();
PdfCanvas canvas = new PdfCanvas(doc, 0, pdfScale);
canvas.setWidth(width);
canvas.setHeight(height);
pane.getChildren().add(canvas);
canvas.renderPdf();
Scene scene = new Scene(pane, width, height);
primaryStage.setTitle(getClass().getName());
primaryStage.setScene(scene);
primaryStage.show();
}
public static class PdfCanvas extends Canvas {
PDFRenderer renderer;
Canvas canvas;
double dragStartMouseX;
double dragStartMouseY;
double pdfX;//PDF描画の起点(X座標)
double pdfY;//PDF描画の起点(Y座標)
int page;
int pdfScale;
public PdfCanvas(PDDocument doc, int page, int scale) {
renderer = new PDFRenderer(doc);
this.pdfScale = scale;
this.page = page;
//press時にマウス座標を取得
setOnMousePressed(e -> {
dragStartMouseX = e.getSceneX();
dragStartMouseY = e.getSceneY();
getScene().setCursor(Cursor.CLOSED_HAND);
});
//マウスリリース時に、移動した分だけPDFレンダリングの起点をずらす
setOnMouseReleased(e -> {
double offsetX = e.getSceneX() - dragStartMouseX;
double offsetY = e.getSceneY() - dragStartMouseY;
pdfX = pdfX + offsetX;
pdfY = pdfY + offsetY;
getScene().setCursor(Cursor.DEFAULT);
renderPdf();
});
}
public void renderPdf() {
FXGraphics2D g2 = new FXGraphics2D(getGraphicsContext2D());
g2.clearRect(0, 0, (int) getWidth(), (int) getHeight());
//AffineTransformを使って、graphicsへの書き込みの起点をずらす
AffineTransform savedAffineTrasform = g2.getTransform();
g2.setTransform(AffineTransform.getTranslateInstance(pdfX, pdfY));
try {
renderer.renderPageToGraphics(page, g2, pdfScale);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
g2.setTransform(savedAffineTrasform);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment