Search code examples
androidandroid-layoutandroid-wifiandroid-print-framework

How to take printout of my layout using wifi printer?


I am developing Restaurant application. After the order completion, i need to display bill (items price and total amount) in AlertView.

Is it possible to take print out of that AlertView in wifi printer? How to make it?


Solution

  • Yes it is possible to print a layout create a bitmap from the layout and send a intent to the printer app as in the following code

        yourRootLayout.setDrawingCacheEnabled(true);
        yourRootLayout.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        yourRootLayout.buildDrawingCache();
    
        Bitmap dummyImageBitmap = Bitmap.createBitmap(yourRootLayout
                .getDrawingCache());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        dummyImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        byte[] photoArray = out.toByteArray();
        yourRootLayout.setDrawingCacheEnabled(false);
    
        try {
    
            File file = new File(getFilePath());//path to sdcard
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream outPut = new FileOutputStream(file);
            outPut.write(photoArray);
            outPut.flush();
            outPut.close();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("application/pdf");
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            startActivity(intent);
    
    
        } catch (Exception e) {
            throw new Exception("Error generating file", e);
        }
    

    now this will pop a a list of apps you will have to select the printers app that allows printing via wifi