Android:放大版面并将其写入PDF会生成空白PDF [英] Android: inflating a layout and writting it to PDF produces a blank PDF

查看:162
本文介绍了Android:放大版面并将其写入PDF会生成空白PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在活动中选择一个共享按钮时,我想填充一个布局,填充它,然后使用新的打印API将该布局写入pdf.

when the user selects a share button within an activity, I would like to inflate a layout, populate it, and then write that layout to a pdf using the new printing API.

我的片段中有

@TargetApi(Build.VERSION_CODES.KITKAT)
  public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_share_context:
        LayoutInflator inflator = getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View container = inflator.inflate(R.layout.person_share, null, false);
        TextView name = (TextView)topContainer.findViewById(R.id.person_name);
        name.setText("Test Name");
        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(612, 792, 1).create()
        PdfDocument.Page page = document.startPage(pageInfo)
        container.draw(page.getCanvas());
        document.finishPage(page)

        // write pdf
        ...

很遗憾,这会输出空白的pdf文档.但是,当我使用屏幕上已经存在的视图(在onCreateView(..)中夸大)时,它按预期显示在pdf中.

This unfortunately outputs a blank pdf document. However, when I use a view that already exists on the screen (inflated in onCreateView(..)), it shows up in the pdf as expected.

我将不胜感激.

推荐答案

如果我的理论是正确的-您的展开式布局的宽度和高度仍为零-您可以手动调用measure()layout()大小和位置的东西:

If my theory is correct -- that your inflated layout still has a width and height of zero -- you can call measure() and layout() to manually size and position things:

root.measure(800, 480);
root.layout(0, 0, 800, 480);

给出一个名为rootView,它将(及其子级,如果有的话)填充800像素宽,480像素高的空间(例如,WVGA设备,横向,全屏) .根据您的情况,您应该能够调用Canvas上的getWidth()getHeight()来确定用于measure()layout()的大小.

Given a View named root, this will have it (and its children, if any) fill an 800-pixel wide by 480-pixel high space (e.g., a WVGA device, landscape, full-screen). In your case, you should be able to call getWidth() and getHeight() on the Canvas to determine the sizes to use for measure() and layout().

FWIW,我个人会生成HTML并将其用作打印的基础,而不是布局文件.这是我在此示例项目中展示的技术之一.

FWIW, personally, I'd generate HTML and use that for the basis of printing, rather than a layout file. That's one of the techniques I demonstrate in this sample project.

这篇关于Android:放大版面并将其写入PDF会生成空白PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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