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
🌐
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
🌐
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
🌐
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. So in this article, we will be using canvas to draw our data inside our canvas, and then we will store that canvas in the form of a PDF.
🌐
Blogger
devofandroid.blogspot.com › 2018 › 11 › write-pdf-android-studio-java.html
Write PDF - Android Studio - Java
July 4, 2023 - Write PDF using EditText: 1) We will use iText PDF Library to create pdf 2) We will input text Using EditText 3) Button to save text as PDF file 4) It will require WRITE_EXTERNAL_STORAGE permission to save pdf file, 5) We'll handle runtime ...
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());
    }
Top answer
1 of 3
3

Do it this way:

import com.cete.dynamicpdf.*;
import com.cete.dynamicpdf.pageelements.Label;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class DynamicPDFHelloWorld extends Activity {
    private static String FILE = Environment.getExternalStorageDirectory()
            + "/HelloWorld.pdf";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Create a document and set it's properties
        Document objDocument = new Document();
        objDocument.setCreator("DynamicPDFHelloWorld.java");
        objDocument.setAuthor("Your Name");
        objDocument.setTitle("Hello World");

        // Create a page to add to the document
        Page objPage = new Page(PageSize.LETTER, PageOrientation.PORTRAIT,
                54.0f);

        // Create a Label to add to the page
        String strText = "Hello World...\nFrom DynamicPDF Generator "
                + "for Java\nDynamicPDF.com";
        Label objLabel = new Label(strText, 0, 0, 504, 100,
                Font.getHelvetica(), 18, TextAlign.CENTER);

        // Add label to page
        objPage.getElements().add(objLabel);

        // Add page to document
        objDocument.getPages().add(objPage);

        try {
            // Outputs the document to file
            objDocument.draw(FILE);
            Toast.makeText(this, "File has been written to :" + FILE,
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(this,
                    "Error, unable to write to file\n" + e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
    }
}

Also check these links. They will help you to fulfill your requirement.

  1. http://www.dynamicpdf.com/Blog/post/2012/06/15/Generating-PDFs-Dynamically-on-Android.aspx

  2. https://github.com/JoanZapata/android-pdfview

  3. How to create PDFs in an Android app?

  4. Render a PDF file using Java on Android

2 of 3
3

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.

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

  • OR

if you WANT TO convert your layout or view into pdf then you have to create image from your layout and then add into pdf.Perfect tutorial of that Go Through this Link . Hope this will help you guys.Thank you.

For Simple Create and Open pdf:

// 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() + "/PDF";

        File dir = new File(path);
        if(!dir.exists())
            dir.mkdirs();

        File file = new File(dir, "mypdffile.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.FontFamily.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("mypdffile.pdf", "PDF");
}

// 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(this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
    }
}
🌐
The Code City
thecodecity.com › home › android › create pdf from layout or any xml view in android studio
Create PDF from Layout or Any XML View in Android Studio
May 24, 2023 - I tutorial on how to create a PDF document from a layout or any XML view in Android Studio, I will walk you through the process of using the PdfDocument class to convert your XML views into PDF files. With this powerful functionality, you can generate professional-looking documents within your Android applications.
🌐
YouTube
youtube.com › watch
Create PDF from any XML Layout/View in Android Studio - Step by Step Tutorial - YouTube
Provided value? Buy me a coffee: https://www.buymeacoffee.com/thecodecityIn the video we will create PDF from XML Layout View using PdfDocument in Android St...
Published   May 24, 2023
Find elsewhere
🌐
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 - Although I have used static data, you can also fetch the data from the internet or the Room database as per your requirements. The next step is to create the necessary XML files which define the layout of our PDF. We will need two layout files for our PDF: one for the entire pdf layout and the second for the item row layout of our recycler view for the subject marks, as shown in Figures 1 and 2.
🌐
Android Developers
developer.android.com › api reference › pdfdocument
PdfDocument | API reference | Android Developers
Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体 · 日本語 · 한국어 Android Studio ·
🌐
YouTube
youtube.com › watch
#6 Create PDF from User Input : Android Studio PDF Document - YouTube
From this video we will learn how to create a pdf invoice based on user Input. The basic idea of this video is to get values from user and generate invoice a...
Published   March 3, 2020
🌐
GeeksforGeeks
geeksforgeeks.org › kotlin › generate-pdf-file-in-android-using-kotlin
Generate PDF File in Android using Kotlin - GeeksforGeeks
July 23, 2025 - Toast.makeText(this, "Permissions Granted..", Toast.LENGTH_SHORT).show() } else { // if the permission is not granted // we are calling request permission method. requestPermission() } // on below line we are adding on click listener for our generate button. generatePDFBtn.setOnClickListener { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { // on below line we are calling generate // PDF method to generate our PDF file. generatePDF() } } } // on below line we are creating a generate PDF method // which is use to generate our PDF file.
🌐
Medium
medium.com › @programmingAi › how-to-create-your-own-pdf-editor-for-android-step-by-step-a9a09b4d12fb
How to Create Your Own PDF Editor for Android Step by Step | by Alamghir | Medium
December 6, 2024 - Android Studio installed on your computer. Basic knowledge of Java or Kotlin programming languages. A physical device or emulator to test the app. The iText library (which is a powerful PDF manipulation library for Android). Start by creating a new Android project in Android Studio:
🌐
YouTube
youtube.com › deccon tech
Create PDF Document | Android Studio | Kotlin 2024 - YouTube
Create Pdf Document | Android Studio | Kotlin 2024android studio tutorialandroid studioandroidcreate pdf in android studiopdf viewer android studiohow to ope...
Published   March 30, 2024
Views   1K
🌐
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%
🌐
Medium
medium.com › @generalfocus1 › build-your-own-android-pdf-reader-from-scratch-using-android-studio-ac65601eb90
Build Android PDF Reader From Scratch Using Android Studio | by Oyinkansola Olabode | Medium
April 6, 2020 - I’ll be explaining how to make an inbuilt pdf reader in your android application and also how to load a pdf file from your internal or…
🌐
Blogger
devofandroid.blogspot.com › 2018 › 11 › write-pdf-android-studio-kotlin.html
Write PDF - Android Studio - Kotlin
July 4, 2023 - Write PDF using EditText: 1) We will use iText PDF Library to create pdf 2) We will input text Using EditText 3) Button to save text as PDF file 4) It will require WRITE_EXTERNAL_STORAGE permission to save pdf file, 5) We'll handle runtime ...
🌐
GitHub
github.com › xcheko51x › Crear-PDF-Android-Studio › blob › master › MainActivity.java
Crear-PDF-Android-Studio/MainActivity.java at master · xcheko51x/Crear-PDF-Android-Studio
import android.widget.Toast; · import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; · import java.io.File; import java.io.FileOutputStream; import java.io.IOException; ·
Author   xcheko51x
🌐
Scribd
scribd.com › document › 465950485 › Create-Pdf-Book-App-in-Android-Studio-Download-Free-Pdf-Book-Source-Code-pdf
Create PDF Book App in Android Studio - Download Free PDF Book Source Code PDF | PDF | Android (Operating System) | Mobile App
Create Pdf Book App in Android Studio __ Download Free Pdf Book Source Code.pdf - Free download as PDF File (.pdf), Text File (.txt) or read online for free. The document describes how to create a PDF book application in Android Studio. It provides 8 steps to develop the app, including designing the user interface, adding buttons to navigate between PDF files, including the PDF viewer dependency, and loading specific PDF files on button clicks.
Rating: 1 ​ - ​ 1 votes