Android-从WebView绘图到PDF画布 [英] Android - Drawing to a PDF canvas from WebView

查看:99
本文介绍了Android-从WebView绘图到PDF画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android上进行PDF打印工作时遇到了麻烦.我想做的是在WebView中呈现一些HTML,然后在PDF画布上绘制WebView内容,最后将PDF写入文件.我遇到的问题是,即使剩余了很多画布,当我绘制到PDF画布时,内容也会被剪切.我尝试使用.clipRect(Rect rect, Op op)调整画布的大小,这种方法可以完成,但效果不理想.

I've been having troubles getting PDF printing work on Android. What I'm trying to do is render some HTML in WebView, then draw the WebView contents on a PDF canvas and finally write the PDF to a file. The problem I'm having is that when I draw to the PDF canvas the content gets clipped even though there is plenty of canvas left. I've tried resizing the canvas using the .clipRect(Rect rect, Op op) and that kind of worked but not as well as I would've liked.

我也不知道如何将HTML px尺寸可靠地转换为PDF PostScript 1/72英寸尺寸.

I also have no idea how I can translate the HTML px measurements to the PDF PostScript 1/72th inch measurements reliably.

这是我正在使用的代码:

Here's the code I'm using:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    WebView wv = (WebView) this.findViewById(R.id.webView1);

    wv.loadUrl("file:///android_asset/temp.html");           
}

public void button1onClick(View v)
{
    //Create PDF document
    PdfDocument doc = new PdfDocument();

    //Create A4 sized PDF page
    PageInfo pageInfo = new PageInfo.Builder(595,842,1).create();

    Page page = doc.startPage(pageInfo);

    WebView wv = (WebView) this.findViewById(R.id.webView1);

    page.getCanvas().setDensity(200);

    //Draw the webview to the canvas
    wv.draw(page.getCanvas());

    doc.finishPage(page);

    try
    {
        //Create the PDF file
        File root = Environment.getExternalStorageDirectory();          
        File file = new File(root,"webview.pdf");
        FileOutputStream out = new FileOutputStream(file);
        doc.writeTo(out);
        out.close();
        doc.close();

        //Open the PDF
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);          
    }
    catch(Exception e)
    {
        throw new RuntimeException("Error generating file", e);
    }
}

基本上,该程序只是将temp.html文件加载到Webview并为我呈现一个可用于创建PDF的按钮.

Basically the program just loads the temp.html file to webview and renders me a button that I can use to create the PDF.

temp.html文件如下所示:

The temp.html file looks like:

<html>
<head>
    <style>
        div.border
        {
            width:600px;
            height:800px;
            border:1px solid black;
        }
    </style>
</head>
<body>
    <div class="border"></div>
</body>

这是带有手动添加的黑色边框以显示比例的结果:

And here is the result with manually added black border to show the scale:

对于在不使用需要商业许可的库的情况下如何在Android上可靠地将HTML转换为PDF的一些技巧,我将非常感谢.

I would really appreciate some tips on how to convert HTML to PDF reliably on Android without using libraries that require licenses for commercial use.

推荐答案

摘要: 请勿修改浓度(应在设备上将其设置为160 dpi左右),而是使用刻度. 如果您只需要PDF中HTML页面的位图(无超链接功能),则可以使用. 这是您的代码生成的,带有以下代码:

Summary: Don't modify the density, (it should be set on your device, probably to medium 160 dpi) instead, use scale. If you Just need Bitmaps of your HTML page in your PDF (No hyper-link function), this works. This is what your code is generating, with the following code:

    //Create PDF document

        PdfDocument doc = new PdfDocument();

        //Create A4 sized PDF page
        int my_width  = 595;
        int my_height = 842;

        PageInfo pageInfo = new PageInfo.Builder(my_width,my_height,1).create();
//      PageInfo pageInfo = new PageInfo.Builder(650,850,1).create();

        Page page = doc.startPage(pageInfo);

        WebView wv = (WebView) this.findViewById(R.id.webView1);

        Canvas canvas = page.getCanvas();
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        final DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        int    height  = displayMetrics.heightPixels;
        int    width   = displayMetrics.widthPixels;
        float  density = displayMetrics.density;
        int    wvWidth = wv.getWidth();
        int    wvHeight= wv.getHeight();
        float  wvScaleX= wv.getScaleX();
        float  wvScaleY= wv.getScaleY();

//      canvas.setDensity(100);//200 Bitmap.DENSITY_NONE
        int cdensity = canvas.getDensity();
        float scaleWidth = (float)width/(float)my_width;
        float scaleHeight = (float)height/(float)my_height;
        canvas.scale(scaleWidth, scaleHeight);
        Log.e("button1onClick","canvas width:" + canvas.getHeight() + " canvas height:" +  canvas.getWidth());
        Log.e("button1onClick","metrics width:" + width + " metrics height:" +  height + "metrics density:" +  density);
        Log.e("button1onClick"," wvWidth:" + wvWidth + " wvHeight:" +  wvHeight);
        Log.e("button1onClick"," scaleWidth: " + scaleWidth +
                " scaleHeight:" +  scaleHeight +" cdensity:" + cdensity);
        Paint paint = new Paint();
//      paint.setStyle(Style.FILL);
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(1);

        //Draw the webview to the canvas
        wv.draw(canvas);
        canvas.scale(1f, 1f);
        canvas.drawRect(0, 0, canvas.getWidth()-1,  canvas.getHeight()-1, paint);
        canvas.drawText("Direct drawn Red Rectangle to fill page canvas 0, 0," +
                canvas.getWidth() + "," + canvas.getHeight(), 100, 100, paint);

        doc.finishPage(page);

这很好用(超级链接当然不能用). 更复杂的示例:

This works well (Hyper-links cannot work of course). More complex example:

这篇关于Android-从WebView绘图到PDF画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆