Hardik Joshi
Hardik Joshi

Reputation: 9507

How to create PDF from webview in android?

I am displaying webpage in webview. Now how to create PDF from webview ?

For Example : webview loads URL is "www.google.co.in". Now how to save this webpage as image and create pdf ??

any help would be appreciated

Upvotes: 19

Views: 17600

Answers (3)

Sandeep Pareek
Sandeep Pareek

Reputation: 1789

if can not want return path

private fun createWebPrintJob(webView: WebView) {
    val printManager = this.getSystemService(Context.PRINT_SERVICE) as PrintManager
    val printAdapter = webView.createPrintDocumentAdapter()
    val jobName = getString(R.string.app_name) + " Print Test"
    printManager.print(
        jobName, printAdapter,
        PrintAttributes.Builder().build()
    )
}

if can want return path of PDF

try this

lib :

implementation 'com.github.pramodkr123:ConvertWebViewToPdfDemo:1.0.4'

Kotlin CODE:

    private fun sentEmailAndSavePDF() {
    val directory =
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/MDP-PDF/")
    val min = 1000
    val max = 9999
    val random = Random().nextInt(max - min + 1) + min
    val fileName = "MDP_$random.pdf"

    PdfView.createWebPrintJob(
        this@WebViewActivity,
        binding.webview,
        directory,
        fileName,
        object : PdfView.Callback {
            override fun success(p0: String?) {

                Log.e(TAG, "success: ")
                   //p0  is your pdf PATH 
            }

            override fun failure() {

            }

        })
}

Upvotes: 0

fattire
fattire

Reputation: 8843

As of API 19 (KitKat), Android now lets you print a webview directly. Moreover, the same PrintManager API can be used to generate a PDF from a WebView without any external libraries.

As the example code shows, just get the PrintManager, create a PrintDocumentAdapter from the WebView in question, then create a new PrintJob and your user should see the option to save it to a file as PDF or print to a cloud printer. On newer Androids than 4.4 they'll also get a visual preview of what will be printed/PDF'd.

Upvotes: 4

Aamirkhan
Aamirkhan

Reputation: 5784

Try like this

WebView have inbuilt method called setPictureListener Use that method as below

webView1.setPictureListener(new PictureListener() {

            public void onNewPicture(WebView view, Picture picture) {
                if (picture != null) {
                    try {
                        bmp = pictureDrawable2Bitmap(new PictureDrawable(
                                picture));

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

For obtaining bitmap i have used pictureDrawable2Bitmap and here is that one

private static Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable) {
        Bitmap bitmap = Bitmap.createBitmap(
                pictureDrawable.getIntrinsicWidth(),
                pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawPicture(pictureDrawable.getPicture());
        return bitmap;
    }

Now Your Bitmap is ready,Now set webview client as below

webView1.setWebViewClient(new myWebClient());

And here is myWebClient

public class myWebClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            view.loadUrl(url);
            return true;

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);
            Log.i("OnPageLoadFinished", url);
            img.setImageBitmap(bmp);
        }

As shown on page load finished i have set image bitmap which is snap of current loaded url on your webview

Now Bitmap is ready pass that bitmap to Pdf using IText Library

Here is an example of writing pdf with image on iText Use Below function for that

public void SimplePDFTable() throws Exception {

    File direct = new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/AamirPDF");
    if (!direct.exists()) {
        if (direct.mkdir()) {
            Toast.makeText(MainActivity.this,
                    "Folder Is created in sd card", Toast.LENGTH_SHORT)
                    .show();
        }
    }
    String test = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/AamirPDF";
    Document document = new Document();

    PdfWriter.getInstance(document, new FileOutputStream(test
            + "/mypdf.pdf"));

    document.open();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    Image image = Image.getInstance(byteArray);


    image.scaleToFit(PageSize.A4.getHeight(), PageSize.A4.getWidth());
    document.add(image);

    document.close();

}

Good Luck

Upvotes: 15

Related Questions