How to set my own canvas into the PdfDocument.Page

Viewed 193

I have an mCanvas object with all the drawings in it. Now, I want to use the same canvas into my PdfDocument so that I can save it as a PDF file as well.

PdfDocument pdfDocument = new PdfDocument();
PageInfo pageInfo = new PageInfo.Builder(mCanvas.getWidth(),
                mCanvas.getHeight(), 1).create();
Page pdfPage = pdfDocument.startPage(pageInfo);

//pdfPage.setCanvas(mCanvas); <--- this is what I want to achieve

Is this possible with PdfDocument?

1 Answers

As mentioned by @CommonsWare in the comments section, there is no way to "play back" the drawing operations made on canvas. The solution that fixed my issue is below.

Bitmap bitmap = mCanvas.getBitmap();
int width = bitmap.getWidth();
int height = bitmap.getHeight();

PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo.Builder builder = 
    new PdfDocument.PageInfo.Builder(width, height, 1);
PdfDocument.PageInfo pageInfo = builder.create();
PdfDocument.Page pdfPage = pdfDocument.startPage(pageInfo);
Canvas pdfCanvas = pdfPage.getCanvas();

pdfCanvas.drawBitmap(bitmap, 0, 0, null);

pdfDocument.finishPage(pdfPage);
pdfDocument.writeTo(outputStream);
pdfDocument.close();

In short, instead of setting the original canvas into my PdfDocument, I extracted the original canvas' bitmap and drew it into my PdfDocument's canvas.

Related