Home > Java > javaTutorial > How to Display a PDF File in an Android App?

How to Display a PDF File in an Android App?

Susan Sarandon
Release: 2024-12-06 10:53:11
Original
799 people have browsed it

How to Display a PDF File in an Android App?

How to Render PDF in Android

In Android applications, you may encounter scenarios where you need to render PDFs. This can be accomplished by following these steps:

Converting Byte Stream to PDF File:

Once you receive the byte stream, save it to the phone's memory as a PDF file using standard file handling techniques.

Rendering PDF in an Activity:

To display the PDF in an activity, you can leverage the Android Intent mechanism. Here's a sample code snippet that demonstrates this approach:

public class OpenPdf extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button button = (Button) findViewById(R.id.OpenPdfButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File("/sdcard/example.pdf");

                if (file.exists()) {
                    Uri path = Uri.fromFile(file);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(path, "application/pdf");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    try {
                        startActivity(intent);
                    } 
                    catch (ActivityNotFoundException e) {
                        Toast.makeText(OpenPdf.this, 
                            "No Application Available to View PDF", 
                            Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }
}
Copy after login

In this code, the OpenPdf activity initializes a button (OpenPdfButton) that, when clicked, attempts to open a PDF file located at /sdcard/example.pdf. If the file exists, an Intent is created to view the PDF using the appropriate application. If no appropriate application is found, a message is displayed indicating so.

The above is the detailed content of How to Display a PDF File in an Android App?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template