在 android 的 assets/raw 文件夹中的 TextView 中显示 pdf

Displaying pdf in a TextView from assets/raw folder in android

我有两个 activity、MainActivity.java 和 SampleActivity.java.I 在 assets 文件夹中存储了一个 .pdf 文件。 我的第一个 activity.When 中有一个按钮 我单击该按钮 我希望 pdf 文件显示在 SampleActivity.java 的文本视图中。第二个 activity 也会有一个下载 pdf 文件的下载按钮。

我不想使用 webview 或使用外部程序显示。 我尝试使用 .txt 文件,它工作正常,但同样不适用于 pdf 文件。

有什么方法可以实现吗

提前致谢。

我用于 .txt 的代码是

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sample);

    txt=(TextView) findViewById(R.id.textView1);

    try
    {
        InputStream is=getAssets().open("hello.txt");
        int size=is.available();
        byte[] buffer=new byte[size];
        is.read(buffer);
        is.close();

        String text=new String(buffer);

        txt.setText(text);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

When i click that button i want the pdf file to be displayed in the textview of SampleActivity.java.

那是不可能的。 TextView 无法呈现 PDF。

在 Android 5.0+ 上,打印框架中有一些东西可以将 PDF 转换为图像,着眼于打印预览。你应该能够让它与 ImageView 一起工作,尽管我还没有玩过它。此外,目前 Android 5.0+ 代表约 10% 的 Android 设备。

或者,欢迎您查找包含在应用中的 PDF 渲染库。

The second activity also will have a download button to download the pdf file.

这是不可能的,因为您无法替换 assets/ 中的 PDF 文件。资产在运行时是只读的。欢迎您将 PDF 文件下载到 read/write 的某个地方,例如内部存储。但是,您仍然无法在 TextView.

中显示 PDF 文件

I tried with .txt files and it worked correctly but same did'nt work with pdf file.

除了上面提到的所有问题之外,PDF文件不是文本文件。它们是二进制文件。您无法将 PDF 读入 String.

下面是您可以在 Android

的图像视图中显示 pdf(来自资产文件夹)内容的代码

private void openPDF() 抛出 IOException {

    //open file in assets


    File fileCopy = new File(getCacheDir(), "source_of_information.pdf");

    InputStream input = getAssets().open("source_of_information.pdf");
    FileOutputStream output = new FileOutputStream(fileCopy);

    byte[] buffer = new byte[1024];
    int size;
    // Copy the entire contents of the file
    while ((size = input.read(buffer)) != -1) {
        output.write(buffer, 0, size);
    }
    //Close the buffer
    input.close();
    output.close();

    // We get a page from the PDF doc by calling 'open'
    ParcelFileDescriptor fileDescriptor =
            ParcelFileDescriptor.open(fileCopy,
                    ParcelFileDescriptor.MODE_READ_ONLY);
    PdfRenderer mPdfRenderer = new PdfRenderer(fileDescriptor);
    PdfRenderer.Page mPdfPage = mPdfRenderer.openPage(0);

    // Create a new bitmap and render the page contents into it
    Bitmap bitmap = Bitmap.createBitmap(mPdfPage.getWidth(),
            mPdfPage.getHeight(),
            Bitmap.Config.ARGB_8888);
    mPdfPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

    // Set the bitmap in the ImageView
    imageView.setImageBitmap(bitmap);
}