Home > database >  How to Access the file associated with PrintJob Object in an Android PrintService?
How to Access the file associated with PrintJob Object in an Android PrintService?

Time:05-27

I've followed A lot of the code in this PrintService example repository: Zaki50 PrintService. The only thing I'm trying to do different is to get the bytes from the file associated with PrintJob. Now I have the FileDescriptor, but don't know how to use it to get the actual file data in anyway! Any help would be immensely appreciated.

CodePudding user response:

Ok, Here's the answer in code:

final PrintJobInfo info = printJob.getInfo();
final File file = new File(getFilesDir(), info.getLabel());


InputStream in = null;
FileOutputStream out = null;

try {
   in = new 
   FileInputStream(printJob.getDocument().getData().getFileDescriptor());
   out = new FileOutputStream(file);

   byte[] buffer = new byte[1024];
   int read;
   while ((read = in.read(buffer)) != -1) {
          out.write(buffer, 0, read);
   }
   in.close();

   out.flush();
   out.close();

} catch (IOException ioe) {

}

FileChannel channel = null;
byte[] fileBytes = null;
try {
       RandomAccessFile raf = new RandomAccessFile(file, "r");
       channel = raf.getChannel();
       ByteBuffer bb = ByteBuffer.NEW(channel.map(
             FileChannel.MapMode.READ_ONLY, 0, channel.size()));
       fileBytes  = new byte[bb.remaining()];
       bb.get(fileBytes , 0, fileBytes .length);

} catch (FileNotFoundException e) {
       e.printStackTrace();
} catch (IOException e) {
       e.printStackTrace();
}

The content of the fileBytes array is the actual bytes of the printed file.

  • Related