2

I can print a receipt (byte[] printer format) via a thermal printer, like this :

// Print a receipt
OutputStream outputStream = mPrinterSocket.getOutputStream();
for (byte[] packet : content)
    outputStream.write(packet);
outputStream.flush();

But I can not manage to save a receipt (byte[] printer format) into a file (pdf or image). I tried :

// Save a receipt
try (OutputStream outputStream = new FileOutputStream(filePath)) {
    for (byte[] packet : content) {
        outputStream.write(packet);
        outputStream.flush();
    }
} catch (Exception exception) {
    exception.printStackTrace();
}

But it returned a corrupted file, containing:

䀛琛ᬐšℝ䴑ਊℝ䴀‬੍੍ㄊ⼵㔰ㄯ‹ㄱ㈺‱†††††慔汢⁥਱䔛ਁ′潂獩潳獮†††††††††††ᬊE‱潃慣†††††††††††⸲〲ᬊE‱慆瑮⁡††††††††††⸲〲ⴊⴭⴭⴭⴭⴭⴭⴭⴭⴭⴭⴭⴭⴭⴭⴭਭ䔛吁呏䱁†††††††††䔠剕㐠㐮ਰਊ䔛䴀牥楣‬⃠楢湥⁴ਡਊਊᴊV

Is the process to "print a byte[] to file" different from "save a byte[] to file"? For example, I use the character {0x1b, 0x45, 0x01} to put a text in bold, is this a problem? I would like to avoid reformatting everything or using an external library.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Greelings
  • 4,964
  • 7
  • 34
  • 70
  • 1
    I'd wrap the `FileOutputStream` into a `BufferedOutputStream`, instead of using a plain FOS. Also, you don't need to `flush()` after each packet, just outside of the loop - as in your first example. – gaborsch May 15 '19 at 09:31
  • @gaborsch Thank you, it works much better :) – Greelings May 15 '19 at 09:57
  • If it solved your issue, I'll post it as an answer... – gaborsch May 15 '19 at 10:00
  • here what is "mPrinterSocket" .For some 3rd party libraries (I think like ur printer library) they are accepting data in normal format and process into their properietary format to print .So please given more details what you are tyring in the mPrinterSocket with the printer and how to you save the file ,etc – SIVAKUMAR.J May 15 '19 at 10:02

2 Answers2

1

I'd wrap the FileOutputStream into a BufferedOutputStream, instead of using a plain FOS. When reading from or writing to a file it is always a good practice to use a buffer.

Also, you don't need to flush() after each packet, just outside of the loop - as in your first example. This also improves performance.

gaborsch
  • 15,408
  • 6
  • 37
  • 48
0

You can use the itext library for android to create PDF file and save it. For more details Read Here

Jauhar xlr
  • 117
  • 2
  • 7