Husayn Hakeem Husayn Hakeem - 7 months ago 1126
Android Question

Creating a pdf file in android programmatically and writing in it

I'm trying to create a pdf file inside my app, save it on the external storage the open it. Saving a file isn't an issue for me, nor is opening one, my issue is with creating one and writing in it. So after some research online I found the following way of doing it:

File file = new File(directoryName, fileName);

// Creating output stream to write in the newly created file
FileOutputStream fOut = null;

try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {

// Creating a new document
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

try {
PdfWriter.getInstance(document, fOut);

// Open the document for writing;

// Write in the document
document.add(new Paragraph("Hello world"));

} catch(DocumentException de) {

Upon running my app and executing the code above, I get the following error:

java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color;

Would someone know what's the issue with my code, or of another way that is sure to work for creating and writing a pdf file ?

Thanks !


So apparently the code I was using wasn't compatible with android, hence the error I was getting. Below you'll find the correct code that actually works right (for creating a pdf file, putting some content in it, saving in and the opening the newly created file):

PS: For this you'll need to add the jar of iTextG to your project:

// Method for creating a pdf file from text, saving it then opening it for display
    public void createandDisplayPdf(String text) {

        Document doc = new Document();

        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir";

            File dir = new File(path);

            File file = new File(dir, "newFile.pdf");
            FileOutputStream fOut = new FileOutputStream(file);

            PdfWriter.getInstance(doc, fOut);

            //open the document

            Paragraph p1 = new Paragraph(text);
            Font paraFont= new Font(Font.COURIER);

            //add paragraph to document

        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        finally {

        viewPdf("newFile.pdf", "Dir");

    // Method for opening a pdf file
    private void viewPdf(String file, String directory) {

        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
        Uri path = Uri.fromFile(pdfFile);

        // Setting the intent for pdf reader
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");

        try {
        } catch (ActivityNotFoundException e) {
            Toast.makeText(TableActivity.this, "Can't read pdf file", Toast.LENGTH_SHORT).show();