Why do I get a "Could not find PdfGraphics2D" error?

Tags: Graphics2DAndroidiText 5

I have come across a runtime exception "Could not find class com.itextpdf.awt.PdfGraphics2D". I wanted to create a PDF document from an android device. For that I used iText library. This my code for creating PDF:

Document document = new Document();
PdfWriter.getInstance(document, outStream);
document.open();
document.add(new Paragraph(data)); 
document.close();
The code works fine. It is creating PDF successfully. but it gives me a runtime exception:

06-14 10:09:20.491: W/dalvikvm(764):
     Unable to resolve superclass of Lcom/itextpdf/awt/PdfGraphics2D; (1251)
06-14 10:09:20.491: W/dalvikvm(764):
     Link of class 'Lcom/itextpdf/awt/PdfGraphics2D;' failed
06-14 10:09:20.491: E/dalvikvm(764):
     Could not find class 'com.itextpdf.awt.PdfGraphics2D',
     referenced from method com.itextpdf.text.pdf.PdfContentByte.createGraphics
06-14 10:09:20.491: W/dalvikvm(764):
     VFY: unable to resolve new-instance 480
     (Lcom/itextpdf/awt/PdfGraphics2D;) in Lcom/itextpdf/text/pdf/PdfContentByte;
06-14 10:09:25.280: E/dalvikvm(764):
     Could not find class 'org.bouncycastle.cert.X509CertificateHolder',
     referenced from method com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj
06-14 10:09:25.280:
     W/dalvikvm(764): VFY: unable to resolve new-instance 1612
    (Lorg/bouncycastle/cert/X509CertificateHolder;) in Lcom/itextpdf/text/pdf/PdfReader;
I have done clean and build, added jar to libs folder and make it selected on order and export and i done lot of research for past 2 days. but nothing helped me. Based upon my knowledge there should be these possibilities: (1) the external jar isn't loaded properly, or (2) the class PdfGraphics2D extends java.awt.Graphics2D which is not available on Android.

Posted on StackOverflow on Jun 14, 2013 by R9J

You've discovered that PdfGraphics2D extends java.awt.Graphics2D, and as you already know Graphics2D is a forbidden class on Android.

You've also encountered problems related to BouncyCastle.

This tells me that you're using the Java version of iText instead of the Android port. In the Android port, we replaced BouncyCastle by SpongyCastle (as recommended when using encryption on Android) and we removed all references to forbidden classes (for instance in the awt and nio packages).

Please switch to using the Android port of iText. It is called iTextG.