Intermediate 30 min Java Full project

Text to PDF Converter and PDF Viewer in Android Studio

Turn text into a PDF file saved on the phone, then open it in a built-in PDF viewer.

What you'll learn

  • Create a PDF with PdfDocument, no library needed
  • Flow long text across pages
  • Show the PDF with PdfRenderer
  • Share or save a copy without storage permission

Before you start

  • Android Studio (any recent version)
  • Basic Java: variables, methods and if/else
  • An emulator or an Android phone

How it fits together

  1. 1Type title and text
  2. 2PdfMaker (PdfDocument)
  3. 3pdfs/Title.pdf in app storage
  4. 4PdfRenderer viewer
  5. 5Share or Save a copy

Build it step by step

1. Create the project

In Android Studio choose New Project → Empty Views Activity, with Language Java and Minimum SDK API 24.

2. No library needed

Android can write and read PDFs by itself: PdfDocument creates them and PdfRenderer displays them. There's nothing to add to Gradle, and no storage permission is needed.

3. Build the form

In activity_main.xml, add a title box and a large text box that fills the screen, then a Create PDF button.

4. Lay out the text

A PDF page is a canvas measured in points; A4 is 595 × 842. StaticLayout wraps your text into lines that fit between the margins, just like a TextView does.

5. Draw the pages

In PdfMaker, startPage gives you a Canvas. The first page gets the title, the date and a thin line. Then draw as many whole lines of text as fit, add the page number, and finishPage. Repeat until every line is drawn, so long text flows onto page 2, 3 and so on.

6. Save it

writeTo saves the PDF into the app's own files/pdfs folder, then close() frees the memory. The title becomes the file name, keeping only letters, digits and dashes.

7. Work in the background

Writing a long PDF takes a moment, so MainActivity does it on a background thread and comes back to the main thread to open the viewer.

8. Show the PDF

PdfViewerActivity opens the file with PdfRenderer. For each page, it draws the page into a Bitmap as wide as the screen and shows it in an ImageView. Fill the bitmap with white first: PDF pages are transparent.

9. Share it

App files are private, so another app can't open them directly. Register a FileProvider in the manifest (Required setup) and res/xml/file_paths.xml. FileProvider.getUriForFile then gives a temporary content:// link to send with ACTION_SEND.

10. Save a copy

ActivityResultContracts.CreateDocument("application/pdf") opens the system Save to screen. The user picks a place, such as Downloads, and you copy the file there.

11. Run it

Paste in a long piece of text to see it flow across pages, then try Share and Save.

What's improved over the video

No third-party PDF library, text wraps and flows onto new pages, writing happens in the background, a built-in viewer shows every page, and you can share or save a copy without any storage permission.

Required setup

These are additions to an existing project—not replacement project files.

Register the viewer and FileProvider

Merge additions

Where: app/src/main/AndroidManifest.xml

Add these inside <application>. No dependencies or permissions are needed.

app/src/main/AndroidManifest.xml
<!-- Inside <application> -->
<activity android:name=".PdfViewerActivity" />

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.files"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

Application code

Select a file to see its code and where it belongs.

This code uses package com.example.texttopdf. Change that first line to your own package, the one at the top of your MainActivity.

Replace fileapp/src/main/java/com/example/texttopdf/MainActivity.java

Checks the title and text, writes the PDF in the background, then opens the viewer.

MainActivity.java
package com.example.texttopdf;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.format.DateFormat;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputLayout;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** Type a title and some text, then turn them into a PDF and open it in the viewer. */
public class MainActivity extends AppCompatActivity {
    /** Writing a long PDF can take a moment, so it happens off the main thread. */
    private final ExecutorService background = Executors.newSingleThreadExecutor();
    private final Handler mainThread = new Handler(Looper.getMainLooper());

    private TextInputLayout titleLayout, bodyLayout;
    private Button create;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Screens.setUp(this, R.layout.activity_main);
        titleLayout = findViewById(R.id.layoutTitle);
        bodyLayout = findViewById(R.id.layoutBody);
        create = findViewById(R.id.btnCreate);
        create.setOnClickListener(v -> create());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        background.shutdown();
    }

    private void create() {
        String title = text(titleLayout);
        String body = text(bodyLayout);
        titleLayout.setError(title.isEmpty() ? getString(R.string.error_title) : null);
        bodyLayout.setError(body.isEmpty() ? getString(R.string.error_body) : null);
        if (title.isEmpty() || body.isEmpty()) return;

        // Files in getFilesDir() belong to the app: no storage permission is needed.
        File file = new File(new File(getFilesDir(), "pdfs"), fileName(title));
        String date = DateFormat.getLongDateFormat(this).format(new Date());

        create.setEnabled(false);
        background.execute(() -> {
            boolean ok = writePdf(title, date, body, file);
            mainThread.post(() -> {
                create.setEnabled(true);
                if (ok) {
                    startActivity(new Intent(this, PdfViewerActivity.class).putExtra("path", file.getAbsolutePath()));
                } else {
                    Toast.makeText(this, R.string.error_create, Toast.LENGTH_LONG).show();
                }
            });
        });
    }

    private static boolean writePdf(String title, String date, String body, File file) {
        File folder = file.getParentFile();
        if (folder == null || !(folder.isDirectory() || folder.mkdirs())) return false;
        try {
            PdfMaker.write(title, date, body, file);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /** "My notes: day 1" becomes "My-notes-day-1.pdf". Only letters, digits and dashes are safe in every file system. */
    static String fileName(String title) {
        String safe = title.replaceAll("[^A-Za-z0-9]+", "-").replaceAll("^-|-$", "");
        return (safe.isEmpty() ? "document" : safe) + ".pdf";
    }

    private static String text(TextInputLayout layout) {
        return layout.getEditText() == null ? "" : layout.getEditText().getText().toString().trim();
    }
}

Full source code