Save ListView as Pdf file
1. On the page containing the ListView listview1, Button savePdf, and an EditText edittext1 (This is for entering the file name).
2. Create a String variable filename.
3. In Activity, add Import event and add following imports:
import java.nio.charset.StandardCharsets;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
import android.graphics.pdf.PdfDocument;
import java.io.IOException;
import java.io.OutputStream;
4. Create a more block savePdfToDownloads [PdfDocument document][String filename]
Here PdfDocument is a custom parameter. To add it, More Block -- Custom Parameter -- parameter: m.PdfDocument, variable: document.
Put following codes in this more block:
Uri pdfUri = null;
OutputStream outputStream = null;
try {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Downloads.DISPLAY_NAME, _filename + ".pdf");
contentValues.put(MediaStore.Downloads.MIME_TYPE, "application/pdf");
contentValues.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
pdfUri = this.getContentResolver().insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
if (pdfUri != null) {
outputStream = this.getContentResolver().openOutputStream(pdfUri);
_document.writeTo(outputStream);
Toast.makeText(this, "PDF saved to Downloads", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Error: Could not create file", Toast.LENGTH_SHORT).show();
}
_document.close();
if (outputStream != null) outputStream.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error saving PDF: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
This code saves the PdfDocument to Downloads folder with the filename specified.
5. Create a more block convertToPdf [ListView listView][String filename]
Put following codes in this more block:
try {
PdfDocument document = new PdfDocument();
ListAdapter adapter = _listView.getAdapter();
int totalItems = adapter.getCount();
// Determine page size from the first item
View firstView = adapter.getView(0, null, _listView);
firstView.measure(
View.MeasureSpec.makeMeasureSpec(_listView.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
);
firstView.layout(0, 0, firstView.getMeasuredWidth(), firstView.getMeasuredHeight());
int pageWidth = firstView.getMeasuredWidth();
int pageHeight = firstView.getMeasuredHeight();
// Loop through all items
for (int i = 0; i < totalItems; i++) {
View itemView = adapter.getView(i, null, _listView);
// Measure and layout each view before drawing
itemView.measure(
View.MeasureSpec.makeMeasureSpec(pageWidth, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
);
itemView.layout(0, 0, pageWidth, itemView.getMeasuredHeight());
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
pageWidth, itemView.getMeasuredHeight(), i + 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
itemView.draw(canvas);
document.finishPage(page);
}
_savePdfToDownloads(document, _filename);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
What this code does:
- Creates a PdfDocument document.
- Determines page size from first item of ListView Adapter.
- For each position in ListView:
- Creates a View from that position of adapter.
- Measures the View.
- Creates a page, using the width and height of View obtained above.
- Gets canvas of the page, and then draws the View obtained above on the page.
- This cycle repeats for each item of ListView.
- Saves the PdfDocument to Downloads folder using the filename specified.
6. In the event Button savePdf onClick, if length of edittext1 getText is greater than 0, then set value of String filename to edittext1 getText, else set value of filename to 123pdf.
Then use more block convertToPdf with listview1 and filename as variables. See image below.
7. Save and run the project.
8. The above project adds each item of ListView as a separate Pdf page. If you want more than 1 ListView item per pdf page, replace the code for the more block convertToPdf [ListView listView][String filename] with following code:
try {
PdfDocument document = new PdfDocument();
ListAdapter adapter = _listView.getAdapter();
int totalItems = adapter.getCount();
// Determine page size from the first item
View firstView = adapter.getView(0, null, _listView);
firstView.measure(
View.MeasureSpec.makeMeasureSpec(_listView.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
);
firstView.layout(0, 0, firstView.getMeasuredWidth(), firstView.getMeasuredHeight());
int pageWidth = firstView.getMeasuredWidth();
int itemsPerPage = 4;
ArrayList<ArrayList<View>> pages = new ArrayList<>();
ArrayList<View> currentPage = new ArrayList<>();
ArrayList<Integer> pageHeights = new ArrayList<>();
int currentPageHeight = 0;
for (int i = 0; i < totalItems; i++) {
View itemView = adapter.getView(i, null, _listView);
// Measure and layout each view
itemView.measure(
View.MeasureSpec.makeMeasureSpec(pageWidth, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
);
itemView.layout(0, 0, pageWidth, itemView.getMeasuredHeight());
// Add to current page
currentPage.add(itemView);
currentPageHeight += itemView.getMeasuredHeight();
// When 4 views are collected OR it's the last item
if (currentPage.size() == itemsPerPage || i == totalItems - 1) {
// Save page list
pages.add(new ArrayList<>(currentPage));
// Save page height
pageHeights.add(currentPageHeight);
// Reset for next page
currentPage.clear();
currentPageHeight = 0;
}
}
for (int p = 0; p < pages.size(); p++) {
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(
pageWidth, pageHeights.get(p), p + 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
int top = 0; // keeps track of vertical position
for (View v : pages.get(p)) {
// Save canvas state before translating
canvas.save();
// Move canvas down by 'top' pixels
canvas.translate(0, top);
// Draw the view
v.draw(canvas);
// Restore canvas to previous position
canvas.restore();
// Increment 'top' for next view
top += v.getMeasuredHeight();
}
document.finishPage(page);
}
_savePdfToDownloads(document, _filename);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
See video below:




Comments
Post a Comment