在Android中生成动态PDF

问题描述 投票:1回答:1

我需要动态地将文本添加到我从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
1个回答
0
投票

问题是你的linearlayout的宽度和高度仍为零。

尝试添加:

//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);

还可以看看this answer

© www.soinside.com 2019 - 2024. All rights reserved.