【发布时间】:2018-09-17 12:06:50
【问题描述】:
我需要将文本动态添加到我从 layout.xml 文件生成的 Android PdfDocument 中的线性布局中。标题是一致的,因此放置在布局中。但是,随后的数据来自一些动态填充的列表。我需要使用 Android PdfDocument 库添加这些数据(请不要使用第三方解决方案)。
我已经能够创建 Pdf 并将其保存到外部存储中。我可以更改 layout.xml 中定义的项目的文本。我只是不能动态地向 layout.xml 添加任何东西。
我的代码很长并且分散在几个类中,因为 PdfDocument 由自定义 ReportBuilder 对象填充。因此,我将简单地列出我采取的步骤并展示我的代码的相关部分。
这有效: 1. 获取布局并对其进行充气。 2. 创建 PdfDocument object.page 对象。 3.设置页面宽度和高度。 4. 获取画布。
...
// Get the canvas we need to draw on.
Canvas canvas = page.getCanvas();
// Set report title, text field already exists in report_layout.xml
// So this works
setPageTitle("Report Title");
// Adding dynamically generated content does not work here...
TextView text = new TextView(mContext);
text.setTextColor(BLACK);
text.setText("Testing if I can add text to linear layout report_container");
text.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
// The report container is an empty LinearLayout
// present in report_layout.xml
LinearLayout cont = mReportLayout.findViewById(R.id.report_container);
((LinearLayout)cont).addView(text);
// Draw the view into the pdf document
mReportLayout.draw(canvas);
// Finalize the page.
mDocument.finishPage(page);
// Return document, calling party will save it.
return mDocument;
...
如上所述,report_layout.xml 文件中已包含的任何内容都可以更改其属性并包含在最终的 pdf 中。但是,我创建并尝试添加的 TextView 永远不可见。我已确保文本颜色正确,没有错误,我也尝试过放置图像,但这也不起作用。我错过了什么?
【问题讨论】:
标签: android pdf pdf-generation using