简体   繁体   中英

Android: Export PDF using file path

I am working on an application that can receive PDF files. The app currently save the received file as a byte[] in the internal app directory and I am then given access to it's localpath.

I now want to be able to take that data and convert it to a PDF file before saving it onto external memory.

I am able to do that using the code below but when I try to access it, I am told that it is of an invalid format. Any ideas how to fix this?

// ---------- EXPORT IMAGE TASK ----------
private class ExportPDF extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... voids) {
        String pathToExternalStorage = Environment.getExternalStorageDirectory().toString();
        File appDirectory = new File(pathToExternalStorage + "/" + getString(R.string.app_name));
        if (!appDirectory.exists()) {
            appDirectory.mkdirs();
        }

        File imageFile = new File(appDirectory.getAbsolutePath() + "/PDF_" + filename.hashCode() + ".pdf");
        if (!imageFile.exists()) {
            try {
                FileOutputStream fos = new FileOutputStream(imageFile.getPath());
                fos.write(new File(localPath).toString().getBytes());
                fos.close();
            } catch (FileNotFoundException e) {
                Log.e(TAG, e.toString());
            } catch (IOException e) {
                Log.e(TAG, e.toString());
            }
        }
        return imageFile.getAbsolutePath();
    }

    @Override
    protected void onPostExecute(String aString) {
        exportPDF(aString);
    }
}

private void exportPDF(String filePath) {
    Uri imageUri = Uri.parse(filePath);
    Intent sharingIntent = new Intent(Intent.ACTION_VIEW);
    sharingIntent.setDataAndType(imageUri, "application/pdf");
    startActivity(sharingIntent);
}
fos.write(new File(localPath).toString().getBytes());

What this code does, step by step:

  • Creates a File object based on some value ( new File(localPath) )
  • Creates a string representation of the path to that file ( new File(localPath).toString() )
  • Creates a byte[] of the string representation of the path to that file ( new File(localPath).toString().getBytes() )
  • Writes that byte[] to the FileOutputStream

The result is that the file identified by imageFile contains the path to some other file. This is not a valid PDF.

My guess is that you are trying to copy the contents of localPath to imageFile , and this code does not do that.

A simpler, faster, and less space-intensive solution is to use FileProvider to serve the PDF to the PDF viewer directly from localPath , rather than making a second copy of the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM