Buffer switching between Processing and pdf (export)

Just thought this was kind of handy.

I needed to export my processing window to pdf, but didn’t really want to make a new drawing function specifically for it (at least I wanted to try without first). I stumbled upon Processing forum user “davbol”'s 2008 buffer switching technique, and hacked this together (very similar).

Demo:

/* Export processing window to PDF

  Switching back and forth between drawing to processing and pdf.

  Using processing forum user "davbol"'s 2008 buffer switching technique:
    https://forum.processing.org/beta/num_1214781848.html

   2019.06.16 
*/

import processing.pdf.*;

PGraphics originalG;
PGraphics pdf;

// window size
int wWidth  = 400;
int wHeight = 400;


void settings() {
  size(wWidth, wHeight);
}


void setup() {
  originalG = g;
  pdf = createGraphics(wWidth, wHeight, PDF, "test.pdf");

  // Main screen red background, green line
  // useOriginalG(); // not really needed first time here
  background(255, 0, 0);
  stroke(0, 255, 0);
  strokeWeight(3);
  line(10, 10, wWidth-10, wHeight-10);

  // PDF page 1
  // blue background, yellow line
  usePDF();
  background(0, 0, 255);
  stroke(255, 255, 0);
  strokeWeight(3);
  line(10, 10, wWidth-10, wHeight-10);

  textSize(30);
  text("Testing PDF export", 50, 50);
  

  // Back to processing window
  useOriginalG();
  text("PDF page 1 done", 200, 200);


  // Make PDF page 2
  usePDF();
  PDFnextPage();

  // PDF dark green background, green line
  background(0, 50, 0);
  stroke(0, 255, 0);
  strokeWeight(3);
  line(10, wHeight-10, wWidth-10, 10);
  
  textSize(16);
  text("PDF page 2", 20, 20);
  
  // End PDF file export
  pdf.dispose();
  // g.dispose();  // also works here
  
  
  // Back to processing window again
  useOriginalG();
  text("PDF page 2 done", 250, 250);
 }


void usePDF() {
  g.endDraw();
  g = pdf;
  g.beginDraw();
}


void PDFnextPage() {
  PGraphicsPDF pdfg = (PGraphicsPDF) pdf;  // Get the pdf renderer
  pdfg.nextPage();  // Tell it to go to the next page
}


void useOriginalG() {
  g.endDraw();
  g = originalG;
  g.beginDraw();
}


void draw() {}
3 Likes