Create a pdf on android

Asked

Viewed 370 times

1

I have a byte[] which is a pdf. use the following class to try to convert it.

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_teste);

    byte[] bytes = getIntent().getByteArrayExtra("pdf");

    String fileName = "out.pdf";
    String filePath = Environment.getExternalStorageDirectory().toString();

    try {
        // Create file
        File someFile = new File(filePath, fileName);
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);


        Intent target = new Intent(Intent.ACTION_VIEW);
        target.setDataAndType(Uri.fromFile(someFile), "application/pdf");
        target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        Intent intent = Intent.createChooser(target, "Open File");
        startActivity(intent);
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        Toast.makeText(this, "Não foi possível abrir", Toast.LENGTH_LONG).show();
    }

}

But when I open in pdf reader it says that the file is corrupted or damaged.

  • Navigating through the mobile file manager, you found the created pdf?

  • I can’t find the app folder in the emulator

  • Checks if you have permissions WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE

  • is with the guaranteed permissions

  • I changed the destination folder to sd card, then it says pdf is corrupted

  • It may be Android security permission, try using the following lines of code: String fileName = "fileName.pdf"; File file = new File(Environment.getExternalStorageDirectory(), fileName); perhaps using the Environment for sure

  • @Gaspar did so but at the time of opening says the document is damaged or corrupted

  • I didn’t understand the line byte[] bytes = getIntent().getByteArrayExtra("pdf"); the getIntent() take the current Activity Intent, you may need to pull the Intent from an external method, check this answer

  • @Gaspar this line is right, it takes the byte[] of the previous Activity. I updated the question with the new code

Show 4 more comments

1 answer

3


Solved in a simple way. The Code was practically right, all that was missing was Code for Base64. I added this line after picking up the byte[] from the previous Activity

byte[] decodedString = Base64.decode(bytes, Base64.DEFAULT);
  • 1

    good, thanks for sharing the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.