NoClassDefFoundError on adding image to a pdf page in PDFBox Android - 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();
}
}
}

Related

Adding image from gallery and saving to pdf in adroid studio

I made an app in android studio (Java) on which is possible to fill some brief data in text boxes. Also app has two buttons, one for loading image from gallery and one for saving complete data to pdf.
I can successfully save all text data, but have problem with loaded image. Image is sucessfully loaded to app, but i dont know hot to save it to pdf. Image is loaded as an ImageView object.
Just to mention for pdf part i use itext.
Pls, help with hints or code for saving ImageVIew object to pdf file.
i had the same problem, but i can fixed.
first i changed the way i used to pick the image and replaced it with this code:
Intent getImage = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(getImage, GALLERY_REQUEST_CODE);
then, in the class onActivityResult i transformed the uri to a bitmap using this:
if(requestCode==GALLERY_REQUEST_CODE && resultCode== RESULT_OK && data!=null){
Uri imageData = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageData,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String myPath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(myPath);
then passed the bitmap to the pdf
pdf.addFoto(bitmap);
and finally, in the pdf template i used this to put the image in a table:
public void addFoto (Bitmap u) {
try{
PdfPTable tabla = new PdfPTable(1);
tabla.setWidthPercentage(60);
tabla.setSpacingBefore(10);
tabla.setSpacingAfter(10);
Bitmap bmp = u;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
PdfPCell imageCell = new PdfPCell();
imageCell.addElement(image);
tabla.addCell(imageCell);
document.add(tabla);
Look into PdfDocument
Example from the documentation
// create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());
// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());
// close the document
document.close();

Assets image to Internal storage runtime

I have converted docx to html and able to display it in webview with images. However, when I try saving the html extracted from webview to internal storage the images are not visible and are rather leaving a blank space in the saved html file.
The code for doing this as follows:
view = (WebView) findViewById(R.id.webpage);
final long startTime = System.currentTimeMillis();
final long endTime;
try {
final LoadFromZipNG loader = new LoadFromZipNG();
WordprocessingMLPackage wordMLPackage = (WordprocessingMLPackage)loader.get(new FileInputStream(new File(Environment.getExternalStorageDirectory()+"/"+getIntent().getStringExtra("textReportFileName"))));
String IMAGE_DIR_NAME = "images";
String baseURL = this.getDir(IMAGE_DIR_NAME, Context.MODE_WORLD_READABLE).toURL().toString();
System.out.println(baseURL); // file:/data/data/com.example.HelloAndroid/app_images/
// Uncomment this to write image files to file system
ConversionImageHandler conversionImageHandler = new AndroidFileConversionImageHandler( IMAGE_DIR_NAME, // <-- don't use a path separator here
baseURL, false, this);
Toast.makeText(getApplicationContext(),baseURL,Toast.LENGTH_SHORT).show();
HtmlExporterNonXSLT withoutXSLT = new HtmlExporterNonXSLT(wordMLPackage, conversionImageHandler);
html = XmlUtils.w3CDomNodeToString(withoutXSLT.export());
File filex = new File(Environment.getExternalStorageDirectory()+"/temp/"+getIntent().getStringExtra("textReportFileName").replace("docx","html"));
if(filex.exists()) {
Toast.makeText(getApplicationContext(),"File exists",Toast.LENGTH_SHORT).show();
InputStream iss = new FileInputStream(filex);
int size = iss.available();
byte[] buffer = new byte[size];
iss.read(buffer);
iss.close();
html = new String(buffer);
//html = html.substring(html.indexOf("0\" rows=\"9\">") + 16);
}
else{
}
} catch (Exception e) {
e.printStackTrace();
finish();
} finally {
endTime = System.currentTimeMillis();
}
The highlighted toast message gives the output : file:/data/data/com.tek.teksmartlab/app_images/
Also the final html file has the image tags with the src = "file:/data/data/com.tek.teksmartlab/app_images/image1.jpg" (like form)
Now I understand the path file:/data/data/com.tek.teksmartlab/app_images/ is non existent in the internal storage so HOW DO I SAVE THE IMAGES FROM THIS PATH TO INTERNAL STORAGE??
I have tried copying the image from assets folder to internal storage code but that didn't work for me.
Your url is not complete you need it to start with file:// so the whole thing would be
file:///data/data/com.tek.teksmartlab/app_images/image1.jpg

No user data box for video captured from android using mp4parser in android

I am trying to wirte metadata information using mp4parser but in my code I am getting userDataBox Empty in case of video captured by android but in case of other video (I have tested with downloaded vide) it is not empty and I was added metadata successfully, my problem is for video captured by android having empty userdatabox. Can any body help me ?
moov.getBoxes(UserDataBox.class).size()
My Code is here :
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
"MYFOLDER");
File f = new File(mediaStorageDir, "VID.mp4");
if(f.exists())
{
Toast.makeText(MainActivity.this," file found",Toast.LENGTH_SHORT).show();
}
try {
fc = new FileInputStream(f).getChannel();
// fc = new FileInputStream(f).getChannel();
isoFile = new IsoFile(fc);
String str = f.getAbsolutePath();
MovieBox moov = isoFile.getMovieBox();
// for (Box box : moov.getBoxes()) {
// System.out.println("box" + box);
// }
if(moov.getBoxes(UserDataBox.class).size()>0)
{
UserDataBox udta = moov.getBoxes(UserDataBox.class).get(0);
}else{
}
If the udta (User Data Box) is not there you can create it. You might want to have a look at the ChangeMetadata example on github.
UserDataBox userDataBox;
long sizeBefore;
if ((userDataBox = Path.getPath(tempIsoFile, "/moov/udta")) == null) {
sizeBefore = 0;
userDataBox = new UserDataBox();
tempIsoFile.getMovieBox().addBox(userDataBox);
} else {
sizeBefore = userDataBox.getSize();
}
MetaBox metaBox;
if ((metaBox = Path.getPath(userDataBox, "meta")) == null) {
metaBox = new MetaBox();
userDataBox.addBox(metaBox);
}
XmlBox xmlBox = new XmlBox();
xmlBox.setXml(text);
metaBox.addBox(xmlBox);
now you have added the boxes. Unfortunately the file contains other boxes that reference the actual video/audio samples. These reference are absolute to the beginning of the file and must be adjusted as you might have inserted data between the start of the file and the actual audio/video samples.
The needsOffsetCorrection(...) method checks if the data was really inserted between filestar and samples. correctChunkOffsets(...) then does he actual correction of the offsets stored in the stco (ChunkOffsetBox).
long sizeAfter = userDataBox.getSize();
if (needsOffsetCorrection(tempIsoFile)) {
correctChunkOffsets(tempIsoFile, sizeAfter - sizeBefore);
}
videoFileOutputStream = new FileOutputStream(videoFilePath + "_mod.mp4");
tempIsoFile.getBox(videoFileOutputStream.getChannel());
I hope that helps you a bit understanding how MP4 and metadata in MP4 is working. Good Luck!

Android - Getting, saving and retrieving images from URL

I have a database of recipes, each of which has an image.
The database can be updated from a JSON feed. I then need to retrieve any new images for a newly added recipe. I'm having issues getting an image from a URL, saving it and then updating a recipe with that image.
There are a lot of different answers on Stack Overflow and other sites. Often I can get to what I would expect to be a working point. Where images appear to be getting saved, and any debug print outs I add in show what I expect, but I cannot update my ImageView. By that I mean it remains blank.
I'm not sure if my issue is simply a poor attempt to update the ImageView, or a problem when saving the images. This code is a bit sloppy and inefficient at the moment. I've tried 10-15 variations on this from suggested other posts and have had no luck. Any help would be greatly appreciated.
Manifest
/* I have these two set (Not sure both are necessary) */
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Main frontend class
/* Create databaseHelper */
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
/* ImageView to update image of */
ImageView foodpic = (ImageView)findViewById(R.id.foodpic);
/* Check if image is already available in drawable folder */
int resID = this.getResources().getIdentifier(filename, "drawable", "mypackage.name");
if (resID == 0) {
/* If not, call function to retrieve from external storage */
newPic = db.getOutputMediaFile(origFilename);
if(newPic.exists()) {
myBitmap = BitmapFactory.decodeFile(newPic.getAbsolutePath());
foodpic.setImageBitmap(myBitmap);
foodpic.invalidate(); /* Tried with and without this */
}
}
DatabaseHelper function to retrieve image saved from URL
public File getOutputMediaFile(String filename){
/* Dir I'm (attempting) to save and retrieve images from */
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/mypackage.name/Files");
/* Create the storage directory if it does not exist */
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/* Get file extension */
String[] fileNameSplit = filename.split("\\.");
String extension = fileNameSplit[(fileNameSplit.length-1)];
/* Get filename, remove special chars & make lowercase */
int extensionIndex = filename.lastIndexOf(".");
filename = filename.substring(0, extensionIndex);
filename = filename.toLowerCase(Locale.getDefault());
filename = filename.replaceAll("[^a-z0-9]", "");
/* Re-make filename to save image as */
String mImageName="r"+filename+"."+extension;
/* Get file
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
DatabaseHelper function to save image from URL
- Called per recipe/image added to the database, if image not found in drawable folder.
public static void saveImage(String imageUrl, String destinationFile, String extension) throws IOException {
URL url = new URL (imageUrl);
InputStream input = url.openStream();
try {
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,destinationFile));
try {
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
*Formatting.
Store URL as string in DB and display it with Image Loader is more easy, but doesn't work off line ,if ur apps need internet to work, the image loader could be better.
android-loading-image-from-url-http
I ended up using this library.
It's not an ideal solution as I'd have preferred to look through this library, understand it fully and explain it for others who may need a similar answer. But for now, people attempting to do something similar should be able to use this too.
https://code.google.com/p/imagemanager/

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