Luc*_*lla 4 pdf android android-intent android-external-storage
我正在尝试从具有以下布局的布局生成 PDF:
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(2480, 3508, 0).create();
PdfDocument.Page page = document.startPage(pageInfo);
linearview.draw(page.getCanvas());
document.finishPage(page);
OutputStream outStream;
File file = new File(getExternalFilesDir(null), "pedido.PDF");
try {
outStream = new FileOutputStream(file);
document.writeTo(outStream);
document.close();
outStream.flush();
outStream.close();
Log.d(TAG, "pdf saved to " + getExternalFilesDir(null));
Intent intent = new Intent(Intent.ACTION_VIEW);
File myPDF = new File(getExternalFilesDir(null), "pedido.PDF");
Uri uri = FileProvider.getUriForFile(OrderActivity.this, BuildConfig.APPLICATION_ID + ".provider", myPDF);
Log.d(TAG, "openPDF: intent with uri: " + uri);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, e.toString());
}
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,我得到一个由默认 PDF 开启器打开的空白 PDF。我不知道它是否这样做,因为它没有找到 PDF 文件,但我想这是问题所在,因为 PDF 生成正确。如果我使用文件搜索器打开文件,/storage/emulated/0/Android/data/com.lucaszanella.venko/files/pedido.PDF我会正常看到 PDF。
这是我得到的输出
D/OrderActivity: pdf saved to /storage/emulated/0/Android/data/com.lucaszanella.venko/files
D/OrderActivity: openPDF: intent with uri: content://com.lucaszanella.venko.provider/external_files/Android/data/com.lucaszanella.venko/files/pedido.PDF
Run Code Online (Sandbox Code Playgroud)
如您所见,pdf 已保存到/storage文件夹中,但意图尝试从/external_files. 这可能是问题所在,但我想我所做的一切都很好。
更新:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
</paths>
Run Code Online (Sandbox Code Playgroud)
这就是所缺少的:
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
即使我不需要从外部目录读取的权限。