Print Button from Asp.net to Android Webview RRS feed

  • Question

  • User-2131774580 posted


         I have web mobile application, at the button in aspx page i put the below code to print the page, it is working fine in browsers (all)  but when i put my application inside webview in android it not working (not response after click)

    <div id="options">

    <input id="printpagebutton" type="button" class="printToprinter" value="PRINT" onclick="printpage()" />


    function printpage() {

        //Get the print button and put it into a variable
        var printButton = document.getElementById("printpagebutton");

        //Set the button visibility to 'hidden' 
        printButton.style.visibility = 'hidden';

        //Print the page content

        //Restore button visibility
        printButton.style.visibility = 'visible';


    The bellow link explicitly says "You cannot use JavaScript in a HTML document to trigger printing", 
    and provides an example of how to use the Java API. Chrome for Android (at least Beta) supports window.print().

    I want to print from my aspx page depend on id so from java itself cannot be done How to add print button to open printer dialogue, i used driver.google. But it return blanc after press print

    i did all the above code and it is failed inside Webview, it is working fine through browser :

            HttpContext.Current.Response.Expires = 0;
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment;FileName="+outletid+ "Check.pdf");
    HttpContext.Current.Response.ContentType = "application/force-download";//Application/pdf


     Process process = new System.Diagnostics.Process();
      process.StartInfo.FileName = "chrome";
      process.StartInfo.Arguments = openurl + " --new-window"; 


      string UrlForAndroid = "http://drive.google.com/viewerng/viewer?embedded=true&url="+openurl;

    this.Page.Response.Redirect(UrlForAndroid, true);

    this option open the pdf, but when i try to print it return white page

    Any help

    Wednesday, February 26, 2020 9:41 AM

All replies

  • User-719153870 posted

    Hi ikrami2000,

    No offence, but the descripton of your issue is little confusing.

    You want to print your aspx page in your Android Webview but it always return white page?

    Is it possible that your webview not able to access the aspx page like in How to access .aspx pages in android WebView?.

    Anyway, can you provide the current code of your app that related to "print in Android Webview" and paste it code area which you can click the "{;}" to "Insert/Edit code sample" .

    And a specific and clear description of your current issue.

    Best Regard,

    Yang Shen

    Thursday, February 27, 2020 5:56 AM
  • User-2131774580 posted

    Sorry for confusing you.

    i have Web Mobile application c# , i put it inside android webview.

    when i run it in browser working fine, but when i run it from android app it is not working.
    First the below is the code which i create pdf from aspx  which working fine in Browser but from android app is not working:

    System.Web.HttpContext.Current.Session["CheckID"]= this.ID0.Text;
    string outletid = System.Web.HttpContext.Current.Session["Outlet_Session"].ToString();			
    string URL_Host = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
    string url = URL_Host+"/Orders/Print-Order-Mobile.aspx?Orders="+this.ID0.Text;
    	url = new Uri(url).AbsoluteUri;			
    	var htmlContent = String.Format("<body>Hello world: {0}</body>", DateTime.Now);
    	var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
    	var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);		
    	string output_path_pdf = HttpContext.Current.Server.MapPath("~/PDF/" +outletid+ "Check.pdf");
    	htmlToPdf.GeneratePdfFromFile(url, null, output_path_pdf);
    			string openurl = URL_Host + ("/PDF") + ("/"+outletid+"Check.pdf");
             HttpContext.Current.Response.Expires = 0;
             HttpContext.Current.Response.Buffer = true;
             HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment;FileName="+outletid+ "Check.pdf");

    The below is MainActivity.java   (by the way i don't have any knowledge about java i just copy and past)

    package com.hynoworld.www.BizPOS;
    import android.Manifest;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.content.res.Configuration;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.content.Context;
    import android.support.annotation.NonNull;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    //import android.support.app.AppCompatActivity;
    import android.util.Log;
    import android.view.KeyEvent;
    import android.view.View;
    import android.webkit.ValueCallback;
    import android.webkit.WebChromeClient;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.Toast;
    import java.io.File;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class MainActivity extends Activity{
        /*-- CUSTOMIZE --*/
        /*-- you can customize these options for your convenience --*/
        private static String webview_url   = "http://MyURL";    // web address or local file location you want to open in webview
        private static String file_type     = "image/*";    // file types to be allowed for upload
        private boolean multiple_files      = true;         // allowing multiple file upload
        private Context context;
        /*-- MAIN VARIABLES --*/
        WebView webView;
        private static final String TAG = MainActivity.class.getSimpleName();
        private String cam_file_data = null;        // for storing camera file information
        private ValueCallback<Uri> file_data;       // data/header received after file selection
        private ValueCallback<Uri[]> file_path;     // received file(s) temp. location
        private final static int file_req_code = 1;
        protected void onActivityResult(int requestCode, int resultCode, Intent intent){
            super.onActivityResult(requestCode, resultCode, intent);
            if(Build.VERSION.SDK_INT >= 21){
                Uri[] results = null;
                /*-- if file request cancelled; exited camera. we need to send null value to make future attempts workable --*/
                if (resultCode == Activity.RESULT_CANCELED) {
                    if (requestCode == file_req_code) {
                /*-- continue if response is positive --*/
                if(resultCode== Activity.RESULT_OK){
                    if(requestCode == file_req_code){
                        if(null == file_path){
                        if(null == intent.getClipData() && null == intent.getDataString() && null != cam_file_data) {
                            results = new Uri[]{Uri.parse(cam_file_data)};
                            if (null != intent.getClipData()) { // checking if multiple files selected or not
                                final int numSelectedFiles = intent.getClipData().getItemCount();
                                results = new Uri[numSelectedFiles];
                                for (int i = 0; i < intent.getClipData().getItemCount(); i++) {
                                    results[i] = intent.getClipData().getItemAt(i).getUri();
                            } else {
                                results = new Uri[]{Uri.parse(intent.getDataString())};
                file_path = null;
                if(requestCode == file_req_code){
                    if(null == file_data) return;
                    Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                    file_data = null;
        @SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
        protected void onCreate(Bundle savedInstanceState){
            webView = (WebView) findViewById(R.id.webViewISD);
            assert webView != null;
            WebSettings webSettings = webView.getSettings();
            webView.setWebViewClient(new MainActivity.Callback());
            Context context = this; // or ActivityNotification.this
            if(Build.VERSION.SDK_INT >= 21){
                webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            }else if(Build.VERSION.SDK_INT >= 19){
                webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            }else {
                webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            webView.setWebViewClient(new Callback());
            webView.setWebChromeClient(new WebChromeClient() {
                /*-- openFileChooser is not a public Android API and has never been part of the SDK. --*/
                /*-- handling input[type="file"] requests for android API 16+ --*/
                public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                    file_data = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    if (multiple_files && Build.VERSION.SDK_INT >= 18) {
                        i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    startActivityForResult(Intent.createChooser(i, "File Chooser"), file_req_code);
                /*-- handling input[type="file"] requests for android API 21+ --*/
                public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                    if(file_permission() && Build.VERSION.SDK_INT >= 21) {
                        file_path = filePathCallback;
                        Intent takePictureIntent = null;
                        Intent takeVideoIntent = null;
                        boolean includeVideo = false;
                        boolean includePhoto = false;
                        /*-- checking the accept parameter to determine which intent(s) to include --*/
                        for (String acceptTypes : fileChooserParams.getAcceptTypes()) {
                            String[] splitTypes = acceptTypes.split(", ?+"); // although it's an array, it still seems to be the whole value; split it out into chunks so that we can detect multiple values
                            for (String acceptType : splitTypes) {
                                switch (acceptType) {
                                    case "*/*":
                                        includePhoto = true;
                                        includeVideo = true;
                                        break paramCheck;
                                    case "image/*":
                                        includePhoto = true;
                                    case "video/*":
                                        includeVideo = true;
                        if (fileChooserParams.getAcceptTypes().length == 0) {   //no `accept` parameter was specified, allow both photo and video
                            includePhoto = true;
                            includeVideo = true;
                        if (includePhoto) {
                            takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                                File photoFile = null;
                                try {
                                    photoFile = create_image();
                                    takePictureIntent.putExtra("PhotoPath", cam_file_data);
                                } catch (IOException ex) {
                                    Log.e(TAG, "Image file creation failed", ex);
                                if (photoFile != null) {
                                    cam_file_data = "file:" + photoFile.getAbsolutePath();
                                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                                } else {
                                    takePictureIntent = null;
                        if (includeVideo) {
                            takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                            if (takeVideoIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                                File videoFile = null;
                                try {
                                    videoFile = create_video();
                                } catch (IOException ex) {
                                    Log.e(TAG, "Video file creation failed", ex);
                                if (videoFile != null) {
                                    cam_file_data = "file:" + videoFile.getAbsolutePath();
                                    takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
                                } else {
                                    takeVideoIntent = null;
                        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                        if (multiple_files) {
                            contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                        Intent[] intentArray;
                        if (takePictureIntent != null && takeVideoIntent != null) {
                            intentArray = new Intent[]{takePictureIntent, takeVideoIntent};
                        } else if (takePictureIntent != null) {
                            intentArray = new Intent[]{takePictureIntent};
                        } else if (takeVideoIntent != null) {
                            intentArray = new Intent[]{takeVideoIntent};
                        } else {
                            intentArray = new Intent[0];
                        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                        chooserIntent.putExtra(Intent.EXTRA_TITLE, "File chooser");
                        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                        startActivityForResult(chooserIntent, file_req_code);
                        return true;
                    } else {
                        return false;
        /*-- callback reporting if error occurs --*/
        public class Callback extends WebViewClient{
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
                Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
        /*-- checking and asking for required file permissions --*/
        public boolean file_permission(){
            if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
                return false;
                return true;
        /*-- creating new image file here --*/
        private File create_image() throws IOException{
            @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "img_"+timeStamp+"_";
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            return File.createTempFile(imageFileName,".jpg",storageDir);
        /*-- creating new video file here --*/
        private File create_video() throws IOException {
            String file_name    = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
            String new_name     = "file_"+file_name+"_";
            File sd_directory   = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            return File.createTempFile(new_name, ".3gp", sd_directory);
        /*-- back/down key handling --*/
        public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){
            if(event.getAction() == KeyEvent.ACTION_DOWN){
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    if (webView.canGoBack()) {
                    } else {
                    return true;
            return super.onKeyDown(keyCode, event);
        public void onConfigurationChanged(Configuration newConfig){

    Webview is open the application and i do the print when i finish the order

    Thursday, February 27, 2020 2:02 PM