在安卓中生成动态PDF



我需要在从layout.xml文件生成的Android PdfDocument中动态添加文本到线性布局。标题是一致的,因此放置在布局中。但是,下面的数据来自几个动态填充的列表。我需要使用Android Pdf文档库添加此数据(请不要使用第三方解决方案)。

我已经能够创建 PDF 并将其保存到外部存储。我可以更改布局中定义的项目的文本.xml。我只是无法动态地向布局添加任何内容.xml。

我的代码很长,分散在几个类中,因为 PdfDocument 由自定义 ReportBuilder 对象填充。因此,我将简单地列出我采取的步骤并显示我的代码的相关部分。

这有效: 1.获取布局并充气。 2. 创建 pdf文档 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 中。但是,我创建并尝试添加的文本视图永远不会可见。我已经确保文本颜色正确,没有错误,我也尝试放置图像,但这也不起作用。我错过了什么?

问题是您的线性布局的宽度和高度仍然为零。

尝试添加:

//add this before mReportLayout.draw(canvas)
int measuredWidth = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getWidth(), View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getHeight(), View.MeasureSpec.EXACTLY);
mReportLayout.measure(measuredWidth, measuredHeight);
mReportLayout.layout(0, 0, measureWidth, measuredHeight);

也看看这个答案。

最新更新