PdfDocument is a class that makes it possible to generate a PDF from an Android View. You simply add a View to PdfDocument
and then save the PDF to memory.
However, I wouldn't like to add a View that is already rendered in the screen, because such View is only good for smartphone screens, and I want to generate a PDF document for printers.
Therefore, I want to pass a View without rendering. While it's certainly possible for me to do that, how would the dimensions and proportions be decided? How can I control this in my PDF?
UPDATE:
Following the answer below from clotodex, I did:
LayoutInflater inflater = getLayoutInflater();
View linearview;
linearview = inflater.inflate(R.layout.printed_order,
findViewById(android.R.id.content),
false);
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(2480, 3508, 0).create();
PdfDocument.Page page = document.startPage(pageInfo);
linearview.draw(page.getCanvas());
document.finishPage(page);
OutputStream outStream;
File file = new File(getExternalFilesDir(null), "pedido.PDF");
try {
outStream = new FileOutputStream(file);
document.writeTo(outStream);
document.close();
outStream.flush();
outStream.close();
but I get an empty PDF. If I do
View view = findViewById(android.R.id.content);
view.draw(page.getCanvas());
in place of
linearview.draw(page.getCanvas());
I get the activity I'm in, which confirms everything is rigth, except for the view that I'm trying to print.
Have a look at this question render view off-screen in android.
In Android the measurements for a view are given by the parent layout.
This means you can create a new layout with your desired measurements and inflate your view with attachToRoot=false
and root=your_new_layout
.
When you have rendered the view you can now proceed as you would with drawing a rendered view to pdf (following the instruction in your link or converting it to a bitmap before drawing to the page canvas).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With