繁体   English   中英

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

[英]Displaying pdf in a TextView from assets/raw folder in android

我有两个活动,MainActivity.java 和 SampleActivity.java。我在资产文件夹中存储了一个 .pdf 文件。 我的第一个活动中有一个按钮。当我单击该按钮时,我希望将 pdf 文件显示在 SampleActivity.java 的文本视图中。 第二个活动也将有一个下载按钮来下载 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();
    }

当我单击该按钮时,我希望 pdf 文件显示在 SampleActivity.java 的文本视图中。

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

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

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

第二个活动也将有一个下载按钮来下载 pdf 文件。

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

我尝试使用 .txt 文件,它工作正常,但同样不适用于 pdf 文件。

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

以下是您可以在 Android 中的 imageview 中显示 pdf(来自资产文件夹)内容的代码

私有无效 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM