【发布时间】:2021-05-21 10:55:24
【问题描述】:
社区问候
我正在使用 ITEXT 库生成 PDF 报告。
'com.itextpdf:itextpdf:5.0.6'
我就是这么干的
Document document = new Document();
fileName = FileName + Common.getCurrentDateTime() + ".pdf";
fileName1 = FileName + Common.getCurrentDateTime() + ".pdf";
String dest = context.getExternalFilesDir(null) + "/RTS";
File dir = new File(dest);
if (!dir.exists())
dir.mkdirs();
try {
File file = new File(dest, fileName);
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file, false);
//FileOutputStream fOut = new FileOutputStream(file);
//PdfWriter.getInstance(document, new FileOutputStream(dest));
PdfWriter.getInstance(document, fOut);
// PdfWriter.getInstance(document, fOut);
} catch (DocumentException e) {
e.printStackTrace();
Log.v("PdfError", e.toString());
// dialog.dismiss();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.v("PdfError", e.toString());
// dialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
请注意,此解决方案在 Android (10)Q 之前都可以正常工作。 我已经经历了许多解决方案,并且花了将近一周的时间来解决这个问题。 我正在模拟器上测试 Android (11)R 场景。
感谢对此问题发表评论的人,现在 PDF 已创建
document.close();
// File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/example.pdf");
File file = new File(dest+"/"+fileName1);
// File file = new File("/" +"Internal storage"+ "/" +"RTS" +"/" + fileName);
if (!file.exists()) {
file.mkdir();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
((Activity) context).startActivity(intent);
listsOfListReportModelList.clear();
现在无法像这样打开文件。 说要缩短名字。
【问题讨论】:
-
Android 11 中对外部存储的访问已更改。请查看此guide
-
停止写信给
Environment.getExternalStorageDirectory()。您不再具有对该位置的写入权限。在Context上使用getExternalFilesDir()。或者,使用ACTION_CREATE_DOCUMENT让用户选择您应该将用户的 PDF 放在用户设备(或用户的云存储)上的哪个位置。 -
感谢您的指导,我正在采纳这些建议。
-
谢谢@AlexanderHoffmann 现在文件正在生成,但无法通过它打开。
-
谢谢@CommonsWare 现在文件正在生成但无法通过此打开它