1

I need to dynamically add text to a linear layout in an Android PdfDocument that I generate from a layout.xml file. The header is consistent and therefore placed in the layout. However, the data that follows comes from a few dynamically populated lists. I need to add this data using the Android PdfDocument library (no third party solutions please).

I have been able to create the Pdf and save it to external storage. I can changed the text of items defined in the layout.xml. I just can't add anything to the layout.xml dynamically.

My code is long and scattered over a few class as the PdfDocument is populated by a custom ReportBuilder object. So I will simply list the steps I take and show the relevant portion of my code.

This works: 1. Get layout and inflate it. 2. Create PdfDocument object.page object. 3. Set page width and height. 4. Get canvas.

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

As stated, anything that is already contained in the report_layout.xml file can have it's properties changed and is contained in the final pdf. However, the TextView I create and try to add is never visible. I have made sure text color is correct, I get no errors, I have tried placing images as well and that does not work either. What am I missing?

user693336
  • 325
  • 5
  • 12

1 Answers1

0

The problem is your linearlayout still has a width and height of zero.

Try to add:

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

Also take a look at this answer.

twitch
  • 13
  • 1
  • 3