Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a PDF file to a printer using PrintWriter via Socket connection

I have to print a pdf file using a printer with a specific IP address. I am able to print a specific text but I want to print a file or a html parsed text.

My Code:

try {
    Socket sock = new Socket("192.168.0.131", 9100);
    PrintWriter oStream = new PrintWriter(sock.getOutputStream());
    oStream.println("HI,test from Android Device");
    oStream.println("\n\n\n");
    oStream.close();
    sock.close();
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Many people are suggesting about PDLs but how to convert the pdf to PDL?

like image 248
Vishwajit Palankar Avatar asked Sep 19 '16 10:09

Vishwajit Palankar


2 Answers

Data sent to a printer must be in Page Description Languages(PDL's), languages printer understand. Here you can find some basic understanding o those. ASCII string is understood by most of the printers, that is why you are able to print the string. But when it comes to complex document formats like(PDF's, Excels, HTML page, etc), you have to convert the document into one of the PDLs. The most common PDLs that i have worked with are PostScript(PS) and PCL(Printer Command Language).

Now in order to print a PDF with exact formatting(to which you require a solution), you have to convert the PDF document to PCl or Postscript and then send that PCL or postscript data to the printer. You can use ghostscript to convert your PDF to PS or PCL.

I have not done exactly what you are trying to do, but i think what i have explained above is the start for you.

I would be highly interested to know if you are able to do it. Let me know.

like image 61
Zaartha Avatar answered Sep 29 '22 14:09

Zaartha


You need to use PDFBox library which is also available for Android.

You can use it to get the PDF text and then use it for your purpose -

A java sample -

import java.io.File;
import java.io.IOException; 
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class myProgram{

    public static void main(String[] args)
    try {
        PDDocument document = null;
        document = PDDocument.load(new File("my_file.pdf"));
        document.getClass();
        if (!document.isEncrypted()) {
        PDFTextStripperByArea stripper = new PDFTextStripperByArea();
        stripper.setSortByPosition(true);
        PDFTextStripper Tstripper = new PDFTextStripper();
        String st = Tstripper.getText(document);
        System.out.println("Text:" + st);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

PdfBox-For-Android

Or use MuPDF

like image 39
Techidiot Avatar answered Sep 29 '22 14:09

Techidiot