Search code examples
javaandroidpdfzebra-printers

Print PDF as byte array in JAVA


I need to print a pdf file for my printer. With this code I have converted my pdf to bytearray, but I am stuck and not know how to send it to the printer. Someone can help me?

    File file = new File("java.pdf");

    FileInputStream fis = new FileInputStream(file);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];

    try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum); //no doubt here is 0
            //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
            System.out.println("read " + readNum + " bytes,");
        }
    } catch (IOException ex) {
        System.out.println("ERROR!");
    }
    byte[] bytes = bos.toByteArray();

Thank you in advance.


Solution

  • Another approach is to send the pdf file using intent and here is an example

    Sample code :

    Intent prnIntent = new Intent(Intent.ACTION_SEND);
    prnIntent.putExtra(Intent.EXTRA_STREAM, uri);
    
    prnIntent.setType("application/pdf");
    
    
    startActivity(Intent.createChooser(prnIntent , "Send pdf using:"));
    

    With this approach there is no need to use buffers but you send pdf file directly to printer!