Android: Create identical Views for drawing on Canvas of PdfDocument for printing

Viewed 205

I'm using Views inflated from XML to draw on the Canvas of a PdfDocument.Page. The problem is, that the generated PDF looks different on different devices (text size, height and width ), depending on screen size etc..

Is there a way to create identical Views no matter what the screen size is, so that I get identical PDFs. Dp, sp, px, pt all respect somehow the physical device. Maybe overwriting some values of screen-size etc. in Context?

Here is my code for generating a PDF Document:

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.pdf_person_container, null);

PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595,842,1).create();
PdfDocument.Page page = document.startPage(pageInfo);

int measureWidth = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getWidth(), View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(page.getCanvas().getHeight(), View.MeasureSpec.EXACTLY);
view.measure(measureWidth, measuredHeight);
view.layout(0, 0, page.getCanvas().getWidth(), page.getCanvas().getHeight());

view.draw(page.getCanvas());

document.finishPage(page);
document.writeTo(new FileOutputStream(filePath + "Detail.pdf"));

PDF on phone 1

PDF on phone 2

1 Answers
Configuration config = sourcecontext.getResources().getConfiguration();
config.densityDpi = DisplayMetrics.DENSITY_HIGH;
config.setTo(config);
Context context sourcecontext.createConfigurationContext(config);

And use this new context for the Inflater

Related