如何在android中从webview创建PDF?

时间:2013-12-11 06:00:08

标签: android pdf webview

我在webpage中显示webview。现在如何从webview创建PDF

例如:webview加载网址为"www.google.co.in"。现在如何将此网页保存为图像并创建pdf ??

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:13)

试试这个

WebView有一个名为setPictureListener的内置方法。使用下面的方法

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();
                    }
                }
            }
        });

为了获得位图,我使用了pictureDrawable2Bitmap,这是一个

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;
    }

现在您的位图已准备就绪,现在将webview客户端设置如下

webView1.setWebViewClient(new myWebClient());

这里是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);
        }

如页面加载完成所示,我已经设置了图像位图,这是您网页视图中当前加载的网址的快照

现在,Bitmap已准备好使用IText Library将该位图传递给Pdf

以下是在iText上使用图像编写带有图像的pdf的示例

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();

}

祝你好运

答案 1 :(得分:2)

从API 19(KitKat)开始,Android现在可以直接让您print a webview。此外,相同的 PrintManager API可用于从 WebView 生成PDF而无需任何外部库。

如示例代码所示,只需获取 PrintManager ,从相关的 WebView 创建 PrintDocumentAdapter ,然后创建一个新的 PrintJob ,您的用户应该看到将其保存为PDF文件或打印到云打印机的选项。在比4.4更新的Androids上,他们还可以预览将要打印的内容/ PDF' d。

答案 2 :(得分:0)

如果不想返回路径

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()
    )
}

如果想要PDF的返回路径

试试这个

库:

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

科特林代码:

    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() {

            }

        })
}