I want to create a Pdf from Recyclerview. I was able to get an image of a recyclerview before. I first obtained a bitmap and then converted it to an image. But I couldn't find the correct way to create a pdf. The recommended libraries are too old. I am looking for an updated solution.
This is my function to get a bitmap:
private fun getRecyclerViewScreenshotAsBitmap(
recyclerView: RecyclerView,
defaultColor: Int = Color.WHITE
): Bitmap {
recyclerView.measure(
View.MeasureSpec.makeMeasureSpec(recyclerView.width, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
)
val bitmap = Bitmap.createBitmap(
recyclerView.width,
recyclerView.measuredHeight,
Bitmap.Config.ARGB_8888
);
val canvas = Canvas(bitmap)
canvas.drawColor(defaultColor)
recyclerView.draw(Canvas(bitmap));
return bitmap
}
How to get a pdf from a bitmap or reyclerview?
You can get a canvas
from the inbuilt PDFDocument class
// Create the initial PDF page
int A4Short = 594; // Postscript points
int A4Long = 841; // Postscript points
int pageNumber = 1;
PdfDocument.PageInfo.Builder pageBuilder = new
PdfDocument.PageInfo.Builder(A4Short,A4Long, pageNumber);
PdfDocument.PageInfo pageInfo = pageBuilder.create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas pdfCanvas = page.getCanvas();
then instead of recyclerView.draw(Canvas(bitmap));
do
recyclerView.draw(pdfCanvas);
or you can draw the bitmap you have to the pdfCanvas
then close the page document.finishPage(page);
and write to file document.writeTo(outputstream);
The problem you might have is that an A4 page is not that big as it is only 594 x 841 pixels and you might need to either break the recycler in to many pages or set a scale on the pdfCanvas pdfCanvas.scale(scaleWidth, scaleWidth);
You might also be better rather than trying to re-use a layout you have used on screen create a linearLayout just for create drawing to pdf as it might be easier to get it to fit to the page size/paginate.