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);
给出一个名为root
的View
,它将(及其子级,如果有的话)填充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.