我正在尝试将PDF保存为Android上的文件,但无法正常工作。我读到Environment.getExternalStorageDirectory()
已被弃用,因此我尝试使用getExternalFilesDir()
这里是代码:
private fun createPDF() {
var pdfDoc = PdfDocument()
var myPaint = Paint()
//page 1
var myPageInfo = PdfDocument.PageInfo.Builder(1452, 589, 1).create()
val myPage = pdfDoc.startPage(myPageInfo)
val canvas = myPage.canvas
canvas.drawBitmap(bmp, 40.0F, 50.0F, myPaint)
//finish
pdfDoc.finishPage(myPage)
//save
val file = File(getExternalFilesDir(null)!!.absolutePath,"test.pdf")
try {
pdfDoc.writeTo(FileOutputStream(file))
println("pdf saved")
} catch (e: IOException) {
e.printStackTrace()
}
pdfDoc.close()
}
此外,我也不完全确定,但这应该出现在“文件”上吗?预先感谢!
您正在尝试保存到外部存储,因此您试图保存到外部SD卡。如果电话没有,您将不会保存它。您可以尝试使用getFilesDir()而不是getExternalFilesDir保存它。如果这仍然不能解决问题,因为您不应该将getFilesDir或getExternalFilesDir用于文档文件,而是使用Storage Access Framework https://developer.android.com/training/data-storage。您可以执行以下操作:
// Request code for creating a PDF document.
private static final int CREATE_FILE = 1;
private void createFile(Uri pickerInitialUri) {
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, "invoice.pdf");
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when your app creates the document.
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, CREATE_FILE);
}
请参见https://developer.android.com/training/data-storage/shared/documents-files