Writing listview contents to html file android - android

I have a listview that is being filled from my database. Now I want to take the contents of this listview and show it in html table.
How I can take my listview and write its contents to html file?

I just did something very similar here.
private File saveResults() {
/*
* Write the results to a file.
*/
List<RiderResult> Results = DataModel.get().getResults();
try {
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Toast.makeText(SummaryFragment.this.getContext(), "Unable to access external storage.",
Toast.LENGTH_SHORT).show();
return null;
}
/*
* Create a file folder in external storage.
*/
File csvDir = new File(
Environment.getExternalStorageDirectory(),
"Android/data/ca.mydomain.myapp/results");
if (!csvDir.exists())
csvDir.mkdirs();
/*
* Create a file in the folder, with today's date and time as the name.
*/
Date dateNow = new Date ();
SimpleDateFormat dateformatYYYYMMDD = new SimpleDateFormat("yyyyMMddHHmm");
StringBuilder nowMMDDYYYY = new StringBuilder( dateformatYYYYMMDD.format( dateNow ) );
File csvFile = new File(csvDir, "result_" + nowMMDDYYYY + ".csv");
BufferedWriter bw = new BufferedWriter(new FileWriter(csvFile, false));
/*
* Write a header row.
*/
bw.write("Finish Seq, Start Num,Clock Time, Actual Time\n");
/*
* and a row for each result, comma separated
*/
for (int i = 0; i < Results.size(); i++) {
String row = new String();
row = "" + (i + 1) + "," + Results.get(i).getStartNo()
+ "," + Results.get(i).getClockTimeString() + ","
+ Results.get(i).getActualTimeString() +"\n";
bw.write(row);
}
bw.close();
/*
* Return the File to the user - for use in a message or email attachment.
*/
return csvFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I was writing to a file which I later attach to an email or send via BlueTooth, or just leave it on file. My file is CSV (race results) and the name of the file is generated. But you can adapt for your use.

Related

Android : how to add an url image to my header in iText generated PDF

I'm using iText to generate a PDF.Pdf is generated for showing some records in a school, so I need to show a school Emblem and school name at the center of the top header of the first page. I have the string HTTP URL of the image file which may be of any size. I want to resize the image without losing its quality and adjust it at the header portion(so it make sense) and need to show the school name below. My problem is I don't know how to add the image so it is displayed in the "header box".
Here there are some code snippets ...
private void createPdf() {
try {
String imgURL = "http URL";
String schoolName = "School Name";
File filePath = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOCUMENTS), "PROJECT");
if (! filePath.exists()){
if (! filePath.mkdirs()){
}else{
}
}
// Create a file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
fileExp = new File(filePath+"/Report_"+ timeStamp + ".pdf");
photoURI = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".fileprovider", fileExp);
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(fileExp));
document.open();
addMetaData(document);
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
Paragraph para1 = new Paragraph(repHeader, catFont);
para1.setAlignment(Element.ALIGN_CENTER);
preface.add(para1);
addEmptyLine(preface, 2);
Paragraph para3 = new Paragraph("Period : ", textBold);
Chunk perChunk3 = new Chunk("from "+edtFromDate.getText().toString()+" to "+edtToDate.getText().toString(),textNormal);
para3.add(perChunk3);
preface.add(para3);
addEmptyLine(preface, 1);
document.close();
//insertDocument("Report_"+ timeStamp + ".pdf");
Intent emailIn = new Intent(Intent.ACTION_SEND);
emailIn.setType("application/pdf");
emailIn.putExtra(Intent.EXTRA_STREAM, photoURI);
emailIn.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIn.putExtra(Intent.EXTRA_EMAIL, new String[] { selEmailId });
emailIn.putExtra(Intent.EXTRA_SUBJECT, "Report : "+repHeader);
emailIn.putExtra(Intent.EXTRA_TEXT, repHeader);
startActivityForResult(Intent.createChooser(emailIn, "E-mail"),15);
} catch (Exception e) {
e.printStackTrace();
}
}
Below is the dependency :
implementation 'com.itextpdf:itextg:5.5.10'
You can add an image to the document and scale as the image by preferred height or width using the below code
Here I have scaled the image width according to the preferredImageHeight
Image image = Image.getInstance("https://static.wikia.nocookie.net/rickandmorty/images/9/95/HarryherpsonHS.jpg/revision/latest/top-crop/width/360/height/360?cb=20150908094923");
image.setAlignment(Element.ALIGN_CENTER);
System.out.println("Image width: " + image.getScaledWidth() + ", height: " + image.getScaledHeight());
float preferredImageHeight = 60;
float widthScale = image.getScaledHeight() / preferredImageHeight;
image.scaleAbsolute(image.getScaledWidth() / widthScale, preferredImageHeight);
System.out.println("Image width: " + image.getScaledWidth() + ", height: " + image.getScaledHeight());
document.add(image);
I would follow the instructions here https://memorynotfound.com/adding-header-footer-pdf-using-itext-java/ and customise their code to suit.
for the purposes of keeping answers here, the basic is that you need to create an "addHeader" method just before your document.close()
using something similar to this code block
private void addHeader(PdfWriter writer){
PdfPTable header = new PdfPTable(2);
try {
// set defaults
header.setWidths(new int[]{2, 24});
header.setTotalWidth(527);
header.setLockedWidth(true);
header.getDefaultCell().setFixedHeight(40);
header.getDefaultCell().setBorder(Rectangle.BOTTOM);
header.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);
// add image
Image logo = Image.getInstance(HeaderFooterPageEvent.class.getResource("/memorynotfound-logo.jpg"));
header.addCell(logo);
// add text
PdfPCell text = new PdfPCell();
text.setPaddingBottom(15);
text.setPaddingLeft(10);
text.setBorder(Rectangle.BOTTOM);
text.setBorderColor(BaseColor.LIGHT_GRAY);
text.addElement(new Phrase("iText PDF Header Footer Example", new Font(Font.FontFamily.HELVETICA, 12)));
text.addElement(new Phrase("https://memorynotfound.com", new Font(Font.FontFamily.HELVETICA, 8)));
header.addCell(text);
// write content
header.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
} catch(DocumentException de) {
throw new ExceptionConverter(de);
} catch (MalformedURLException e) {
throw new ExceptionConverter(e);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}

Android New Image has strange numbers on the end of the file name

I'm writing a camera2 app in android and when I try to save the image, something adds extra numbers on the end of the filename before the '.jpg'
I have a feeling it's because of the createTempFile() method, but here's my code:
File createImageFile() throws IOException {
++image_id;
String timestamp = new SimpleDateFormat("yyyyMMdd").format(new Date());
String subFolder = "";
if(pref_session_unique_gallery.equals("yes")){
if(event_name != null){
subFolder = event_name;
} else {
subFolder = timestamp;
}
} else {
subFolder = "_GEN";
}
if(event_name == null){
imageFileName = "CPB_"+timestamp+"-"+image_id;
} else {
imageFileName = "CPB_"+event_name+"_"+timestamp+"-"+image_id;
}
imageStorageDirectory = Environment.getExternalStorageDirectory() + File.separator + "CPB" + File.separator + subFolder;
imageFinalFileName = imageFileName;
Toast.makeText(getApplicationContext(), imageStorageDirectory + "/" + imageFileName, Toast.LENGTH_LONG).show();
File storageDirectory = new File(imageStorageDirectory);
storageDirectory.mkdir();
File image = File.createTempFile(imageFileName, ".jpg", storageDirectory);
return image;
}
When I read the toast it gives me the correct path and filename that I am expecting, but when I look in my folder view, the picture has a lot of extra numbers on it.
For example, the picture name should be CPB_20160120-1.jpg but it currently reads CPB_20160120-1484291604.jpg If it makes a difference, the file was saved at 6:37 PM
two more examples:
should be: CPB_20160120-2.jpg
is: CPB_20160120-22140921986.jpg
should be: CPB_20160120-3.jpg
is: CPB_20160120-3-965716644.jpg
Not sure where those extra numbers are coming from when the file saves...
Those random numbers are explicitly generated by createTempFile(), as seen in the source code.
You probably don't want to use temporary files anyway, thus I'd recommend to create normal files:
File image = new File(storageDirectory, imageFileName + ".jpg");
According implementation of used method new file is created with extra random integer new File(tmpDirFile, prefix + Math.randomIntInternal() + suffix)
public static File createTempFile(String prefix, String suffix, File directory)
throws IOException {
// Force a prefix null check first
if (prefix.length() < 3) {
throw new IllegalArgumentException("prefix must be at least 3 characters");
}
if (suffix == null) {
suffix = ".tmp";
}
File tmpDirFile = directory;
if (tmpDirFile == null) {
String tmpDir = System.getProperty("java.io.tmpdir", ".");
tmpDirFile = new File(tmpDir);
}
File result;
do {
result = new File(tmpDirFile, prefix + Math.randomIntInternal() + suffix);
} while (!result.createNewFile());
return result;
}

Android Studio: Can not write to the Storage of my device, even though it seems to find the path just fine

So, I am trying to make a little GPS Tracker, which works fine so far. I get the data, put it into a .kml file and then I want to save the file to the storage. I can see in my android console that it creates the file just fine. But when I then try to save it to storage, it always throws a file not found exception.
This is the class that should do the exporting and saving:
private void doExport() {
SQLiteDatabase db = null;
Cursor cursor = null;
try {
// Hard code to set altitudeCorectionMeters
this.setAltitudeCorrectionMeters(40);
db = openOrCreateDatabase(GPSLoggerService.DATABASE_NAME,
SQLiteDatabase.OPEN_READWRITE, null);
cursor = db.rawQuery("SELECT * " + " FROM "
+ GPSLoggerService.POINTS_TABLE_NAME
+ " ORDER BY GMTTIMESTAMP ASC", null);
int gmtTimestampColumnIndex = cursor
.getColumnIndexOrThrow("GMTTIMESTAMP");
int latitudeColumnIndex = cursor.getColumnIndexOrThrow("LATITUDE");
int longitudeColumnIndex = cursor
.getColumnIndexOrThrow("LONGITUDE");
int altitudeColumnIndex = cursor.getColumnIndexOrThrow("ALTITUDE");
int accuracyColumnIndex = cursor.getColumnIndexOrThrow("ACCURACY");
if (cursor.moveToFirst()) {
StringBuffer fileBuf = new StringBuffer();
String beginTimestamp = null;
String endTimestamp = null;
String gmtTimestamp = null;
initFileBuf(fileBuf, initValuesMap());
// Write coordinates to file
do {
gmtTimestamp = cursor.getString(gmtTimestampColumnIndex);
if (beginTimestamp == null) {
beginTimestamp = gmtTimestamp;
}
/**
* 2. getData from database (cursor);
*/
double latitude = cursor.getDouble(latitudeColumnIndex);
double longitude = cursor.getDouble(longitudeColumnIndex);
double altitude = cursor.getDouble(altitudeColumnIndex)
+ this.getAltitudeCorrectionMeters();
double accuracy = cursor.getDouble(accuracyColumnIndex);
/**
* End step 2.
*/
/**
* 3. Write data (query from database) to file
*/
fileBuf.append(sevenSigDigits.format(longitude) + ","
+ sevenSigDigits.format(latitude) + "," + altitude
+ "\n");
/**
* End Step 3.
*/
} while (cursor.moveToNext());
endTimestamp = gmtTimestamp;
closeFileBuf(fileBuf, beginTimestamp, endTimestamp);
String fileContents = fileBuf.toString();
Log.d(tag, fileContents);
/**
* Step 4. Write file to /sdcard
*/
File sdDir = new File("/sdcard/GPSLogger");
sdDir.mkdirs();
File file = new File("/sdcard/GPSLogger/" + currentTripName
+ ".kml");
Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
FileWriter sdWriter = new FileWriter(file, false);
sdWriter.write(fileContents);
sdWriter.close();
/**
* End Step 4.
*/
// R.string.export_completed Predefined in string.xml
Toast.makeText(getBaseContext(), R.string.export_completed,
Toast.LENGTH_LONG).show();
// If cursor.moveToFirst() Fails, no data is available
// database
} else {
Toast.makeText(
getBaseContext(),
"I didn't find any location points in the database, so no KML file was exported.",
Toast.LENGTH_LONG).show();
File sdDir = new File("/sdcard/GPSLogger");
sdDir.mkdirs();
File file = new File("/sdcard/GPSLogger/" + currentTripName
+ ".kml");
Toast.makeText(getApplicationContext(), file.toString(), Toast.LENGTH_LONG).show();
}
} catch (FileNotFoundException fnfe) {
Toast.makeText(
getBaseContext(),
"Error trying access the SD card. Make sure your handset is not connected to a computer and the SD card is properly installed",
Toast.LENGTH_LONG).show();
File sdDir = new File(Environment.getExternalStoragePublicDirectory(Environment.MEDIA_MOUNTED).getPath());
String pathname = sdDir.toString();
Toast.makeText(getApplicationContext(), pathname, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Error trying to export: " + e.getMessage(),
Toast.LENGTH_LONG).show();
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
close_db(db);
}
}
The path to:
File sdDir = new File("/sdcard/GPSLogger");
is hardcoded, because otherwise the App only finds the emulated storage. Can anyone tell me where I am going wrong? Everything seems to work fine, until it shall save the file to the actual storage...
The Toast message from the exception also seems to show a valid path+name combination. I would be very grateful for help.
I am an idiot!
I forgot to give it permission to write to my storage.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
That fixed it for me.
:)

WordtoPdf /PdftoWord in Android

Anyone Know the code for converting Word to PDF / PDF to Word in ANDROID...
If you Know
Please Share me....
Already tried:
Jars:
docx4j-3.0.0.jar
Code:
try
{
long start = System.currentTimeMillis();
InputStream is = new FileInputStream(
new File("file1"));
Toast.makeText(getApplicationContext(), "is", Toast.LENGTH_SHORT).show();
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(is);
List sections = wordMLPackage.getDocumentModel().getSections();
for (int i = 0; i < sections.size(); i++) {
System.out.println("sections Size" + sections.size());
/* wordMLPackage.getDocumentModel().getSections().get(i)
.getPageDimensions().setHeaderExtent(3000);*/
}
Mapper fontMapper = new IdentityPlusMapper();
PhysicalFont font = (PhysicalFont) PhysicalFonts.getPhysicalFonts().get(
"Comic Sans MS");
fontMapper.getFontMappings().put("Algerian", font);
wordMLPackage.setFontMapper(fontMapper);
PdfSettings pdfSettings = new PdfSettings();
org.docx4j.convert.out.pdf.PdfConversion conversion = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
wordMLPackage);
OutputStream out = new FileOutputStream(new File(
"file1/sampleeee.pdf"));
conversion.output(out, pdfSettings);
System.err.println("Time taken to Generate pdf "
+ (System.currentTimeMillis() - start) + "ms");
}
catch(Exception e)
{
e.printStackTrace();
}
But I cant get the output...
One reason why you "cant get the output" is because you are providing an incorrect FileOutputStream. You need to be using either:
Internal storage (openOutputStream(), getFilesDir(), etc.), or
External storage (getExternalFilesDir(), etc.)

Display sqlite database content in pdf format in android

I have a Sqlite database in Android and I want to display its content in a PDF file, by building it dynamically in Android on pressing a Button.
I am aware with iText but I want to go with a simpler solution..
Can anyone help me with it plz!!
Look at droidtext which a port of the iText library version 2.1.7 for Android.
There are lots of examples too. Get started with Helloworld.
public class HelloWorld {
/**
* Generates a PDF file with the text 'Hello World'
*
* #param args
* no arguments needed here
*/
public static void main(String[] args) {
System.out.println("Hello World");
// step 1: creation of a document-object
Document document = new Document();
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.getInstance(document, new FileOutputStream(android.os.Environment.getExternalStorageDirectory() + java.io.File.separator + "droidtext" + java.io.File.separator + "HelloWorld.pdf"));
// step 3: we open the document
document.open();
// step 4: we add a paragraph to the document
document.add(new Paragraph("Hello World"));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
// step 5: we close the document
document.close();
}
}
For display content of Sqlite database into pdf you have to use itextpdf-5.2.1.jar.you can download it from here
Example code:
DatabaseHandlerofdatabase dbHandler = new DatabaseHandlerofdatabase(this);
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor c1 = db.rawQuery("SELECT * FROM tablename", null);
String filename="nameoffile.pdf";
Document document=new Document(); // create the document
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs(); // create root directory in sdcard
}
File gpxfile = new File(root,filename); // generate pdf file in that directory
PdfWriter.getInstance(document,new FileOutputStream(gpxfile));
document.open(); // open the directory
Paragraph p3=new Paragraph(); // to enter value you have to create paragraph and add value in it then paragraph is added into document
p3.add("Username : ");
document.add(p3);
// now for ad table in pdf use below code
PdfPTable table = new PdfPTable(3); // Code 1
// Code 2
table.addCell("CATEGORY");
table.addCell("BUDGET");
table.addCell("USED BUDGET");
// now fetch data from database and display it in pdf
while (c1.moveToNext()) {
// get the value from database
String ex_bdgt = c1.getString(3);
String used_bdgt = c1.getString(5);
table.addCell(type);
table.addCell(ex_bdgt);
table.addCell(used_bdgt);
int temp_ex=Integer.parseInt(ex_bdgt);
ttlbud=ttlbud+temp_ex;
int temp_used=Integer.parseInt(used_bdgt);
usdbud=usdbud+temp_used;
}
// add table into document
document.add(table);
document.addCreationDate();
document.close();
I have tried Ketul Patel solution, the solution is fine in principle, but I needed to change few things in it. I changed the way I created the file in the directory, I got the idea from here, and it worked perfectly. and my final code is:
The DatabaseHelper is a class I created in my project which extends SQLiteOpenHelper. read more
public void createPdf() throws FileNotFoundException, DocumentException {
String dir = Environment.getExternalStorageDirectory()+File.separator+"myLogs";
File folder = new File(dir);
folder.mkdirs();
File file = new File(dir, "LogHistory.pdf");
Cursor c1 = database.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_LOG, null);
Document document = new Document(); // create the document
PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
Paragraph p3 = new Paragraph();
p3.add("Your Log History for \n");
document.add(p3);
PdfPTable table = new PdfPTable(4);
table.addCell("Date");
table.addCell("Start");
table.addCell("End");
table.addCell("Total");
while (c1.moveToNext()) {
String date = c1.getString(3);
String start = c1.getString(1);
String end = c1.getString(2);
String total = c1.getString(4);
table.addCell(date);
table.addCell(start);
table.addCell(end);
table.addCell(total);
}
document.add(table);
document.addCreationDate();
document.close();
}
I have completed the PDF implementation in php with the help of fpdf Tutorials. With this I also got help for Pie Charts and Bar Charts for graphical representation in my pdf. Also this format simplifies for mailing our pdf file as an attachment as it could be stored as various ways.

Categories

Resources