The solution from Ollie Glass ceased to work because the constructor of PApplet/Applet
checks whether the environment is headless or not, i.e. -Djava.awt.headless=true
.
So there is no way of creating a PApplet object in the first place.
Instead, create your PGraphics
directly. For instance, to draw everything into a pdf
PGraphics pdf = new PGraphicsPDF();
pdf.setPrimary(false);
pdf.setPath(filename);
pdf.setSize(sizeX, sizeY);
// pdf.setParent(new PApplet()); This is intentionally NOT called.
pdf.beginDraw();
// draw everything
pdf.dispose();
pdf.endDraw();
Adding text will still throw an exception since the underlying PGraphics
calls its parent
(the PApplet
) for some helper methods. However, this hasn't been set because we are not allowed to create a PApplet
in the first place.
A solution is to get rid of these function calls is creating you own version of PGraphicsPDF
. For example
class MyPGraphicsPDF extends PGraphicsPDF{
@Override
public float textAscent() {
if (textFont == null) {
defaultFontOrDeath("textAscent");
}
Font font = (Font) textFont.getNative();
//if (font != null && (textFont.isStream() || hints[ENABLE_NATIVE_FONTS])) {
if (font != null) {
FontMetrics metrics = this.getFontMetrics(font);
return metrics.getAscent();
}
return super.textAscent();
}
@Override
public float textDescent() {
if (textFont == null) {
defaultFontOrDeath("textDescent");
}
Font font = (Font) textFont.getNative();
//if (font != null && (textFont.isStream() || hints[ENABLE_NATIVE_FONTS])) {
if (font != null) {
FontMetrics metrics = this.getFontMetrics(font);
return metrics.getDescent();
}
return super.textDescent();
}
public FontMetrics getFontMetrics(Font font) {
FontManager fm = FontManagerFactory.getInstance();
return sun.font.FontDesignMetrics.getMetrics(font);
}
}
textAscent()
and textDescent()
are copies of the code from PGraphics
with the change of not calling getFontMetrics(Font font)
from the non-existing parent
PApplet
. Instead both redirect to the third method that reimplements the missing helper method of PApplet
as a slightly shorter version of java.awt.Component.getFontMetrics(Font font)
.
Hope that helps.
Would be nice to have a native headless version of processing when explicitely calling for a file as drawing board.