1

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.

2
  • See my answer here. The job can be done with sockets Commented Mar 24, 2014 at 11:16
  • Thank you for your answer, but there are other possibility like not be sockets? Commented Mar 24, 2014 at 11:25

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, but I have converted my pdf to bytearray, in your example, where I send my bytearray to printer?
With this example you send a pdf file. So, you have to do your work first as bytearray then convert to pdf file and then you send it to printer with this solution.
How will an Android approach help in a standard java application? How do Intents fit in here?
You are right Christian it's an android solution only but I thought that this question was for android. So, the tag android I think is missing from the question.
2

Steps to follow:

  1. Find default printer service in your environment.
  2. Define the document flavor, for PDF, to use for print.
  3. Prepare a document to print from byte array.
  4. Execute the print job.

Example code snippet:

byte[] bytes = bos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream( bytes );

// First identify the default print service on the system  
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();  

// prepare the flvaor you are intended to print  
DocFlavor docFlavor = DocFlavor.BYTE_ARRAY.PDF;  

// prepare the print job
DocPrintJob printJob = printService.createPrintJob();  

// prepare the document, with default attributes, ready to print  
Doc docToPrint = new SimpleDoc( bais, docFlavor, null );  

// now send the doc to print job, with no attributes to print
printJob.print( docToPrint, null );

5 Comments

It throws a "data is not of declared type" exception
@whizzzkey: ??? which data??? where is it???? post your query with proper details on where you are struck with...
"which data???" - just simple pdf doc, "where is it???? " - on line Doc docToPrint = new SimpleDoc( bais, docFlavor, null );. I do everything as you posted, and I have a similar code like TS for getting a bytearray from my pdf file.
As I suggested, you better post your code, exception stacktrace with your query as a new question. Just through comments it is hard to identify the problem and give a solution.
This code will always throws an exception. you should pass the byte array instead of IS to the SimpleDoc obj (No need of IS to be more clear). Or else you should change the doc flavor to DocFlavor.INPUT_STREAM in order to work.
2

Using a ByteArrayInputStream throws java.lang.IllegalArgumentException, but a regular byte array worked for me. Modifying the example of Ravinder Reddy:

    // Get default print service
    PrintService printService = PrintServiceLookup.lookupDefaultPrintService();

    // Create a print job
    DocPrintJob printJob = printService.createPrintJob();

    // Optional fancy listener
    printJob.addPrintJobListener(new PrintJobAdapter() {
        @Override
        public void printJobCompleted(PrintJobEvent pje) {
            System.out.println("PDF printing completed");
            super.printJobCompleted(pje);
        }

        @Override
        public void printJobFailed(PrintJobEvent pje) {
            System.out.println("PDF printing failed");
            super.printJobFailed(pje);
        }
    });

    // Check the PDF file and get a byte array
    File pdfFile = new File("path/to/pdf");
    if (pdfFile.exists() && pdfFile.isFile()) {
        byte[] PDFByteArray = Files.readAllBytes(FileSystems.getDefault().getPath(pdfFile.getAbsolutePath()));

        // Create a doc and print it
        Doc doc = new SimpleDoc(PDFByteArray, DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
        printJob.print(doc, null);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.