See the code below which i am using to generate PDF from a recyclerview .
@TargetApi(19)
private void writePDFDocument() {
final File file = new File(getStorageDir("PDF"), "sample.pdf");
int PDF_PAGE_WIDTH = 595, PDF_PAGE_HEIGHT = 842;
// create a new document
PdfDocument pdfDocument = new PdfDocument();
//Get Content View.
View contentView = recyclerView;
// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.
Builder((int) PDF_PAGE_WIDTH, (int) PDF_PAGE_HEIGHT, 1).create();
// start a page
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
// draw view on the page
Canvas pageCanvas = page.getCanvas();
int pageWidth = pageCanvas.getWidth();
int pageHeight = pageCanvas.getHeight();
int measureWidth = View.MeasureSpec.makeMeasureSpec(pageWidth, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(pageHeight, View.MeasureSpec.EXACTLY);
contentView.measure(measureWidth, measuredHeight);
contentView.layout(0, 0, pageWidth, pageHeight);
contentView.draw(pageCanvas);
// finish the page
pdfDocument.finishPage(page);
try {
pdfDocument.writeTo(new FileOutputStream(file));
} catch (IOException e) {
e.printStackTrace();
}
// close the document
pdfDocument.close();
// Set on UI Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(PrintPDFSample.this);
builder.setTitle("Success")
.setMessage("PDF File Generated Successfully.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
}).show();
}
});
}
From the above code i was able to generate PDF . My actual problem is that the PDF generated contains only visible item in the screen. If i increase the page height i can see the entire items . But i need to generate multiple A4 pages instead of increasing PDF height . I am aware that there is a lib called iText for generating PDF but its only free for personal use .