afreakyelf / Pdf-Viewer

A Lightweight PDF Viewer Android library which only occupies around 80kb while most of the Pdf viewer occupies up to 16MB space.
https://afreakyelf.github.io/Pdf-Viewer/
MIT License
820 stars 173 forks source link

No specific way to load from fragments to a layout #118

Closed psavarmattas closed 8 months ago

psavarmattas commented 8 months ago

📝 Description

I have a fragment in which I want to load the pdf in from storage in the pdf layout I put in the fragment layout xml. The view option I see in your library is only to start from a activity and I don't have the option to use that, therefore is there any option that i'm missing? This might not be a bug but I can't seem to figure it out and really want to use your library as it looks so good for my usecase.

📖 Library Version

🤔 Expected Behavior

What did you expect to happen?

🖼️ Screenshots/Videos

If applicable, add screenshots or videos to help explain your problem.

💻 Code Snippets

PDFViewerFragment.kt

class PDFViewerFragment : Fragment() {

    private var _binding: FragmentPdfViewerBinding? = null
    private lateinit var progressIndicator: LinearProgressIndicator
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPdfViewerBinding.inflate(inflater, container, false)
        return binding.root
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        progressIndicator = view.findViewById(R.id.progressIndicator)
        val pdfView = view.findViewById<PdfRendererView>(R.id.pdfView)

        progressIndicator.visibility = View.VISIBLE // Show loading indicator

        // TODO: MAKE THIS PDF VIEWER WORK IN THIS FRAGMENT

        val pdfPath = context?.filesDir.toString() + "/paperport_001.pdf"
        Log.d("PDFViewerFragment", "PDF Path: $pdfPath")

        try {
            PdfViewerActivity.launchPdfFromPath(
                context = context,
                path = pdfPath,
                pdfTitle = "PDF Test",
                saveTo = saveTo.ASK_EVERYTIME,
                fromAssets = false,
            )
            Log.d("PDFViewerFragment", "Launched PDF Viewer")
            progressIndicator.visibility = View.GONE // Hide loading indicator
        } catch (e: Exception) {
            Log.e("PDFViewerFragment", "Error opening PDF: ", e)
            progressIndicator.visibility = View.VISIBLE // Show loading indicator
        } finally {
            // Close resources if necessary
        }
    }
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

fragment_pdf_viewer.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".utils.PDFViewerFragment">

    <com.google.android.material.progressindicator.LinearProgressIndicator
        android:id="@+id/progressIndicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="true"
        app:layout_constraintTop_toTopOf="parent"/>

    <com.rajat.pdfviewer.PdfRendererView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:pdfView_divider="@drawable/pdf_viewer_divider"
        app:pdfView_showDivider="false" />

</androidx.constraintlayout.widget.ConstraintLayout>

github-actions[bot] commented 8 months ago

Thank you for creating your first issue. We appreciate your help in making this project better. We will look into it, and get back to you soon. Need help or want to discuss this issue? Join our Discord community here to ask questions and discuss this issue live!

psavarmattas commented 8 months ago

Workaround Description:

Okay so I found a workaround to load the files as URI link which can be rendered directly from a fragment. Thanks for an amazing library. Once my project is public I will give you the appropriate credit.

Code:

PDFViewerFragment.kt

class PDFViewerFragment : Fragment() {

    private var _binding: FragmentPdfViewerBinding? = null
    private lateinit var progressIndicator: LinearProgressIndicator
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPdfViewerBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        progressIndicator = view.findViewById(R.id.progressIndicator)

        progressIndicator.visibility = View.VISIBLE
        Log.d("PDFViewerFragment", "Showing progress indicator")

        val pdfPath = getFilePath(context, "paperport_001.pdf")
        Log.d("PDFViewerFragment", "Constructed PDF path: $pdfPath")

        try {
            binding.pdfView.initWithUrl(
                url = pdfPath,
                lifecycleCoroutineScope = lifecycleScope,
                lifecycle = lifecycle
            )
            Log.d("PDFViewerFragment", "PDF Viewer launched successfully")
            progressIndicator.visibility = View.GONE
            Log.d("PDFViewerFragment", "Hiding progress indicator")
        } catch (e: Exception) {
            Toast.makeText(requireContext(), "Error opening PDF: $e", Toast.LENGTH_LONG).show()
            Log.e("PDFViewerFragment", "Error opening PDF:", e)
            progressIndicator.visibility = View.VISIBLE
            Log.d("PDFViewerFragment", "Showing progress indicator")
        } finally {
            Log.d("PDFViewerFragment", "Closing PDF Viewer")
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun getFilePath(context: Context?, filename: String): String {
        return if (context != null && context.filesDir != null) {
            val filesDir = context.filesDir.absolutePath
            "file://$filesDir/$filename"
        } else {
            // Handle cases where context or filesDir is missing:
            "file:///$filename"  // Assume default location or provide alternative strategy
        }
    }
}

fragment_pdf_viewer.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".utils.PDFViewerFragment">

    <com.google.android.material.progressindicator.LinearProgressIndicator
        android:id="@+id/progressIndicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="true"
        app:layout_constraintTop_toTopOf="parent"/>

    <com.rajat.pdfviewer.PdfRendererView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:pdfView_divider="@drawable/pdf_viewer_divider"
        app:pdfView_showDivider="false" />

</androidx.constraintlayout.widget.ConstraintLayout>
afreakyelf commented 8 months ago

Glad to hear that @psavarmatts.