How to open pdf file using iText in Android? - java

I'm new in Android . I'm implementing PDF document using iText in Android . I want to read PDF document in my application. I don't have an idea how to access PDF doc in my app. I have created but when I run the application I get exception for FileNotFoundException and I also import a PDF file in SD card through DD-MS. But the PDF file does not open in Android. Here is my code:
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.codec.Base64.InputStream;
public class MainActivity extends Activity
{
private static String FILE = "xyz.pdf";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager assetManager = getAssets();
InputStream istr = null;
PdfReader reader = null;
String str = null;
int n = 0;
try
{
istr =(InputStream) assetManager.open("xyz.pdf");
reader=new PdfReader(istr);
n=reader.getNumberOfPages();
Log.e("n value:","-> " +n);
str=reader.getPageContent(2).toString();
}
catch(Exception e)
{
e.printStackTrace();
}
TextView tv = (TextView) findViewById(R.id.textOne);
tv.setText(str);
}
}

As far as i know,iText is only for PDF creation, it doesn't contain viewer part.It is a parser, not a renderer. So you need to choose some another library to view pdf.But theare are some excellent code example in SO which you can view whether it meets your requirement..
How to render PDF in Android
Reading a pdf file using iText library
You can try other solution rather than iText..
- Render a PDF file using Java on Android
- http://andpdf.svn.sourceforge.net/viewvc/andpdf/trunk/
And an excellent working code last of all..
- Example of code to implement a PDF reader

We can Extract data from iText. Here i am extracting text from PDFs file and showing on Edit-text :
String path = data.getData().getPath();
File f = new File(path);
static PdfReader read;
read = new PdfReader(new FileInputStream(f));
PdfReaderContentParser parser;
parser = new PdfReaderContentParser(read);
StringWriter strw;
strw = new StringWriter();
TextExtractionStrategy stretegy;
stretegy = parser.processContent(j, new SimpleTextExtractionStrategy());
strw.write(stretegy.getResultantText());
String da = strw.toString();
edt1.setText(da);

Related

How to open pdf file inside my app (android studio, JAVA) from firebase storage link

I have pdf file stored on my firebase storage, and its link in firebase real-time database, how can I open it inside my android app (android studio, JAVA). Not using INTENT , but directly inside my app.
You can use android-pdfView, see this blog post.
It demonstrates the basic usage of the library to display pdf onto the view with vertical and horizontal swipe.
pdfView = (PDFView) findViewById(R.id.pdfView);
pdfView.fromFile(new File("/storage/sdcard0/Download/pdf.pdf")).defaultPage(1).enableSwipe(true).onPageChange(this).load();
There are also other libraries like Android PDF Viewer,
VuDroid etc.
Also Android API 19 provides feasibility now to present pdf content inside an app and thus no need of 3rd party SDKs.
you can find details here.
If you want to load the file using a URL then you can use a webview.
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + pdf);
Found the answer with little research :-
no need of webview or Intent which opens another app
Library :-
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
xml code :-
<com.github.barteksc.pdfviewer.PDFView
android:visibility="visible"
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA code :-
{
String pdfurl="firebase_access_token_of_pdf_file";
pdfView = (PDFView) findViewById(R.id.pdfView);
new RetrivePDFfromUrl().execute(pdfUrl);
}
// create an async task class for loading pdf file from URL.
class RetrivePDFfromUrl extends AsyncTask<String, Void, InputStream> {
#Override
protected InputStream doInBackground(String... strings) {
// we are using inputstream
// for getting out PDF.
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
// below is the step where we are
// creating our connection.
HttpURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
// response is success.
// we are getting input stream from url
// and storing it in our variable.
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
// this is the method
// to handle errors.
e.printStackTrace();
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
// after the execution of our async
// task we are loading our pdf in our pdf view.
pdfView.fromStream(inputStream).load();
}
}
}

Scale image with Vaadin and Java

I have following code to upload an image and show it on the webpage
// Show uploaded file in this placeholder
final Embedded image = new Embedded("Uploaded Image");
image.setVisible(false);
// Implement both receiver that saves upload in a file and
// listener for successful upload
class ImageUploader implements Receiver, SucceededListener {
public File file;
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File(tmp_dir + "/" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
return null;
}
return fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
// Show the uploaded file in the image viewer
image.setVisible(true);
image.setSource(new FileResource(file));
}
};
ImageUploader receiver = new ImageUploader();
// Create the upload with a caption and set receiver later
Upload upload = new Upload("Upload Image Here", receiver);
upload.setButtonCaption("Start Upload");
upload.addSucceededListener(receiver);
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, image);
The problem is, it shows the full resolution and I want to scale (so it remains proportional) it down to 180px width. The picture also needs to be saved as the original filename_resized.jpg but I can't seem to get it to scale. Several guides on the web talk about resizing (but then the picture gets distorted) or it gives some issues with Vaadin.
Update:
Added the scarl jar (from this answer)) because it would be easy-peasy then by using following code:
BufferedImage scaledImage = Scalr.resize(image, 200);
but that gives following error:
The method resize(BufferedImage, int, BufferedImageOp...) in the type Scalr is not applicable for the arguments (Embedded, int)
and I cannot cast because Cannot cast from Embedded to BufferedImage error
Update: with following code I can cast to the right type
File imageFile = (((FileResource) (image.getSource())).getSourceFile());
BufferedImage originalImage = ImageIO.read(imageFile) ;
BufferedImage scaledImage = Scalr.resize(originalImage, 200);
but now I can't show the image..
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, scaledImage);
because of error The method addComponents(Component...) in the type AbstractComponentContainer is not applicable for the arguments (Upload, BufferedImage)
You cannot use Vaadin objects directly with a third-party tool such as Scalr without adapting one to the other. "Embedded" is a Vaadin class whereas SclaR expects a "BufferedImage".
So, you first need to extract the File object from the Embedded object:
File imageFile = ((FileResource)(image.getSource()).getSourceFile();
Then, load it into the BufferedImage using ImageIO, such as explained in the link you pointed at ( What is the best way to scale images in Java? )
BufferedImage img = ImageIO.read(...); // load image
Then, you have the BufferedImage object you were looking for.

Download to folder/files android apps

my problem is that I use in my practice are pdf files. I did not add them into my application. I want pdf files from ftp or a URL to download it. I have no idea about the solution. I've tried a lot ftp code and URL code. All I want, when you pressed the button of the sdcard files from a URL or FTP address to get a download. Thanks for your help.
this code is working for me
public void onClick(View v) {
PrintAttributes printAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
setResolution(new PrintAttributes.Resolution("zooey", PRINT_SERVICE, 300, 300)).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).
build();
PdfDocument document = new PrintedPdfDocument(DynamicPDFHelloWorld.this, printAttrs);
// crate a page description
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300, 300, 1).create();
// create a new page from the PageInfo
PdfDocument.Page page = document.startPage(pageInfo);
// repaint the user's text into the page
View content = findViewById(R.id.textarea);
content.draw(page.getCanvas());
content.draw(edt.getText().toString().);
// do final processing of the page
document.finishPage(page);
// Here you could add more pages in a longer doc app, but you'd have
// to handle page-breaking yourself in e.g., write your own word processor...
// Now write the PDF document to a file; it actually needs to be a file
// since the Share mechanism can't accept a byte[]. though it can
// accept a String/CharSequence. Meh.
try {
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/pruebaAppModerator.pdf");
FileOutputStream fos = new FileOutputStream(f);
document.writeTo(fos);
document.close();
fos.close();
} catch (IOException e) {
throw new RuntimeException("Error generating file", e);
}
}
});

How to Create android supported video file (e.g. mp4) using InputStream object in Android

In my Android app I'm downloading Video file using Quickblox API, on successful download I'm getting file content in the form of InputStream object now, using that InputStream object I wants to create android supported Video file and stored it on to the SDCard but I don't know how to create Video file using InputStream object. Please see the following code where I'm getting InputStream object.
QBContent.downloadFileTask(fileId, new QBEntityCallbackImpl<InputStream>()
{
#Override
public void onSuccess(InputStream inputStreamObject, Bundle params)
{
// TODO Auto-generated method stub
super.onSuccess(inputStreamObject, params);
});
}
Please help. Thank you..!
If the inputStreamObject is the content of an mp4 file, you could simply save the input stream to a file. That's your mp4 .
public static final String PREFIX = "myMusicfile";
public static final String SUFFIX = ".mp4";
public static File stream2file (InputStream in) throws IOException {
final File tempFile = File.createTempFile(PREFIX, SUFFIX);
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
}
return tempFile;
}
Hope it help :)
Thanks

JDom on Android: error opening trace file: No such file or directory

I don't understand why I'm getting this error, I'm trying to write to a file, not read from it. At first I got an error because I didn't put a jar in the libs folder, now I am getting this error. Here's my code, help would be appreciated! :)
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
writeXML();
}
private void writeXML() {
try{
Document doc = new Document();
Element theRoot = new Element("tvshows");
doc.setRootElement(theRoot);
Element show = new Element("show");
Element name = new Element("show");
name.setAttribute("show_id", "show_001");
name.addContent(new Text("Life On mars"));
Element network = new Element("network");
network.setAttribute("country", "US");
network.addContent(new Text("ABC"));
show.addContent(name);
show.addContent(network);
theRoot.addContent(show);
// - -
Element show2 = new Element("show");
Element name2 = new Element("show");
name2.setAttribute("show_id", "show_002");
name2.addContent(new Text("Life On mars"));
Element network2 = new Element("network");
network2.setAttribute("country", "US");
network2.addContent(new Text("ABC"));
show2.addContent(name2);
show2.addContent(network2);
theRoot.addContent(show2);
XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
xmlOutput.output(doc, new FileOutputStream(new File("C:\\Users\\jmckay\\Desktop\\jdomMade.xml")));
TextView tv = (TextView)findViewById(R.id.text);
tv.setText("done");
}catch(Exception e){
e.printStackTrace();
}
}
It looks like you're trying to save to a Windows file address, which you can't do from an Android device (emulated or otherwise). You can use openFileOutput to get a FileOutputStream to write to a file in internal storage (specific to your app):
xmlOutput.output(doc, openFileOutput(yourFilename, Context.MODE_PRIVATE));
Have a look at this developer guide on Storage Options, in particular Internal and External Storage.

Categories