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
5,764 10 10 gold badges 48 48 silver badges 75 75 bronze badges asked Dec 11, 2013 at 6:00 Hardik Joshi Hardik Joshi 9,507 12 12 gold badges 63 63 silver badges 115 115 bronze badges searching for online API or local API.? Commented Dec 11, 2013 at 6:06 @SilentKiller anyone no matters. Commented Dec 11, 2013 at 6:09 try to implement of @Aamirkhan code..it will solve ur problem. Commented Dec 11, 2013 at 6:10 @Prince try with following answer else here is online api Commented Dec 11, 2013 at 6:11WebView 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)
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(); >