Read or open a PDF file using iText in android - android

i am new to android application development.
using iText i had done the PDF creation n write on that created file
now i want to read that PDF file.
how to open or read a PDF file using iText.
Examples will be appreciable..
thenx in advance.....!!!
which is the best library to render the PDF file..????
JPedal / iText / gnujpdf or anyother.....?????

Actually, iText is only for PDF creation, it doesn't contains viewer part. So, you need to choose some another library. You can follow the link provided by Azharahmed to find some useful libraries.

You can create your own PDF Viewer using iText, you can fetch Images for the specific page and simply display that image in a Scroll View.
But for using this approach, you will have to implement an efficient cache and set the specific pages threshold that will be made on initial run and progressively.
Here is the link, that will facilitate you:
public void makeImageFromPDF throws DocumentException,
IOException {
String INPUTFILE = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/YOUR_DIRECTORY/inputFile.pdf";
String OUTPUTFILE = Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/YOUR_DIRECTORY/outputFile.pdf";
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(OUTPUTFILE));
document.open();
PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();
PdfImportedPage page;
// Traversing through all the pages
for (int i = 1; i <= n; i++) {
page = writer.getImportedPage(reader, i);
Image instance = Image.getInstance(page);
//Save a specific page threshold for displaying in a scroll view inside your App
}
document.close();
}
You can also use this link as a reference:
Reading a pdf file using iText library
I hope this helps.

Related

Show PDF file in App

I found this two possibilities to show a pdf file.
Open a webView with:
webView.loadUrl("https://docs.google.com/gview?embedded=true&url="+uri);
Open the pdf File with a extern App:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(outFile),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Both of them work. But my problem is that the pdf is for internal use only and in both examples the user could download it or save it in another folder.
I know frameworks for this in iOS dev, I looking for a solution that works with Android.
Android provides PDF API now with which it is easy to present pdf content inside application.
you can find details here
Below is the sample snippet to render from a pdf file in assets folder.
private void openRenderer(Context context) throws IOException {
// In this sample, we read a PDF from the assets directory.
File file = new File(context.getCacheDir(), FILENAME);
if (!file.exists()) {
// Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
// the cache directory.
InputStream asset = context.getAssets().open(FILENAME);
FileOutputStream output = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int size;
while ((size = asset.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
asset.close();
output.close();
}
mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
// This is the PdfRenderer we use to render the PDF.
if (mFileDescriptor != null) {
mPdfRenderer = new PdfRenderer(mFileDescriptor);
}
}
update: This snippet is from google developers provided samples.
Many libraries are available for showing pdfs within your own app.
Android PDF Viewer
VuDroid
APDFViewer
droidreader
android-pdf
mupdf
android-pdfView
For a working example using 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();
You can show the PDF in your own viewer
Tier are few open source pdf viewers you should look at:
http://androiddeveloperspot.blogspot.com/2013/05/android-pdf-reader-open-source-code.html
You can encrypt the pdf and make sure that your viewer only will be able to decrypt it.

Read PDF file from Online in Android

I want to be able to read a file hosted online in my android application. The google docs pdf viewers are effective but do not provide a good experience. The PDFViewer jar for opening the file works well for files offline but does not seem to be working for online files. Any sample which shows this.
For reading from SD card, I have found this sample to be very effective [Example of code to implement a PDF reader
Thanks
There is a pdf viewer that's working well in this case, it's RadaeePDF
To open a pdf from remote url:
Global.Init( this );
PDFHttpStream m_stream = new PDFHttpStream();
Document m_doc = new Document();
ReaderController m_vPDF = new ReaderController(this);
m_doc.Close();
m_stream.open("http://server/filename.pdf");
int ret = m_doc.OpenStream(m_stream, null);
if( ret == 0 ) {
m_vPDF.open(m_doc);
setContentView( m_vPDF );
}

How to merge several single page PDF files in to one PDF document in Android

I have single page several PDF files in my SD card. Now I need to programmatically merge those single page PDF files in to one PDF document. I have used Android PDF Writer library to create those single PDF files. How can I do that?
The iText library can merge PDF files, and reputedly there is a version of iText that works on Android.
You can combine multiple PDF Files on Android with with the latest Apache PdfBox Release.
Just add this dependency to your build.gradle:
compile 'org.apache.pdfbox:pdfbox:2.0.2'
And in an async task do this:
private File downloadAndCombinePDFs(InputStream streamToPdf1, InputStream streamToPdf2, InputStream streamToPdf3 ) throws IOException {
PDFMergerUtility ut = new PDFMergerUtility();
ut.addSource(streamToPdf1);
ut.addSource(streamToPdf2);
ut.addSource(streamToPdf3);
final File file = new File(getContext().getExternalCacheDir(), System.currentTimeMillis() + ".pdf");
final FileOutputStream fileOutputStream = new FileOutputStream(file);
try {
ut.setDestinationStream(fileOutputStream);
ut.mergeDocuments(MemoryUsageSetting.setupTempFileOnly());
} finally {
fileOutputStream.close();
}
return file;
}

Android iText addTemplate Stamp pdf form fields overtop exisiting PDF document

I am trying to open a standard PDF form from a legacy application in Android, overlay form fields using iText and pass to Adobe Reader on Android to fill out the form.
I have been able to create the TextFields manually but I would prefer to have a pdf file as a template to speed up the process and better control quality.
Here is the code I have so far, this follows the itext examples.
AssetFileDescriptor descriptor = getAssets().openFd("standardWO_Template_v1_fo.pdf");
File templateFile = new File(descriptor.getFileDescriptor().toString());
PdfReader reader = new PdfReader(intent.getData().getPath());
reader.selectPages("1");
PdfReader templateReader = new PdfReader(templateFile.getAbsolutePath());
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(file));
// Stamp the template onto the document
PdfImportedPage page = stamper.getImportedPage(templateReader, 1);
PdfContentByte cb = stamper.getOverContent(1);
cb.addTemplate(page, 0, 0);
The issue I am having is on the last line. cb.addTemplate(page, 0,0);
Eclipse reports the following error. The type java.awt.geom.AffineTransform cannot be resolved. It is indirectly referenced from required .class files
From what I have been able to tell java.awt.geom.AffineTransform will not work in Android only Java.
Is there a different way to accomplish my task or get AffineTransform to work in Android?
After some more searching I found this method. First I had to change from using the iText5.3.1 library in my android project to the droidText library.
Once I installed the droidText library was able to use the following code. (and a ctrl-o in eclipse)
File templateFile = new File(dir.getAbsolutePath() + "/templates/standardWO.pdf");
// Read the incoming file
PdfReader reader = new PdfReader(intent.getData().getPath());
// Read the template form information
PdfReader templateReader = new PdfReader(templateFile.getAbsolutePath());
// Create the stamper from the incoming file.
PdfStamper stamper = new PdfStamper(templateReader, new FileOutputStream(file));
// Import the template information
PdfImportedPage iPage = stamper.getImportedPage(reader, 1);
// get the direct content
PdfContentByte cb = stamper.getUnderContent(1);
// Add the imported page to the content
cb.addTemplate(iPage, 0, 0);
stamper.close();
Log.v(TAG, "Opening file in adobe reader: " + file.getAbsolutePath());
loadDocInReader(file);

Android fill PDF form

I have .pdf file and multiple forms are there.
I want to open my .pdf file, fill the forms and save it from Android development.
Is there any API for Android Rendering.
I found iText but I just manage to create new pdf and than i can fill form. means which .pdf file i created that will be filled out. I need to fill my form in my own .pdf.
Thanks in Advance...any help will be appreciated...
DynamicPDF Merger for Java allows you to do just that. You can take an existing PDF document, fill out the form field values and then output that newly filled PDF.
There was a recent blog post on dynamicpdf.com on setting up DynamicPDF for Java in an Android application and creating a simple PDF from it, http://www.dynamicpdf.com/Blog/post/2012/06/15/Generating-PDFs-Dynamically-on-Android.aspx.
You can easily take that example one step further and use it to accomplish your task of form filling. The following (untested) code is an example of what it would take to form fill an existing PDF on an Android device using DynamicPDF Merger for Java:
InputStream inputStream = this.getAssets().open("PDFToFill.pdf");
long avail = inputStream.available();
byte[] samplePDF = new byte[(int) avail];
inputStream.read(samplePDF , 0, (int) avail);
inputStream.close();
PdfDocument objPDF = new PdfDocument(samplePDF);
MergeDocument document = new MergeDocument(objPDF);
document.getForm().getFields().getFormField("FormField1").setValue("My Text");
document.draw("[PhysicalPath]/FilledPDF.pdf");
The native PDF support on current Android platforms (including Android P) doesn't expose any controls for filling forms. 3rd-party PDF SDKs such as PSPDFKit fill this gap and allow programmatic PDF form filling:
List<FormField> formFields = document.getFormProvider().getFormFields();
for (FormField formField : formFields) {
if (formField.getType() == FormType.TEXT) {
TextFormElement textFormElement = (TextFormElement) formField.getFormElement();
textFormElement.setText("Test " + textFormElement.getName());
} else if (formField.getType() == FormType.CHECKBOX) {
CheckBoxFormElement checkBoxFormElement = (CheckBoxFormElement)formField.getFormElement();
checkBoxFormElement.toggleSelection();
}
}
(If you click on above link there's also a Kotlin PDF form filling example.)
Note that most SDKs on the market focus on PDF AcroForms, and not the XFA specification, which has been deprecated in the PDF 2.0 spec.

Categories

Resources