How to create PDFs in an Android app? [closed] - android

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
Is there any way to create PDF Files from an Android application?

If anyone wants to generate PDFs on Android device, here is how to do it:
http://sourceforge.net/projects/itext/ (library)
http://www.vogella.de/articles/JavaPDF/article.html (tutorial)
http://tutorials.jenkov.com/java-itext/image.html (images tutorial)

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html
// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
printAttributes);
// start a page
Page page = document.startPage(0);
// 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();

A trick to make a PDF with complex features is to make a dummy activity with the desired xml layout. You can then open this dummy activity, take a screenshot programmatically and convert that image to pdf using this library. Of course there are limitations such as not being able to scroll, not more than one page,but for a limited application this is quick and easy. Hope this helps someone!

It's not easy to find a full solution of the problem of a convertion of an arbitrary HTML to PDF with non-english letters in Android. I test it for russian unicode letters.
We use three libraries:
(1) Jsoup (jsoup-1.7.3.jar) for a convertion from HTML to XHTML,
(2) iTextPDF (itextpdf-5.5.0.jar),
(3) XMLWorker (xmlworker-5.5.1.jar).
public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
if ( !path.exists() ){ path.mkdir(); }
File file = new File(path, fileName);
try{
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
// Подготавливаем HTML
String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );
// Печатаем документ PDF
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
inputStream, null, Charset.defaultCharset(), new MyFont());
document.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
The difficult problem is to display russian letters in PDF by using iTextPDF XMLWorker library. For this we should create our own implementation of FontProvider interface:
public class MyFont implements FontProvider{
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
private static final String FONT_ALIAS = "my_font";
public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }
#Override
public Font getFont(String fontname, String encoding, boolean embedded,
float size, int style, BaseColor color){
return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H,
BaseFont.EMBEDDED, size, style, color);
}
#Override
public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}
Here we use the standard Android font Droid Sans, which is located in the system folder:
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";

A bit late and I have not yet tested it yet myself but another library that is under the BSD license is Android PDF Writer.
Update I have tried the library myself. Works ok with simple pdf generations (it provide methods for adding text, lines, rectangles, bitmaps, fonts). The only problem is that the generated PDF is stored in a String in memory, this may cause memory issues in large documents.

PDFJet offers an open-source version of their library that should be able to handle any basic PDF generation task. It's a purely Java-based solution and it is stated to be compatible with Android. There is a commercial version with some additional features that does not appear to be too expensive.

Late, but relevant to request and hopefully helpful. If using an external service (as suggested in the reply by CommonsWare) then Docmosis has a cloud service that might help - offloading processing to a cloud service that does the heavy processing. That approach is ideal in some circumstances but of course relies on being net-connected.

U can also use PoDoFo library. The main goal is that it published under LGPL. Since it is written in C++ you should cross-compile it using NDK and write C-side and Java wrapper. Some of third-party libraries can be used from OpenCV project. Also in OpenCV project U can find android.toolchain.cmake file, which will help you with generating Makefile.

Related

How to Write float data into Text file in Android Working with Unity and C#

im trying to Write the data Stored in a float variable into a text file.
it works well in PC using Streamwriter
using (System.IO.StreamWriter file = new System.IO.StreamWriter();
but not on Android.
please tell me what is the way to Write it into a text file .
all i need is a similar way to write the above which works on android as well.
*collecting data from leap motion
*each frame data has to be written into Text file.
There's lots of good resources in the Unity documentation/forums for this. Look up 'Unity File I/O' and you will find links to articles that are helpful.
Here's some sample code to help you with your specific problem:
public void WriteToFile()
{
string FILE_PATH = Application.persistentDataPath + "/MYFILENAME.txt";
if (File.Exists(FILE_PATH))
{
Debug.Log(FILE_PATH + " already exists.");
return;
}
StreamWriter sr = System.IO.File.CreateText(FILE_PATH);
sr.WriteLine ("This is line 1 to be written in file.");
sr.WriteLine ("This is line 2.");
sr.Close();
}
I hope that helps!

How do I export Point Cloud Data (Project Tango)?

Just got a Project Tango Development Kit tablet and have worked through some of the demos and examples.
Some older blog posts use the log files from a "Tango Mapper" application that should be preloaded on the device.
Interactive Visualization of Google Project Tango Data with ParaView
Ologic Announces integration between ROS and Project Tango
Google Tango and ROS integration at Bosch
Mapping Hints and Tips
Unfortunately, the "Tango Mapper" application did not come preloaded on my device and I can't seem to find it on the Play Store.
Is there some other method to simply export or retrieve the PointCloud data for downstream rendering?
[Model number: yellowstone, Tango Core Version: 1.1:2014.11.14-bernoulli-release]
Not sure if you ever got to solve this, but I was able to find the APK along with a method to export using Tango updated tablet version. I successfully exported the point cloud data using the method described in this blog.
http://www.kitware.com/blog/home/post/838
Edit
Procedure download the APK or use the source code found found in the GITHUB project folder.
Once that is done boot up the app as you normally would. There will a slider record, and auto. If you slide record it will only wait until you hit the snap shot button to record the point cloud data you are currently viewing.
If you slide the auto it will continuously record the point cloud data and create files as it tracks where you are moving. Keep in mind the larger the file the larger it takes to save as a zip.
Once done slide the record and it will prompt you to save and send.
I find it easier to save to the Google Drive as other the other methods sometimes fail to send.
Once done download the free Paraview App found http://www.paraview.org/download/ load up your Point cloud data.
It should be two files one your pose data and the other point cloud. (you could individually load each data using the collapse arrow you see before importing it in.)
That will be it you will be able to see your data and actually play back the animation of you recording it because of your pose data collected.
( only wrote this out because you were looking for an easier way to export data) This is probably the easiest. You could take said data and begin to reconstructed the room based on the pose data collected.)
all credit for source code and tutorial goes to the The Kitware blog
If links are broken DM me and I will send the file to you.
APK is found here
APK DOWNLOAD
they also have listed their source code at the bottom of the blog. It is based on the tango Explorer found in the app store.
Tango Mapper is an internal tool, and it's currently not public to developers. I think the best way to log the point cloud data is using the c or java example code provided, and maybe do some small modification to log the data to a file.
c example: https://github.com/googlesamples/tango-examples-c
java example: https://github.com/googlesamples/tango-examples-java
Sparse mapping: https://www.youtube.com/watch?v=x5C_HNnW_3Q
More indoor mapping: https://www.youtube.com/watch?v=3BNOsxMZD14
It appears that more than a few of the contributors to the Tango project were hired or bought by google. As an example most of the links to code and/or articles by Hidof are MIA, only a facebook page with few clues remains. The internet archive's wayback machine has a few snapshots of their website for the curious.
Go take a look at the Java Point Cloud sample on GitHub - The function you want to look at is onXyzIsAvailable in PointCloudActivity. Extracting a few relevant lines....
public void onXyzIjAvailable(final TangoXyzIjData xyzIj) {
....
byte[] buffer = new byte[xyzIj.xyzCount * 3 * 4];
FileInputStream fileStream = new FileInputStream(
xyzIj.xyzParcelFileDescriptor.getFileDescriptor());
try {
fileStream.read(buffer,
xyzIj.xyzParcelFileDescriptorOffset, buffer.length);
fileStream.close();
} catch (IOException e) {
e.printStackTrace();
}
At this point buffer contains the point cloud data - I would strongly recommend you ship this off the device via a binary service call, as I think making the poor thing try and convert it to JSON or XML would make things slower than you would like
Thank you Mark for your advice. I am a novice programmer and it is my first time working with java...
I am interested in exporting the Tango acquired PointCloud data to a file and I would like to ask for your feedback on my approach (I created a Save button, and onClick the data would be saved to a file on an external drive). Please find the code bellow for the part that should save the xyzIj data:
#Override
public void onClick(View v) {
switch (v.getId()) {
...
case R.id.save_button:
savePointCloud();
break;
default:
Log.w(TAG, "Unrecognized button click.");
}
}
private static void savePointCloud(final TangoXyzIjData xyzIj, String file) {
File directoryName = getAlbumStorageDir(file);
FileOutputStream out = new FileOutputStream(directoryName,"text.txt");
byte[] buffer = new byte[xyzIj.xyzCount * 3 * 4];
FileInputStream fileStream = new FileInputStream(
xyzIj.xyzParcelFileDescriptor.getFileDescriptor());
int read;
while ((read=fileStream.read(buffer))!=1){
try{
out.write(buffer, 0, read);
out.close();
System.out.println("Printed to file");
}catch(IOException e){e.printStackTrace();}
}
}
public File getAlbumStorageDir(String dirName) {
if (!isExternalStorageWritable()) {
return null;
} else {
// Get the directory for the user's public downloads directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), dirName);
if (!file.mkdirs() || !file.exists()) {
Log.e(TAG, "Directory not created");
return null;
}
return file;
}
}
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if ((Environment.MEDIA_MOUNTED.equals(state)
&& Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))) {
return true;
} else {
Log.e(TAG, "External storage is not mounted READ/WRITE.");
return false;
}
}

Create video file from images in Android

I am reading found many articles and info about creating video from sequence of images. They all recommend to use ffmpeg. The thing is that this pretty complicated. There is simple way to do this without ffmpeg? I need that the result video will be readable to regular video player on the device.
Not sure what you mean by complicated. If you are not very comfortable with native layer then you might use javaCV. It provides java wrapper for ffmpeg among other open source library and works very well.
Possibly, you want to make use of the Movie. The reference is here:
http://developer.android.com/reference/android/graphics/Movie.html
And, a sample example is here:
https://code.google.com/p/animated-gifs-in-android/
You can use JCodec library.
It now supports android too.
You need to download the library and add it in your project.
here is an example of using the library:
SequenceEncoder se = null;
try {
se = new SequenceEncoder(new File(Environment.getExternalStorageDirectory(),
"jcodec_enc.mp4"));
File[] files = yourDirectory.listFiles();
for (int i = 0;i<files.length; i++) {
if (!files[i].exists())
break;
Bitmap frame = BitmapFactory.decodeFile(files[i]
.getAbsolutePath());
se.encodeImage(frame);
}
se.finish();
} catch (IOException e) {
Log.e(TAG, "IO", e);
}

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.

Read or open a PDF file using iText in 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.

Categories

Resources