# Drawing a PGraphics while saving a PDF crashes

**URL:** <https://discourse.processing.org/t/drawing-a-pgraphics-while-saving-a-pdf-crashes/42522>\
**Category:** Processing\
**Created:** [July 31, 2023, 5:00am UTC](https://discourse.processing.org/t/drawing-a-pgraphics-while-saving-a-pdf-crashes/42522 "2023-07-31T05:00:43Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![villares](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/villares/32/3166_2.png) [@villares](https://discourse.processing.org/u/villares)\
**Post date:** [July 31, 2023, 5:00am UTC](https://discourse.processing.org/t/drawing-a-pgraphics-while-saving-a-pdf-crashes/42522/1 "2023-07-31T05:00:43Z")

</div>

This might be more of a curiosity than a “bug” I want to solve. My main motivation was to draw shapes and have them clipped by the PGraphics canvas before applying them elsewhere.

When drawing the Pgraphics with `image()` it normaly works fine, but when recording a PDF frame I get this:

```auto
ClassCastException: class sun.java2d.SunGraphics2D cannot be cast to class java.awt.Image (sun.java2d.SunGraphics2D and java.awt.Image are in module java.desktop of loader 'bootstrap')

```

… when running the code below…

```pde
import processing.pdf.*;

boolean savePDF = false;
PFont f;
PGraphics pg;

void setup() {
  size(400, 400);
  textMode(SHAPE);
  f = createFont("DejaVu Sans", 100);
  pg = createGraphics(300, 300);
  pg.beginDraw();
  pg.background(0, 100, 0);
  pg.textAlign(CENTER, CENTER);
  pg.textFont(f);
  pg.textSize(pg.width / 8);
  pg.textMode(SHAPE);
  pg.text("hello", pg.width * 0.6, pg.height * 0.6);
  pg.endDraw();
}

void draw() {
  if (savePDF) {
    PGraphics pdf = createGraphics(width, height, PDF, "out.pdf");
    beginRecord(pdf);
  }
  imageMode(CENTER);
  int x = 200;
  int y = 200;
  float rot = PI / 4;
  pushMatrix();
  translate(x, y);
  rotate(rot);
  image(pg, 0, 0);
  popMatrix();
  if (savePDF) {
    endRecord();
    savePDF = false;
  }

}
void keyPressed() {
  savePDF = true;
}

```

It works if I use `pg.copy()` that gets me a PImage object, but maybe I don’t want to do that because I don’t want a raster of the vector-graphics…
