Android 上 xml Layout view 生成pdf文件

前言,以前生成PDF,是靠盲布的。效率非常不高,再次做类似项目决定将XML Layout View转换成pdf,这个布局就由xml文件来实现,xml再使用上ConstraintLayout,那简直就是「所见即所得」了。非常的方便。这里把这个方案分析给大家。

系统版本: Android 4.4.2 +
平台:不限

    public static void createPdfFromView(View content, final String pdfPath) {
        if (content == null || pdfPath == null) {
            Log.e(TAG, "content and pdfPath can not be null!");
            return;
        }

        // create a new document
        PdfDocument document = new PdfDocument();
        // crate a page description
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
                PrintAttributes.MediaSize.ISO_A4.getWidthMils() * 72 / 1000,
                PrintAttributes.MediaSize.ISO_A4.getHeightMils() * 72 / 1000, 1)
                .create();

        // start a page
        PdfDocument.Page page = document.startPage(pageInfo);

        // draw something on the page
//        LayoutInflater li = LayoutInflater.from(getApplicationContext());
//        View content = li.inflate(R.layout.activity_welcome, null);
        Canvas canvas = page.getCanvas();
        content.draw(canvas);

        // finish the page
        document.finishPage(page);
        // add more pages
        // write the document content
        FileOutputStream os = null;
        try {
            Log.i(TAG, "String:" + pdfPath);
            os = new FileOutputStream(pdfPath);
            document.writeTo(os);
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // close the document
            document.close();
        }
    }

来源:stackoverflow,具体链接找不到了。:(

注意事项:
1. 使用LayoutInflater反射出来的View不行;
2. 将要转换成pdf的xml view文件include到一个界面中,将其设置成android:visibility=”invisible”就可以实现,不显示,但是能转换成PDF;
3. 设置成gone不行;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

袁保康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值