OpenPDF icon indicating copy to clipboard operation
OpenPDF copied to clipboard

PdfPrinterGraphics2D does not override create

Open mperktold opened this issue 1 year ago • 1 comments

Describe the bug The PdfPrinterGraphics2D class inherits the create method from PdfGraphics2D, which in turn overrides. The method is declared as abstract in Graphics and is convenient to create equivalent copies that can be modified without modifying the original object, just like the classic clone method.

Because PdfPrinterGraphics2D does not override create, it returns a PdfGraphics2D instead of a PdfPrinterGraphics2D, which is unexpected.

To Reproduce

try (var document = new Document()) {
    var writer = PdfWriter.getInstance(document, new ByteArrayOutputStream());
    document.open();
    var graphics1 = writer.getDirectContent().createPrinterGraphics(10, 10, PrinterJob.getPrinterJob());
    var graphics2 = graphics1.create();
    System.out.println(graphics1.getClass());
    System.out.println(graphics2.getClass());
}

Expected behavior The above code should print:

class com.lowagie.text.pdf.PdfPrinterGraphics2D
class com.lowagie.text.pdf.PdfPrinterGraphics2D

But it prints:

class com.lowagie.text.pdf.PdfPrinterGraphics2D
class com.lowagie.text.pdf.PdfGraphics2D

It also throws an exception, but that is a problem with the example code and therefore expected and not the point of this issue.

System (please complete the following information):

  • OS: Windows 11
  • Used Font: not relevant

Additional context You might want to consider to make it easier to override PdfGraphics2D.create. At the moment, it creates a new empty PdfGraphics2D and then copies all own fields to the copy. When overriding the method, you would need to create an empty PdfPrinterGraphics2D object instead. Then, you would still need to copy the fields of the base class to the new copy in addition to any field of the derived class, but you cannot use super.create() for that. It would be much easier if create were implemented by two separate hooks (possibly protected): one for creating an empty copy, and another for copying all fields to a copy that is given as a parameter. Alternatively, PdfGraphics2D could also implement the Cloneable interface, move the implementation of create() to clone() and implement create() on top of that.

mperktold avatar Feb 23 '24 15:02 mperktold

Pull requests are welcome.

asturio avatar Feb 23 '24 15:02 asturio