[英]how to open pdf file from assets folder
尝试单击按钮从资产文件夹中打开 pdf 文件
public class CodSecreen extends AppCompatActivity {
PDFView pdfView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cod_secreen);
pdfView=(PDFView)findViewById(R.id.pdf);
Intent intent = getIntent();
String str = intent.getStringExtra("message");
if (str.equals(getResources().getString(R.string.introduction))){
pdfView.fromAsset("phpvariable.pdf").load();
}
}
}
通过传递按钮的字符串值
bttn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = bttn1.getText().toString();
Intent i=new Intent(DetailSecreen.this,CodSecreen.class);
startActivity(i);
}
});
你可以通过四个步骤来做到这一点 ☺
第 1 步:在项目中创建资产文件夹并将 PDF 放入其中
:: 例如:assets/MyPdf.pdf
第 2 步:将以下代码放入您的类 [onCreate] 中:
Button read = (Button) findViewById(R.id.read);
// Press the button and Call Method => [ ReadPDF ]
read.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
ReadPDF();
}
});
}
private void ReadPDF()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "MyPdf.pdf"); //<= PDF file Name
try
{
in = assetManager.open("MyPdf.pdf"); //<= PDF file Name
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copypdf(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
System.out.println(e.getMessage());
}
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0 && file.isFile()) {
//Toast.makeText(MainActivity.this,"Pdf Reader Exist !",Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/MyPdf.pdf"),
"application/pdf");
startActivity(intent);
}
else {
// show toast when => The PDF Reader is not installed !
Toast.makeText(MainActivity.this,"Pdf Reader NOT Exist !",Toast.LENGTH_SHORT).show();
}
}
private void copypdf(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
第 3 步:将以下代码放在您的布局中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Read PDF !"
android:id="@+id/read"/>
</LinearLayout>
第 4 步:许可:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
就这样 :)
祝你好运 !
安卓 Q 更新
这是一个较旧的问题,但由于新的文件访问权限/系统,Android Q 有一些变化。 现在不再可能仅将 PDF 文件存储在公共文件夹中。 我通过在我的应用程序的数据/数据的cache
文件夹中创建 PDF 文件的副本解决了这个问题。 这种方法不再需要WRITE_EXTERNAL_STORAGE
权限。
打开 PDF 文件:
fun openPdf(){
// Open the PDF file from raw folder
val inputStream = resources.openRawResource(R.raw.mypdf)
// Copy the file to the cache folder
inputStream.use { inputStream ->
val file = File(cacheDir, "mypdf.pdf")
FileOutputStream(file).use { output ->
val buffer = ByteArray(4 * 1024) // or other buffer size
var read: Int
while (inputStream.read(buffer).also { read = it } != -1) {
output.write(buffer, 0, read)
}
output.flush()
}
}
val cacheFile = File(cacheDir, "mypdf.pdf")
// Get the URI of the cache file from the FileProvider
val uri = FileProvider.getUriForFile(this, "$packageName.provider", cacheFile)
if (uri != null) {
// Create an intent to open the PDF in a third party app
val pdfViewIntent = Intent(Intent.ACTION_VIEW)
pdfViewIntent.data = uri
pdfViewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(pdfViewIntent, "Choos PDF viewer"))
}
}
里面提供的配置provider_paths.xml
访问自己的应用程序的文件之外。 这允许访问cache
文件夹中的所有文件:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path
name="cache-files"
path="/" />
</paths>
在AndroidManifest.xml
添加文件提供程序配置
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
这可以通过只复制文件一次并检查文件是否已经存在并替换它来增强。 由于打开 PDF 不是我的应用程序的重要组成部分,我只是将它保存在缓存文件夹中,并在用户每次打开 PDF 时覆盖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.