Display sqlite database content in pdf format in android - 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.

Related

Emojis not rendering with itextpdf

I try to generate a pdf with com.itextpdf in android / java. Basically, (text) chat messages shall be transferred to the pdf for archiving the chat.
Using com.itextpdf works fine for text only messages using the font included in com.itextpdf. Unfortunately, emojis are not covered by these fonts and therefore will not be included in the pdf file.
For including emojis a sample is given here. Following the sample code I am not able to generate a pdf file with emojis displaying. I tried different fonts like noto_emoji_regular.ttf or noto_color_emoji_compat.ttf. Some fonts end in a completely white pdf, some in funny signs like in this
screen shot.
This is my code:
public File createPdfDoc() {
final String font_path = "assets/noto_emoji_regular.ttf";
// test strings
String html = new String("<!DOCTYPE html>\n" +
"<html>\n" +
"<body>\n" +
"<span style='font-size:100px;'>πŸ˜€</span>\n" +
"<p>I will display πŸ˜‚</p>\n" +
"<p>I will display 😁 test πŸ˜…</p>\n" +
"</body>\n" +
"</html>");
String s = "\"title\":\"πŸ‘ΊTEST title value 😁\",\"text\":\"πŸ’– TEST text value.\"";
File pdfFile = null;
try {
String exportPath = new ExportProvider(weakContext.get()).getExportDirPath() + File.separator
+ generateDocTitle();
PdfWriter pdfWriter = new PdfWriter(exportPath);
PdfDocument pdf = new PdfDocument(pdfWriter);
// testing text 2 pdf
Document doc = new Document(pdf);
Paragraph p = new Paragraph();
PdfFont emoji_font = PdfFontFactory.createFont(FONT_ACCESS); //Create Pdf Font with Emoji glyphs
p.setFont(emoji_font); //add font to Paragraph
p.setFontSize(15);
p.add(new Text(String.format("Here are some emojis: %s %s", 0x1F600, encodeCodepoint(0x1F604)))); //encode unicode values
doc.add(p); //add Paragraph to document
doc.close();
/*
// testing html 2 pdf
ConverterProperties cprop = new ConverterProperties();//ConverterProperties will be used to add the FontProvider to the Converter.
FontProvider provider = new FontProvider();//The FontProvider will hold our emoji font
provider.addStandardPdfFonts();
provider.addFont("/font/noto_emoji_regular.ttf", PdfEncodings.IDENTITY_H);
cprop.setFontProvider(provider);//add provider to properties
HtmlConverter.convertToPdf(new ByteArrayInputStream(html.getBytes()), pdf, cprop);//Include ConverterProperties as argument for the #convertToPdf() method.
pdf.close();
*/
pdfFile = new File(exportPath);
} catch (IOException e) {
e.printStackTrace();
}
return pdfFile;
}
Can you give me any hint what I have to do for displaying text and emojis?
EDIT: The goal it to export chat messages including emojis to a pdf document. Any alternative idea how to do that is very welcome.

Android: Create and Download PDF files to Downloads directory

In my Android App, in one of the activity, there is a "PDF Download" button. When this button is clicked, I create a PDF and then download it to the "Downloads" directory. Following is my code which runs on the click event of the button:
public void createAndDownloadPDF()
{
try
{
PdfDocument document = new PdfDocument();
View content = this.findViewById(android.R.id.content);
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(content.getWidth(),
content.getHeight() - 20, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
content.draw(page.getCanvas());
document.finishPage(page);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdfdemo"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), pdfName);
try
{
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
document.writeTo(out);
document.close();
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Please note that I added the required WRITE permission to the MANIFEST file and also asking for the permission at runtime. So, there is no issue of permissions.
When I debug the code, I notice that "outputFile" variable holds this path:
/storage/emulated/o/Download/pdfdemo07052017121233.pdf
My users will never find above path in their mobile. So, they will have no clue where their PDF got saved. I want that when users click on "Downloads" icon on their mobile, they should see the PDF file they downloaded from the app.
So, I think if I can sort out the following line:
File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), pdfName);
my work will be done. What should be the path I use so that my PDF files get saved / downloaded in the "Downloads" directory? I researched over the internet, but did not find any concrete solution.
Try this:
File outDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
If this doesn't work, evaluate the chance of having your PDF file previously generated and saved into a folder inside your Assets folder. If this can be the case, after the above line you insert this:
copyAssets("XXX",outDir.toString());
Where "XXX" is the name of the folder inside your Assets folder which will contain the PDF file. This will copy the contents of XXX to DOWNLOADS/XXX on your device.

NoClassDefFoundError on adding image to a pdf page in PDFBox Android

Trying to write an image on a pdf page
PDDocument document = null;
File inputFile = new File(mFilePath);
document = PDDocument.load(inputFile);
PDPage page = document.getPage(0);
File image = new File("/storage/emulated/0/", "1.jpg");
PDImageXObject img = JPEGFactory.createFromStream(document, inputStream);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 100, 100);
contentStream.close();
File outputFile = new File(inputFile.getParent(), "new file.pdf");
document.save(outputFile);
document.close();
but getting this exception:
java.lang.NoClassDefFoundError: Failed resolution of: Ljavax/imageio/ImageIO;
at org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory.readJPEG(JPEGFactory.java:99)
at org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory.createFromStream(JPEGFactory.java:78)
Note: I have also tried to use
PDImageXObject img = PDImageXObject.createFromFile(image.getPath(), document);
But nothing different happened.
What can i do to add a image to a position in current page with no exception? (If you know a better soloution let me know)
Finaly, I used Android Port of PDFBox(Link to answer) and added the image to pdf using a sample code from this link:
/**
* Add an image to an existing PDF document.
*
* #param inputFile The input PDF to add the image to.
* #param imagePath The filename of the image to put in the PDF.
* #param outputFile The file to write to the pdf to.
*
* #throws IOException If there is an error writing the data.
*/
public void createPDFFromImage( String inputFile, String imagePath, String outputFile )
throws IOException
{
// the document
PDDocument doc = null;
try
{
doc = PDDocument.load( new File(inputFile) );
//we will add the image to the first page.
PDPage page = doc.getPage(0);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);
// contentStream.drawImage(ximage, 20, 20 );
// better method inspired by https://stackoverflow.com/a/22318681/535646
// reduce this value if the image is too large
float scale = 1f;
contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth()*scale, pdImage.getHeight()*scale);
contentStream.close();
doc.save( outputFile );
}
finally
{
if( doc != null )
{
doc.close();
}
}
}

Creating a PDF File in PDFBOX (from existing pdf file)

I have a 300 page PDF file. I want to create a new PDF file from my chosen pages the existing pdf file.
I have created a blank PDF File (using PDFBox ) like this:
// Create a new empty document
PDDocument document = new PDDocument();
// Create a new blank page and add it to the document
PDPage blankPage = new PDPage();
document.addPage( blankPage );
// Save the newly created document
document.save("BlankPage.pdf");
and this is how I am reading a page from pdf File.
PDDocument doc = PDDocument.load("Hello World.pdf");
PDPage firstPage = (PDPage) doc.getDocumentCatalog().getAllPages().get(67);
My question is, how do I get the contents of 'firstpage' into "blankPage.pdf".
If I can choose the x,y coordinates of the firstpage(where it is to be overlayed), it would be even better.
P.S.
The page sizes of my Hello World file are not A4.Each page is more like a thumbnail with text and shapes.So, overlaying is possible on A4. Also, I do not want to convert the files to image and then onverlay, I want the whole pdf file to be pasted as is(without converting to image first)
it turns out that iText can do the same thing.Here is the code for that :
PdfReader reader = new PdfReader("Hello World.pdf");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("RESULT.PDF"));
document.open();
PdfContentByte canvas = writer.getDirectContent();
PdfImportedPage page;
for (int i = 3; i <=6; i++) {
page = writer.getImportedPage(reader, i);
canvas.addTemplate(page, 1f, 0, 0, 1, 0, i*30-250);
}
document.close();

How to read an existing pdf file using the itextpdf.jar file in java/Android

I want to read a pdf file using Java/Android from my SD card. I imported the itextpdf5.1.1.jar file in to Eclipse. I am able to read a file if I create a new file from an existing one, like this:
public void readPdfFile(String pFilename){
try{
Document document = null;
document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(OUTPUTFILE));
document.open();
PdfReader reader = new PdfReader(pFilename);
int n = reader.getNumberOfPages();
PdfImportedPage page;
// Go through all pages
for (int i = 1; i <= n; i++) {
// Only page number 2 will be included
if (i == 1) {
page = writer.getImportedPage(reader, i);
Image instance = Image.getInstance(page);
document.add(instance);
}
}
}
catch (DocumentException e) {
// TODO: handle exception
System.out.println("Doc Exception"+ e);
}
catch (IOException io) {
// TODO: handle exception
System.out.println("IO Exception"+ io);
}
}
But I want to read the file without creating a new pdf file in my sd card. How can I do this?
Please guide me how to create a pdf reader application in Android that reads the pdf file and also allows you to enter a page number to jump to.
It is impossible to replace an existing PDF. We can able to write or manipulate anything in our PDF but it could not be replaced with the original. While using iText we can make change and save it in a new file and not in a original file, this information is available in the iText official website.
You can use awt tools like jPanel in java with iText to read a pdf file.
In Android there is a pdf viewer for reading or viewing pdf files.

Categories

Resources