Updated 22 April 2017
In this blog we will learn on how to print content from your application by connecting with your wifi printer.
Android community provides some APIs that helps us in printing content from our application.They have classified the printing into three categories :
You can find more details regarding these categories over here : https://developer.android.com/training/printing/index.html
Here, we will discuss about how to print the html content as i needed to print only that.
You can try the other two yourself.
APPROACH :
Implementing this is not at all difficault if you follow the steps in the same manner.
Now lets have a look at the code to have a clear idea of how to print the html content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
WebView webView = new WebView(mContext); webView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { return false; } @Override public void onPageFinished(WebView view, String url) { createWebPrintJob(view); mWebView = null; } }); String myHtml = getHtmlContent(); webView.loadDataWithBaseURL(null, myHtml, "text/HTML", "UTF-8", null); |
This is the main piece of code . Now lets have a look at the function createWebPrintJob(view)
1 2 3 4 5 6 7 8 9 |
private void createWebPrintJob(WebView webView) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE); PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter("MyDocument"); printManager.print(" My Print Job", printAdapter, new PrintAttributes.Builder().build()); } else { // SHOW MESSAGE or UPDATE UI } } |
And finally lets have a look at the function getHtmlContent() :
1 2 3 4 5 6 7 |
public String getHtmlContent(){ return "<html>" +"<head>" +"<title> My Test Document </title></head>" +"<body><p>Test content 1</p> " +"<p>Test content 2</p> +"</body></html>"; } |
You can change the content of the getHtmlContent as per your need.
And it is done.
But keep in mind that your Printer and mobile should be on the same wifi network.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
4 comments
If there are multiple printers that can be connected throught his code, the first window that will appear should automatically ask for the printer selection and then you can select the printer from the list of printers.
If due to any reason this is not working please share a snippet of what exactly are you trying and I will try to help you.
But As far as I know, you can try putting your content in a file and then from UIActivityViewController you can easily print the same.
iOS already allows you to print the PDF files saved over your phone.
So, you can easily take help from that too.