PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

[FIXED] How to Access the file associated with PrintJob Object in an Android PrintService?

 September 15, 2022     android, file, inputstream, printing, thermal-printer     No comments   

Issue

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.


Solution

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.



Answered By - Ahmed Almahdie
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing