📜  如何在Android中将WebView转换为PDF?

📅  最后修改于: 2021-05-13 17:35:03             🧑  作者: Mango

有时需要将一些文章以PDF文件的形式保存在互联网上。这样做有很多方法,一个人可以使用任何浏览器扩展程序或任何软件或网站来这样做。但是,为了在android应用中实现此功能,不能依赖其他软件或网站来实现。因此,要在android应用中实现此惊人功能,请遵循本教程。下面给出了一个示例GIF,以了解我们将在本文中做些什么

网页浏览到pdf

将WebView转换为PDF的步骤

步骤1:建立新专案

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,尽管我们将使用Java语言来实现该项目,但请选择Java作为编程语言。

第2步:在进入编码部分之前,请先执行一些预任务

  • 转到应用程序->清单-> AndroidManifest.xml部分,并允许“ Internet权限”。

步骤3:设计UI

activity_main.xml文件中,有一个WebView 用于加载网站的按钮和一个用于将加载的网页保存为PDF文件的按钮。这是activity_main.xml文件的代码。

XML


  
  
  
  
  
  


Java
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
      
    // creating object of WebView
    WebView printWeb;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Initializing the WebView
        final WebView webView = (WebView) findViewById(R.id.webViewMain);
  
        // Initializing the Button
        Button savePdfBtn = (Button) findViewById(R.id.savePdfBtn);
  
        // Setting we View Client
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // initializing the printWeb Object
                printWeb = webView;
            }
        });
  
        // loading the URL
        webView.loadUrl("https://www.google.com");
  
        // setting clickListener for Save Pdf Button
        savePdfBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (printWeb != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        // Calling createWebPrintJob()
                        PrintTheWebPage(printWeb);
                    } else {
                        // Showing Toast message to user
                        Toast.makeText(MainActivity.this, "Not available for device below Android LOLLIPOP", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // Showing Toast message to user
                    Toast.makeText(MainActivity.this, "WebPage not fully loaded", Toast.LENGTH_SHORT).show();
                }
            }
        });
  
    }
  
    // object of print job
    PrintJob printJob;
  
    // a boolean to check the status of printing
    boolean printBtnPressed = false;
  
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void PrintTheWebPage(WebView webView) {
          
        // set printBtnPressed true
        printBtnPressed = true;
  
        // Creating  PrintManager instance
        PrintManager printManager = (PrintManager) this
                .getSystemService(Context.PRINT_SERVICE);
  
        // setting the name of job
        String jobName = getString(R.string.app_name) + " webpage" + webView.getUrl();
  
        // Creating  PrintDocumentAdapter instance
        PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(jobName);
  
        // Create a print job with name and adapter instance
        assert printManager != null;
        printJob = printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());
    }
  
    @Override
    protected void onResume() {
        super.onResume();
        if (printJob != null && printBtnPressed) {
            if (printJob.isCompleted()) {
                // Showing Toast Message
                Toast.makeText(this, "Completed", Toast.LENGTH_SHORT).show();
            } else if (printJob.isStarted()) {
                // Showing Toast Message
                Toast.makeText(this, "isStarted", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isBlocked()) {
                // Showing Toast Message
                Toast.makeText(this, "isBlocked", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isCancelled()) {
                // Showing Toast Message
                Toast.makeText(this, "isCancelled", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isFailed()) {
                // Showing Toast Message
                Toast.makeText(this, "isFailed", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isQueued()) {
                // Showing Toast Message
                Toast.makeText(this, "isQueued", Toast.LENGTH_SHORT).show();
  
            }
            // set printBtnPressed false
            printBtnPressed = false;
        }
    }
}


步骤4:使用MainActivity。 Java文件

  • 打开MainActivity。类中有Java文件,首先创建WebView类的对象。
  • 现在,在onCreate()方法中,使用activity_main.xml文件中给出的各自的ID初始化WebView和Button。
  • 现在setWebViewClient在W ebView的和内部的onPageFinished()初始化与web视图printWeb对象。
  • 现在加载URL
  • 接下来,调用稍后在onClick()内部创建的createWebPrintJob()方法, 并显示相应的Toast消息。
  • 创建一个PrintJob对象,并创建一个布尔printBtnPressed ,用于检查打印网页的状态。
  • 现在在MainActivity中创建一个PrintTheWebPage()方法。 Java类,下面是PrintTheWebPage()方法的完整代码。
  • 接下来,在onResume()方法中显示“保存PDF”的状态,并检查打印状态。以下是onResume()方法的完整代码。
  • 以下是MainActivity的完整代码。 Java文件。

Java

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
      
    // creating object of WebView
    WebView printWeb;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Initializing the WebView
        final WebView webView = (WebView) findViewById(R.id.webViewMain);
  
        // Initializing the Button
        Button savePdfBtn = (Button) findViewById(R.id.savePdfBtn);
  
        // Setting we View Client
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // initializing the printWeb Object
                printWeb = webView;
            }
        });
  
        // loading the URL
        webView.loadUrl("https://www.google.com");
  
        // setting clickListener for Save Pdf Button
        savePdfBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (printWeb != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        // Calling createWebPrintJob()
                        PrintTheWebPage(printWeb);
                    } else {
                        // Showing Toast message to user
                        Toast.makeText(MainActivity.this, "Not available for device below Android LOLLIPOP", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    // Showing Toast message to user
                    Toast.makeText(MainActivity.this, "WebPage not fully loaded", Toast.LENGTH_SHORT).show();
                }
            }
        });
  
    }
  
    // object of print job
    PrintJob printJob;
  
    // a boolean to check the status of printing
    boolean printBtnPressed = false;
  
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void PrintTheWebPage(WebView webView) {
          
        // set printBtnPressed true
        printBtnPressed = true;
  
        // Creating  PrintManager instance
        PrintManager printManager = (PrintManager) this
                .getSystemService(Context.PRINT_SERVICE);
  
        // setting the name of job
        String jobName = getString(R.string.app_name) + " webpage" + webView.getUrl();
  
        // Creating  PrintDocumentAdapter instance
        PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(jobName);
  
        // Create a print job with name and adapter instance
        assert printManager != null;
        printJob = printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());
    }
  
    @Override
    protected void onResume() {
        super.onResume();
        if (printJob != null && printBtnPressed) {
            if (printJob.isCompleted()) {
                // Showing Toast Message
                Toast.makeText(this, "Completed", Toast.LENGTH_SHORT).show();
            } else if (printJob.isStarted()) {
                // Showing Toast Message
                Toast.makeText(this, "isStarted", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isBlocked()) {
                // Showing Toast Message
                Toast.makeText(this, "isBlocked", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isCancelled()) {
                // Showing Toast Message
                Toast.makeText(this, "isCancelled", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isFailed()) {
                // Showing Toast Message
                Toast.makeText(this, "isFailed", Toast.LENGTH_SHORT).show();
  
            } else if (printJob.isQueued()) {
                // Showing Toast Message
                Toast.makeText(this, "isQueued", Toast.LENGTH_SHORT).show();
  
            }
            // set printBtnPressed false
            printBtnPressed = false;
        }
    }
}

输出:在模拟器上运行

资源:

  • 从github下载完整项目
  • 下载apk文件
想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!