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);
            if(!dir.exists())
                dir.mkdirs();

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

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

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

            //add paragraph to document
            doc.add(p1);    

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

        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");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try {
            startActivity(pdfIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(TableActivity.this, "No application has been found to open PDF files.", Toast.LENGTH_SHORT).show();
        }
    }
Answer from Husayn Hakeem on Stack Overflow
Top answer
1 of 4
23

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);
            if(!dir.exists())
                dir.mkdirs();

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

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

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

            //add paragraph to document
            doc.add(p1);    

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

        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");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try {
            startActivity(pdfIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(TableActivity.this, "No application has been found to open PDF files.", Toast.LENGTH_SHORT).show();
        }
    }
2 of 4
17

PdfDocument class enables generating a PDF document from native Android content. By using this class we can create pdf and also open it by using PdfRenderer. Sample code for creating a pdf file

 public void stringtopdf(String data)  {
    String extstoragedir = Environment.getExternalStorageDirectory().toString();
    File fol = new File(extstoragedir, "pdf");
    File folder=new File(fol,"pdf");
    if(!folder.exists()) {
        boolean bool = folder.mkdir();
    }
    try {
        final File file = new File(folder, "sample.pdf");
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file);


        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new 
        PdfDocument.PageInfo.Builder(100, 100, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);
        Canvas canvas = page.getCanvas();
        Paint paint = new Paint();

        canvas.drawText(data, 10, 10, paint);



        document.finishPage(page);
        document.writeTo(fOut);
        document.close();

    }catch (IOException e){
        Log.i("error",e.getLocalizedMessage());
    }
🌐
Nutrient
nutrient.io › android › pdf generation › programmatically
Android generate PDF programmatically | Nutrient SDK
July 2, 2025 - Optionally, you can also use Android’s built-in APIs provided by PdfDocument(opens in a new tab) to generate a PDF. For maximum flexibility, you can write your own drawing code to generate PDFs. The provided APIs are fairly straightforward, so if you already have existing drawing code, this can be a good approach for PDF creation.
Discussions

itext - How to create a pdf programmatically from Android - Stack Overflow
I'm building an app with Android Studio. In my activity, I want to create a PDF file, so I have copy from internet this code to create and open a simple PDF file. public void createandDisplayPdf(S... More on stackoverflow.com
🌐 stackoverflow.com
I realized the best way to create a PDF file in Android is not to use Android to do it
Had the basically same issue. Needed to create complex PDFs (images, tables, logos, grids etc) offline in Kotlin Multiplatform. Best way to go is definitly Via Html and than convert it via Webview. Most of it can even be done in commom main. If you dont have licensing problems e.g. can open source your code use itext7 html2pdf. Or their direct pdf generator. My experience with apache pdf box was not great i also tried that and several others i cant recall. Was a lot of of tedious work because debugging and testing is hell but at the end, to my.suprise, it worked great and could output 100 page pdfs with no issues If you dont need on device or offline definitly do this on a server lol More on reddit.com
🌐 r/androiddev
33
33
August 16, 2025
Any good free PDF app for making PDF files with pages of text with photos?
Samsung notes is my go-to. You can import pdf, images and add your own text. MS Word files can be saved as pdf's and them imported to Samsung notes. When you're done, just save the note as a pdf. I use this a lot to combine several pdf's in one document, and you can also move pages around. More on reddit.com
🌐 r/GalaxyTab
5
7
March 27, 2022
Best app to build a pdf document from photos?
Microsoft Office Lens More on reddit.com
🌐 r/androidapps
20
0
January 26, 2025
🌐
Android Developers
developer.android.com › api reference › pdfdocument
PdfDocument | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Techholding
techholding.co › blog › step-by-step-guide-for-creating-dynamic-pdf
Android PDF Generation: A Step-by-Step Guide for Creating Dynamic PDF Documents | Tech Holding
Overall, rendering PDFs in Android using the PdfDocument class offers a powerful and flexible approach to generate PDF documents programmatically, opening up possibilities for creating customised and visually appealing content within Android ...
🌐
YouTube
youtube.com › aaviskar infotech
How to create PDF in android programmatically | share pdf file in android programmatically - YouTube
This video about how to create PDF in android programmatically and share pdf file in android programmatically.if developer wants to create pdf file in androi...
Published   September 19, 2023
Views   1K
Top answer
1 of 2
5

You are using iText for Java, while you should use iTextG for Android and GoogleAppEngine. See http://itextgroup.com/product/itextg

In iText for Java you have dependencies on classes in the Java packages java.awt, javax.nio and so on. These classes are forbidden on Android and that explains why you get that error.

In iTextG, we removed all those classes, keeping most of the functionality intact.

Update: looking at your dependencies, I see 'com.itextpdf:itextg:5.5.9' which means you are already using iTextG. Nevertheless, you are using java.awt.Color somewhere and that is forbidden.

When I look at your error message, I see

dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-lowagie-2.1.7

Lowagie, that's me, and you are using iText 2.1.7 (a library that should no longer be used) as well as iTextG (the library you need). You should check how you introduced that old iText version as it shouldn't be used on Android.

Solution:

  • Make sure that you don't import com.lowagie classes. Only import com.itextpdf classes. The general rule is: if you see my name in your code, you're doing something wrong.
  • Make sure you remove all references to iText 2.1.7. You shouldn't use two different versions of iText next to each other.
  • Make sure you don't introduce any of the forbidden classes (java.awt.*, javax.nio.*) in your code.
2 of 2
0

You are using a library that has been designed for pure Java. There are some minor but still notable differences between Java APIs and Android APIs, mostly related to gfx. As you can see the Java Color class doesn't have a strict equivalent on Android. That's what causes your bug here.

Either you find an Android-able PDF library or you use a remote service to convert your document and download it as PDF directly.

This thread might be of interest to you : PDF Library for Android - PDFBox?

🌐
YouTube
youtube.com › codelib
How to create PDF programmatically in android 11 || How to create PDF in android 11 - YouTube
In this video I am showing how to create PDF in android 11. Dependency :- implementation 'com.itextpdf:itextg:5.5.10' Source code url : - https://github.com...
Published   October 18, 2021
Views   808
Find elsewhere
🌐
Medium
medium.com › @meet30997 › creating-dynamic-pdf-documents-with-android-step-by-step-tutorial-for-dynamic-pdfs-5e15fdd92bb7
Creating Dynamic PDF Documents with Android: Step-by-Step Tutorial for Dynamic PDFs | by Meet | Medium
June 15, 2023 - We can later programmatically inflate the view while rendering the PDF just like we did with pdfHeaderView. ... The startPage method of the PdfDocument object (doc) is called with the pageInfo object as a parameter to initiate the creation of the first page of the PDF document.
🌐
YouTube
youtube.com › watch
Create PDF in Android Studio and Write to It - Step by Step Tutorial - YouTube
In this tutorial, we will generate PDF files directly from Android app in Android Studio. We will also write text to the PDF file that we will create. We wil...
Published   May 23, 2023
🌐
GitHub
github.com › tejpratap46 › PDFCreatorAndroid
GitHub - tejpratap46/PDFCreatorAndroid: Simple library to generate and view PDF in Android · GitHub
Simple library to generate and view PDF in Android · A simple library to create and view PDF with zero dependency Or native code.
Starred by 284 users
Forked by 66 users
Languages   Java 98.1% | HTML 1.9%
🌐
Blogger
deepshikhapuri.blogspot.com › 2017 › 06 › create-pdf-file-in-android.html
Create Pdf File In Android Programmatically - Deepshikha Puri: Mobile App Developer (Android & iOS))
Now we can use PdfDocument to generate the pdf file. But PdfDocument only works in 21 or above api level. In this tutorial I have created the pdf file with image and text. Download source code from here. ... android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry.
🌐
Nutrient
nutrient.io › android › pdf generation
Android PDF generator library — Fast and accurate | Nutrient
July 2, 2025 - Nutrient Android SDK is a library for generating PDF documents in an app without using a server. Newly created PDFs can be rendered in our viewer for signing, editing, filling forms, and more.
🌐
YouTube
youtube.com › watch
How to create PDF file in your Android App? Complete source code using Android Studio - YouTube
This video shows the steps to create a PDF file for various contents such as Texts and Strings in your Android App. This video shows the steps using the Andr...
Published   June 2, 2019
🌐
Loginet
loginet.com › dynamic-pdf-creator-android-developer
Create dynamic PDFs on Android - PDF creator guide
Learn how to use a PDF generator to create dynamic, user-friendly PDF documents programmatically on Android
🌐
Reddit
reddit.com › r/androiddev › i realized the best way to create a pdf file in android is not to use android to do it
r/androiddev on Reddit: I realized the best way to create a PDF file in Android is not to use Android to do it
August 16, 2025 -

I realized the best way to create a PDF file in Android is not to use Android to do it. It may be my lack of knowledge, but my experience with PDF files was mostly reading them and occasionally creating them using Microsoft Word, in fact, exporting a DOC file as a PDF. I never thought about creating a PDF file programmatically; I just presumed you could create paragraphs, or at very least, there's some sort of XML-ish layout for creating them; however, Android internal libraries' capabilities to create a PDF are, pardon my language, in the commode. However, there are some proprietary libraries. There was another way that I resisted initially, and we'll get to it.
The best tool the PdfDocument class can provide is the good ol' Canvas. Well, canvas is good, canvas in a way is liable for everything you see in Android, but I don't think it's reasonable that to create a simple PDF report, you should resort to calculations for text size/bounds and their positions. God forbid if you want to make a complex report with tables and images filled with text, just forget it.
In my infinite wisdom, I had the idea of creating the report in Android itself using either Views/Composables, then converting it to a Bitmap (which itself is a headache), then drawing that bitmap into the PDF, but it's a big but since you can't rely/trust that the device metrics and configs are always as your assumptions, you may force a device orientation but with recent changes in API 36 and even some tenacious tablets that are always in the landscape, it's a folly. As far as I know, you can draw a View directly into a bitmap, but that's not possible with Compose.
So I thought, I fought, I lost, and now I rest, but in the end, I repented. I think the best way to create a PDF on Android is to create the desired layout in HTML and print it to a PDF, which itself has its issues because you need to rely on WebView, but it's doable.

🌐
GeeksforGeeks
geeksforgeeks.org › android › how-to-generate-a-pdf-file-in-android-app
How to Generate a PDF file in Android App? - GeeksforGeeks
July 23, 2025 - So for generating a new PDF file from the data present inside our Android app we will be using Canvas. Canvas is a predefined class in Android which is used to make 2D drawings of the different objects on our screen.
🌐
Medium
medium.com › android-school › exploring-itext-to-create-pdf-in-android-5577881998c8
Exploring iText : To Create PDF in Android | by Pratik Butani | Android School | Medium
July 18, 2017 - /** * Creating Document */ Document document = new Document();// Location to save PdfWriter.getInstance(document, new FileOutputStream(dest)); // Open to write document.open(); // Document Settings document.setPageSize(PageSize.A4); document.addCreationDate(); document.addAuthor("Android School"); document.addCreator("Pratik Butani");
🌐
Aspose
blog.aspose.com › aspose.blogs › convert html to pdf in android programmatically
HTML to PDF in Android Programmatically | Android Converter Library
April 27, 2021 - Create the Document object and initialize it with _InputStream _and _HtmlLoadOptions _objects. Save HTML as PDF using Document.save(String) method. The following code sample shows how to save a web page as PDF in Android programmatically.
🌐
Medium
medium.com › @strawberryinc0531 › convert-xml-to-pdf-in-android-studio-using-pdfdocument-class-757dee166d50
Create PDF from layout XML in Android Studio using PDFDocument class | by Sowbhagya Visweswaran | Medium
August 27, 2021 - Create PDF from layout XML in Android Studio using PDFDocument class Often developers tend to use third-party libraries for generating a PDF in Android Studio. What if I want to create professional …