WebView print android java

XML Code in activity_main.xml :

 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   tools:context=".MainActivity">  
   
   <WebView  
     android:id="@+id/webView"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent" />  
   
   <com.google.android.material.floatingactionbutton.FloatingActionButton  
     android:id="@+id/btnPrint"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:layout_alignParentEnd="true"  
     android:layout_alignParentBottom="true"  
     android:layout_marginEnd="20dp"  
     android:layout_marginBottom="20dp"  
     android:src="@drawable/ic_print" />  
   
   
 </RelativeLayout>  

JAVA Code in MainActivity.java :

 public class MainActivity extends AppCompatActivity {  
   
   WebView webView;  
   FloatingActionButton floatingActionButton;  
   
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   
     webView = findViewById(R.id.webView);  
     floatingActionButton = findViewById(R.id.btnPrint);  
   
     webView.setWebChromeClient(new WebChromeClient());  
     webView.setWebViewClient(new WebViewClient());  
     webView.getSettings().setJavaScriptEnabled(true);  
   
     webView.loadUrl("https://www.google.com");  
   
     floatingActionButton.setOnClickListener(v -> {  
       createWebPrint(webView);  
     });  
   
   
   } // onCreate method end here ============  
   
   private void createWebPrint(WebView webView){  
     PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);  
     PrintDocumentAdapter printDocumentAdapter = webView.createPrintDocumentAdapter();  
     String jobName = getString(R.string.app_name) + "Hello";  
     printManager.print(jobName,printDocumentAdapter, new PrintAttributes.Builder().build());  
   }  
   
 } // public class end here ===================  

Internet Permission in AndroidManifest.xml :

   <!-- Internet Permission -->  
   <uses-permission android:name="android.permission.INTERNET"/>  
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>  

Video Tutorial:

Previous Post
No Comment
Add Comment
comment url