0

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.

  • I've found this [repo](https://github.com/serrexlabs/thermal-printer-service) that can make a `Bitmap` file out of the `PrintJob`data sent to its `PrintService`. All I did was just migrate it to AndroidX and it worked beautifully. kudos to the guys at [SERrex Labs](https://github.com/serrexlabs). I will only take sometime to make sure that this solution would solve all my issues, and then I will make it into an answer. – Ahmed Almahdie May 26 '22 at 11:12

1 Answers1

0

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.