How to render PDF in Android
Asked Answered
S

6

84

In my application I will receive a byte stream and convert it to a pdf file in the phone memory. How do I render that to a pdf? And show it on an activity?

Sloppy answered 21/5, 2010 at 15:21 Comment(1)
This has been answered here: https://mcmap.net/q/120086/-convert-a-pdf-page-into-bitmap-in-android-javaSketchy
E
115

Some phones (like the Nexus One) come with a version of Quickoffice pre-installed so it may be as easy as sending the appropriate Intent once you've saved the file to the SD card.

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();
                    }
                }
            }
        });
    }
}
Erlin answered 21/5, 2010 at 21:35 Comment(8)
hmm ill try this tomorrow. so from byte streams i will get i need to save them as a file and then try doing that code .Sloppy
hmm how about if i do not have QuickOffice installed in my Android?Sloppy
so? what if you do not have QuickOffice?Washburn
If phone has not quick Office then?Wilburwilburn
How to do open the PDF file directly from the Server? Rather than saving it on the device and then opening.Latarsha
I tried same but it occurs execption "android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW"Allow
Isn't adobe pdf reader available for android for free? yep.Sylphid
For those people asking if QuickOffice is not found, just catch ActivityNotFoundException and show an alert, which gives the user the option to download a PDF viewer from the app store.Suet
P
15

Open pdf file in webview.

public class MyPdfViewActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WebView mWebView=new WebView(MyPdfViewActivity.this);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setPluginsEnabled(true);
    mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
    setContentView(mWebView);
  }
}
Pitsaw answered 2/6, 2012 at 10:16 Comment(4)
i think this only works with the google viewer link, because it only serves images. If we use link to pdf directly, it won't work. Is that correct ?Cispadane
This does not appear to work for local files, only remote ones.Prolific
What if link will change?Inverson
"After testing it persistently for 2 days, I got an error on Google docs saying You've reached the bandwidth limit for viewing or downloading files that aren't in Google Docs format..... So doesn't seem reliable." #2656472Teflon
H
10

Android-Lollipop (api 21) introduce a new API : PdfRenderer

This API allows you to create a Bitmap from a page in a PDF document.

Shortly :

  • get a seekable file descriptor from your pdf document :

      ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
    
  • create the PdfRenderer

      PdfRenderer renderer = new PdfRenderer(fd);
    
  • prepare the Bitmap

      Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_4444);
    
  • get the PdfRenderer.Page to render

      PdfRenderer.Page page = renderer.openPage(pageIndex);
    
  • render the page on the prepared bitmap

      page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    
  • now you can do what you want with the bitmap.

  • note that the 2 null args may allow you to clip some portion in the page and perform a transformation (using a Matrix) of the clip

  • there is another rendering mode : RENDER_MODE_FOR_PRINT. If you need this mode there are some guidelines to use it properly : here are the details.

Hypognathous answered 8/11, 2014 at 10:1 Comment(2)
Is there any way to achieve this without saving file on the phone? I am getting PDF as bytestream and I need to show it to user without saving it on the phone.Depressant
the constraint is to pass a seekable file descriptor to the constructor; and fd from a socket stream is not seekable. You may try to store all the bytes from the stream in a buffer and get a seekable fd from that.Hypognathous
L
5

This library is simple and works well: Android Pdf Viewer https://github.com/barteksc/AndroidPdfViewer

Old Reply...

I think that Joan Zapata give us the better and simple solution:

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

I assure you that it works!

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

Lundt answered 14/11, 2014 at 10:14 Comment(3)
Alecs: What did you use for the pdfName in pdfView.fromAsset(pdfName)? I tried using the absolute path, but the file was not found (and I am certain it is there). Example: /data/data/package.name/files/images/filename.pdfTurnabout
Dear @h-bomb, you have to use fromasset method when your pdf is in the asset foder of your project. To load the pdf from the device, you can use fromFile method.Lundt
Thanks so much. I decided to use Android's FileProvider and allow an external app open the PDF. Suprisingly, the documentation and sample code in the FileProvider dev doc were excellent.Turnabout
G
3

For the local pdf files, you can render them through the third party libraries. for example, use the MuPDF library, its supported file types include PDF, PNG and JPEG.

One shortcoming of MuPDF is that it uses native library to fulfill the target, so it won't be easy to port the application on BlackBerry platform later.

Griffen answered 26/5, 2014 at 14:17 Comment(0)
N
0

To open a pdf from a byte array, you can use RadaeePDF, you can do the following into your activity:

private PDFReader m_vPDF = null;
private Document doc = new Document();

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    Global.Init(this);

    m_vPDF = new PDFReader(this);
    doc.Close();

    int ret = m_doc.OpenMem(data, password);
        switch( ret )
        {
            case -1://need input password
                finish();
                break;
            case -2://unknown encryption
                finish();
                break;
            case -3://damaged or invalid format
                finish();
                break;
            case -10://access denied or invalid file path
                finish();
                break;
            case 0://succeeded, and continue
                break;
            default://unknown error
                finish();
                break;
        }

    m_vPDF.open(doc);

    setContentView( m_vPDF );
}
Nicko answered 21/11, 2014 at 9:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.