4

I'm using barteksc pdf viewer library to load pdf in my application.

pdfView = findViewById(R.id.pdfView);
            pdfView.fromAsset(getResources().getString(R.string.pdfname))
                    .enableDoubletap(true)
                    .enableSwipe(true)
                    .defaultPage(pageNumber)
                    .onPageChange(mainreading.this)
                    .pageFitPolicy(FitPolicy.WIDTH)
                    .pageFling(true)
                    .linkHandler(null)
                    .enableAnnotationRendering(true)
                    .swipeHorizontal(true)
                    .scrollHandle(new DefaultScrollHandlenew(mainreading.this))
                    .enableAntialiasing(true)
                    .load();
        }

I want pdf to start scroll automatically when user click the button of volume up and down buttons to start stop. I tried with below code while wrapping it in the handler with handler.performClick(); but it shows blank screen while scrolling up and down.

    scrollbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pdfView.scrollTo(0, pdfView.getScrollY() + 24);
        }
    });

Example : https://play.google.com/store/apps/details?id=com.emptysheet.pdfreader_autoscroll&hl=en&gl=US

I want to make as like this. Can anyone help please.

Also tried with this. But it shows blank page after some scrolls.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int action = event.getAction();
    int keyCode = event.getKeyCode();
    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_UP:
            if (action == KeyEvent.ACTION_DOWN) {
                pdfView.scrollTo(0, pdfView.getScrollY() -24);
            }
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                pdfView.scrollTo(0, pdfView.getScrollY() + 24);
            }
            return true;
        default:
            return super.dispatchKeyEvent(event);
    }
}

2 Answers2

0

You can simply use this PDF viewer from github. It's based on the same 'barsteksc' pdf viewer with the feature to jump to any pages.

It's MagicalPdfViewer and you can use 'jumpTo(pageNo)' method to simply jump to the specific page. It also gives you the option to animate to the specific page with the same method, just pass 'true' as the 2nd parameter.

Moreover, if you pass the values like '-1' and 'bigger than pageNo', It will automatically scroll to the 0 & last page respectively.

Give it a try & let me know if you got what you wanted.

Dev4Life
  • 2,328
  • 8
  • 22
  • Thank you so much Dev4Life, Sir I check this, and I think it might work but actually problem is that I'm working with barteksc pdf reader from long time and I have done a lot of coding and added almost every possible functionality. You can check here https://play.google.com/store/apps/details?id=com.traffic.signs.driving.test . So, it's not possible for me to change everything. I appropriate your contribution. Thanks in advance. – Shahid Niazi Dec 03 '22 at 13:06
  • @ShahidNiazi If you haven't changed the core dependency module code, then you can replace it with the new one I suggested..otherwise you'll have to find the specific place to put the new 'jumpToPage()' code. – Dev4Life Dec 05 '22 at 04:52
  • Thanks.... actually I'm not using jumpToPage() neither want to. I want to use scrollTo or moveTo because I want the pdf reader to move to pixels not pages. I also tried wrapping this in handler with infinite loop (that's actually a workaround and also work somehow but page got blank after some scrolls. Is that possible to control 'scrollHandle' with 'Touchevent' I have separate activity for scroll handle. I want to make something like this. https://play.google.com/store/apps/details?id=com.emptysheet.pdfreader_autoscroll – Shahid Niazi Dec 05 '22 at 11:34
0
    import android.content.Context
    import android.graphics.Bitmap
    import android.graphics.Canvas
    import android.graphics.pdf.PdfRenderer
    import android.os.Bundle
    import android.os.Handler
    import android.os.Looper
    import android.os.ParcelFileDescriptor
    import android.view.View
    import android.widget.LinearLayout
    import android.widget.ScrollView
    import androidx.appcompat.app.AppCompatActivity
    import com.app.pie.R
    import java.io.File
    import java.io.FileOutputStream
    
    class PDFAutoScrollActivity : AppCompatActivity() {
    
        private lateinit var scrollView: ScrollView
        private lateinit var pdfRenderer: PdfRenderer
        private lateinit var pdfPageViews: MutableList<PdfPageView>
    
        private val scrollSpeed = 3
        private val scrollDelay = 2000
        private val scrollInterval = 10
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_pdf_auto_scroll)
    
            scrollView = findViewById(R.id.scrollView)
    
            val assetManager = applicationContext.assets
            val fileName = "sample_five.pdf" // Replace with the actual file name
            val file = File(cacheDir, fileName)
            if (!file.exists()) {
                val inputStream = assetManager.open(fileName)
                val outputStream = FileOutputStream(file)
                inputStream.copyTo(outputStream)
                inputStream.close()
                outputStream.close()
            }
    
            pdfRenderer =
                PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY))
    
            pdfPageViews = mutableListOf()
            val parentLinearLayout = LinearLayout(this)
            parentLinearLayout.orientation = LinearLayout.VERTICAL
            for (pageIndex in 0 until pdfRenderer.pageCount) {
                val pdfPage = pdfRenderer.openPage(pageIndex)
                val displayMetrics = resources.displayMetrics
                val screenWidth = displayMetrics.widthPixels
    
                val pdfPageWidth = pdfPage.width
                val pdfPageHeight = pdfPage.height
                val scaleFactor = screenWidth.toFloat() / pdfPageWidth.toFloat()
                val scaledHeight = (scaleFactor * pdfPageHeight).toInt()
                val pdfBitmap = Bitmap.createBitmap(screenWidth, scaledHeight, Bitmap.Config.ARGB_8888)
                pdfPage.render(pdfBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                pdfPage.close()
                val pdfPageView = PdfPageView(this, pdfBitmap)
                val layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    scaledHeight
                )
                val linearLayout = LinearLayout(this)
                linearLayout.orientation = LinearLayout.VERTICAL
                linearLayout.addView(pdfPageView, layoutParams)
                pdfPageViews.add(pdfPageView)
                parentLinearLayout.addView(linearLayout)
            }
    
            scrollView.addView(parentLinearLayout)
            scrollView.isSmoothScrollingEnabled = true
            scrollView.postDelayed({
                startAutoScrolling()
            }, scrollDelay.toLong())
        }
    
        private fun startAutoScrolling() {
            val totalHeight = pdfPageViews.sumBy { it.height }
            val maxScrollY = totalHeight - scrollView.height
            val scrollRunnable = object : Runnable {
                var scrollY = 0
    
                override fun run() {
                    scrollY += scrollSpeed
                    if (scrollY >= maxScrollY) {
                        scrollY = maxScrollY
                    }
                    scrollView.scrollTo(0, scrollY)
                    if (scrollY < maxScrollY) {
                        scrollView.postDelayed(this, scrollInterval.toLong())
                    } else {
                        scrollView.scrollTo(0, 0)
                        Handler(Looper.getMainLooper()).postDelayed({
                            // Code to be executed after a delay
                            scrollY = 0
                            scrollView.postDelayed(this, scrollInterval.toLong())
                        }, 2000)
                    }
                }
            }
            scrollView.postDelayed(scrollRunnable, scrollDelay.toLong())
        }
    
        override fun onDestroy() {
            super.onDestroy()
            pdfRenderer.close()
        }
    
        class PdfPageView(context: Context, private val pdfBitmap: Bitmap) : View(context) {
            override fun onDraw(canvas: Canvas) {
                super.onDraw(canvas)
                canvas.drawBitmap(pdfBitmap, 0f, 0f, null)
            }
        }
    
    }

layout activity_pdf_auto_scroll

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/scrollView"
    android:background="@color/white"
    android:fillViewport="true"
    android:layout_height="match_parent"
    tools:context=".activity.PDFAutoScrollActivity">
</ScrollView>
Hardip
  • 360
  • 3
  • 9