我有两个活动,MainActivity.java和SampleActivity.java.I已在assets文件夹中存储了.pdf文件。 我的第一个活动中有一个按钮。当我单击该按钮时,我希望pdf文件显示在SampleActivity.java的textview中。第二个活动还将有一个下载按钮来下载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();
}
答案 0 :(得分:0)
当我点击该按钮时,我希望pdf文件显示在SampleActivity.java的textview中。
这是不可能的。 TextView
无法呈现PDF。
在Android 5.0及更高版本中,打印框架中有一些东西可以将PDF转换为图像,并着眼于打印预览。您应该能够使用ImageView
,但我尚未玩过它。此外,目前,Android 5.0+占Android设备的10%左右。
或者,欢迎您找到您在应用中添加的PDF呈现库。
第二个活动还有一个下载按钮来下载pdf文件。
这是不可能的,因为您无法替换assets/
中的PDF文件。资产在运行时是只读的。欢迎您将PDF文件下载到可读/写的某个位置,如内部存储。但是,您仍然无法在TextView
。
我尝试使用.txt文件,但它运行正常,但同样适用于pdf文件。
除上述所有问题外,PDF文件不是文本文件。它们是二进制文件。您无法将PDF读入String
。
答案 1 :(得分:0)
下面是可以在Android的imageview中显示pdf(来自Assets文件夹)内容的代码
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);
}