diff --git a/pdfbox/src/main/java/org/apache/pdfbox/printing/PDFPrintable.java b/pdfbox/src/main/java/org/apache/pdfbox/printing/PDFPrintable.java index 8926024ac7a..96f10823c54 100644 --- a/pdfbox/src/main/java/org/apache/pdfbox/printing/PDFPrintable.java +++ b/pdfbox/src/main/java/org/apache/pdfbox/printing/PDFPrintable.java @@ -206,14 +206,14 @@ public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) return NO_SUCH_PAGE; } - Graphics2D printerGraphics = null; - Graphics2D graphics2D = null; + // work on a private copy so the caller's Graphics2D state (transform, clip, color, + // background, stroke) is never mutated. Disposing the copy in the finally block + // releases its resources without affecting the original. + Graphics2D printerGraphics = (Graphics2D) graphics.create(); + Graphics2D graphics2D = printerGraphics; try { - printerGraphics = (Graphics2D) graphics; - graphics2D = printerGraphics; - // capture the DPI that will be used for rasterizing the image // if rasterizing is specified float rasterDpi = dpi; @@ -324,10 +324,11 @@ public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) } finally { - if (graphics2D != null && graphics2D != printerGraphics) + if (graphics2D != printerGraphics) { graphics2D.dispose(); } + printerGraphics.dispose(); } }