1

i need to display online pdf file in my app. i am using third party api but problem is that it's not displaying online file here is my code

compile 'com.github.barteksc:android-pdf-viewer:2.5.1'
compile 'org.apache.commons:commons-io:1.3.2'

my xml file

    <com.github.barteksc.pdfviewer.PDFView
    android:id="@+id/pdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

and here is my final code to render online pdf file in PDFview

    Uri uri = Uri.parse("http://www.pdf995.com/samples/pdf.pdf");
    mypdfview =(PDFView)findViewById(R.id.pdfView);


    mypdfview.fromUri(uri)
            .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
            .enableSwipe(true) // allows to block changing pages using swipe
            .swipeHorizontal(false)
            .enableDoubletap(true)
            .defaultPage(0)
            .onDraw(this) // allows to draw something on a provided canvas, above the current page
            .onLoad(this) // called after document is loaded and starts to be rendered
            .onPageChange(this)
            .onPageScroll(this)
            .onError(this)
            .onRender(this) // called after document is rendered for the first time
            .enableAnnotationRendering(false) // render annotations (such as comments, colors or forms)
            .password(null)
            .scrollHandle(null)
            .enableAntialiasing(true) // improve rendering a little bit on low-res screens
            .load();

i am facing problem that i can display file from asset folder. but when i passed uri then it not showing anything. i also given internet permission and external data read permission in menifest.

user7824858
  • 59
  • 1
  • 2
  • 9

7 Answers7

2

It seems that library doesn't allow to display remote files.

Check this issue: Library does not support remote files, you have to download it by yourself.

You should download and store that PDF locally before trying to display it.

nano
  • 2,511
  • 4
  • 25
  • 42
1

Alternatively you can use Webview to load pdf

webView.loadUrl("http://docs.google.com/gview?embedded=true&url=" +pdfUrl);

WebView webView = (WebView) findViewById(R.id.my_webview);
webView.setWebViewClient(new MyWebViewClient());
webView.addView(webView.getZoomControls());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://docs.google.com/gview?embedded=true&url=" +pdfUrl);
PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
1

Rather than using some other control, you can use the webview for viewing the pdf within your application

String url = "http://docs.google.com/gview?embedded=true&url=" + yourURL;
String doc="<iframe src='"+url+"' width='100%' height='100%' style='border: none;'></iframe>";
WebView web=(WebView)findViewById(R.id.webViewpdf);
webView.getSettings().setJavaScriptEnabled(true); 
webView.loadData(doc, "text/html", "UTF-8");
Chetan Talwar
  • 111
  • 1
  • 6
  • yaa but using webview i cant acchive some property of pdfviewer. like zoom in and zoom out and pagechange and some other. so have to use pdfviewer. – user7824858 May 10 '17 at 07:40
1

First you should read the file of pdf using Asynctask and then load...

Here is the code that worked for me...

Note here I am using pdfview library to show pdf

implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

!!!online_pdf is the string variable which contains the Url of pdf

First make LOADURL class extending AsyncTask

public class LOADURL extends AsyncTask<String,Void,InputStream>
{
private ProgressDialog progressDialog;
public LOADURL(LoadPDF loadPdf) {

        progressDialog = new ProgressDialog(loadPdf);

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog.setTitle("Please wait");
        progressDialog.setMessage("Fetching PDF from server...");
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

    }

    @Override
    protected InputStream doInBackground(String... strings) {
        InputStream inputStream = null;
        try
        {
            URL url = new URL(strings[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) 
     url.openConnection();
            if (urlConnection.getResponseCode()==200)
            {

                inputStream = new 
     BufferedInputStream(urlConnection.getInputStream());

            }
        } catch (IOException e) {

            return null;
        }
        return inputStream;
    }

    @Override
    protected void onPostExecute(InputStream inputStream) {
        pdfFileName = getFileName(mypdf);
        pdfViewer.fromStream(inputStream)
                .defaultPage(pageNumber)
                .onPageChange(LoadPDF.this)
                .enableAnnotationRendering(true)
                .onLoad(LoadPDF.this)
                .scrollHandle(new DefaultScrollHandle(LoadPDF.this))
                .spacing(10) // in dp
                .onPageError(LoadPDF.this)
                .onError(LoadPDF.this)
                .onPageError(LoadPDF.this)
                .enableAnnotationRendering(false)
                .enableAntialiasing(true)
                .onRender(LoadPDF.this)
                .load();
        progressDialog.dismiss();
    }

}

After that call the class within onCreate View...

LOADURL loadurl = new LOADURL(LoadPDF.this);
loadurl.execute(online_pdf);
1

You can use PDFRenderer provided by Android SDK (added in API level 21) to render PDF inside your android application. Download the PDF and save it on local storage and use below code to render it inside your app.

PdfRendererAdapter.kt

class PdfRendererAdapter(
private val renderer: PdfRenderer?,
private val pageWidth: Int
) : RecyclerView.Adapter<PdfRendererAdapter.ViewHolder>() {

class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    private val imageView: ImageView = view.imageView
    fun bind(bitmap: Bitmap) = imageView.setImageBitmap(bitmap)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
    ViewHolder(
        LayoutInflater.from(parent.context).inflate(R.layout.pdf_page_item, parent, false)
    )

override fun getItemCount() = renderer!!.pageCount

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val currentPage = renderer?.openPage(position)
    val bitmap = currentPage!!.render(pageWidth)
    holder.bind(bitmap)
}

}

PDFRendererExtensions.kt

fun PdfRenderer.Page.render(width: Int): Bitmap {
val bitmap = createBitmap(width)
render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
close()
return bitmap
}

private fun PdfRenderer.Page.createBitmap(bitmapWidth: Int): Bitmap {
val bitmap = Bitmap.createBitmap(
    bitmapWidth, (bitmapWidth.toFloat() / width * height).toInt(), Bitmap.Config.ARGB_8888
)

val canvas = Canvas(bitmap)
canvas.drawColor(Color.WHITE)
canvas.drawBitmap(bitmap, 0f, 0f, null)

return bitmap
}

PDFRendererActivity.kt

class PdfRenderActivity : AppCompatActivity() {
private var pdfRenderer: PdfRenderer? = null
private var currentPage: PdfRenderer.Page? = null
private var parcelFileDescriptor: ParcelFileDescriptor? = null

companion object {
    const val FILE_NAME = "testPDF.pdf"
    private const val INTENT_PDF_FILE = "pdf_file"

    fun getCallingIntent(context: Context, pdfFile: File): Intent {
        val intent = Intent(context, PdfRenderActivity::class.java)
        intent.putExtra(INTENT_PDF_FILE, pdfFile)
        return intent
    }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_pdf_renderer)
    openRenderer()
    showPagesInRecyclerView()
}

private fun showPagesInRecyclerView() {
    currentPage = pdfRenderer!!.openPage(0)
    val pdfAdapter = PdfRendererAdapter(renderer = pdfRenderer, pageWidth = currentPage!!.width)
    currentPage!!.close()
    pdf_rv.adapter = pdfAdapter
    pdf_rv.layoutManager =
        LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
}

public override fun onStop() {
    try {
        closeRenderer()
    } catch (e: IOException) {
        e.printStackTrace()
    }
    super.onStop()
}

private fun openRenderer() {
    val file = intent.extras?.get(INTENT_PDF_FILE) as File
    parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
    if (parcelFileDescriptor != null) {
        pdfRenderer = PdfRenderer(parcelFileDescriptor!!)
    }
}

private fun closeRenderer() {
    pdfRenderer!!.close()
    parcelFileDescriptor!!.close()
}
}
  • Do not post a link to a tool or library as an answer. Demonstrate [how it solves the problem](http://meta.stackoverflow.com/a/251605) in the answer itself. Do [edit] the answer, and flag for undeletion once you have added the demonstration. – Bhargav Rao Sep 20 '20 at 19:24
0

This will helps you How to open/display documents(.pdf, .doc) without external app?

Add this dependency in your Grade:

compile 'com.github.barteksc:android-pdf-viewer:2.0.3'

activity_main.xml

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    xmlns:android="http://schemas.android.com/apk/res/android" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="@color/colorPrimaryDark"
        android:text="View PDF"
        android:textColor="#ffffff"
        android:id="@+id/tv_header"
        android:textSize="18dp"
        android:gravity="center"></TextView>

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_below="@+id/tv_header"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    </RelativeLayout>

MainActivity.java

public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{

    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String SAMPLE_FILE = "android_tutorial.pdf";
    PDFView pdfView;
    Integer pageNumber = 0;
    String pdfFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pdfView= (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
}
Community
  • 1
  • 1
Gowtham Subramaniam
  • 3,358
  • 2
  • 19
  • 31
0

This is a best way to load remote pdf in app

 WebView  wv = (WebView)findViewById(R.id.webview);
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setWebViewClient(new WebViewClient());
        wv.getSettings().setAllowFileAccess(true);
       String src="http://docs.google.com/gview?embedded=true&url=https://firebasestorage.googleapis.com/v0/b/tuloenaseerapp.appspot.com/o/2_arsh_e_naaz_hq_compressed.pdf?alt=media&token=607c124b-ac28-4560-9854-1fe7d023f813";
        wv.loadUrl(src);
Adnan Bashir
  • 645
  • 4
  • 8