android - 我正在使用以下代码创建 pdf 并将其存储在设备上,但不成功
问题描述
public void savePDF(View view) {
//create document object
Document doc = new Document();
//output file path
String outpath= Environment.getExternalStorageDirectory()+"/mypdf.pdf";
try {
//create pdf writer instance
PdfWriter.getInstance(doc, new FileOutputStream(outpath));
//open the document for writing
doc.open();
//add paragraph to the document
doc.add(new Paragraph("bob"));
//close the document
doc.close();
Toast.makeText(this, "Worked", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我正在使用上面的代码创建一个 PDF 文件并将其存储在设备的外部存储中。以下是我的清单的片段:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.mobileappdevelopment">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
按下按钮(运行 savePDF 功能)后,什么也没有发生。没有文件被保存,toast 也没有显示。我在这里做错了吗?
还添加了itext依赖...
implementation 'com.itextpdf:itextg:5.5.10'
解决方案
WRITE_EXTERNAL_STORAGE 从 API 级别 19 开始,读取/写入 Context.getExternalFilesDir(String) 和 Context.getExternalCacheDir() 返回的应用程序特定目录中的文件不需要此权限。
https://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE
推荐阅读
- mysql - 只显示选择 SQL 中的前 5 个字符?
- html - 仅关注特定媒体查询中的链接
- javascript - Ace Editor - 当我按下空格键时自动完成触发
- sql - 如何在不使用子查询的情况下编写此查询?
- google-apps-script - 谷歌表根据日期比较更改标签颜色
- java - GlassFish 5:错误:HTTP 状态 404 - 未找到
- python-3.x - 如何使我的猜词游戏的代码更短?
- arrays - 无法访问数组内的对象数组及其大小
- javascript - 显示元素按下按钮同时隐藏所有其他元素
- twilio - 如果在非工作时间未得到答复,则消息有问题