Tuesday, March 25, 2014

How to Convert Memory Stream Image to PDF inside Android Applications

This technical tip shows how developers can convert Memory Stream image to PDF file inside their Android application. The Image class in Aspose.Pdf makes it possible to convert an image from various sources into PDF format. This may include an image from particular location over the hard-drive, an image from MemoryStream or an image at a web location. The ImageInfo class has a method named setMemoryData() which is used to specify MemoryStream as the image source. 

The following code snippet shows you how convert Memory Stream image to PDF file.
try {

     // Create PDF document
     Pdf pdf = new Pdf();
     // Add a section into the PDF document
     Section sec1 = pdf.getSections().add();
     byte[] fileArray = null;
     //=====================================================//
     // Get the Image contents into Byte Array
     //=====================================================//
     try {
            fileArray = getBytesFromFile(new File("/mnt/sdcard/Aspose.jpg"));
         } catch (IOException e) {
            e.printStackTrace();
         }
     // Create an image object in the section
     aspose.pdf.Image img1 = new aspose.pdf.Image(sec1);
     // Add image object into the Paragraphs collection of the section
     sec1.getParagraphs().add(img1);

     // Set the Image file type
     img1.getImageInfo().setImageFileType(ImageFileType.Jpeg);
     // Create a BinayFileStream Object to hold byte array
     BinaryFileStream bstream = new BinaryFileStream(fileArray);
     // Set the image object to use BinaySgtream object
     img1.getImageInfo().setImageStream(bstream);

     // Save the PDF file
     pdf.save("/mnt/sdcard/Image2PDF.pdf");
}catch(java.io.IOException ioe){
                               System.out.println(ioe.getMessage());
              }catch(Exception e){
                               System.out.println(e.getMessage());
              }
}
        //=====================================================//
        // Method Returns the contents of file in a byte array
        //=====================================================//
        private static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
        // Get the size of the file
        long length = file.length();
        /*
         * Ensure that file is not loarger than Integer.MAX_VALUE;
         */
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large to process");
            return null;
        }
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ( (offset < bytes.length)
                &&
                ( (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) ) {
            offset += numRead;
        }
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        is.close();
        return bytes;
        }
Overview: Aspose.Pdf for Android

Aspose.Pdf for Android is a PDF document creation & manipulation component that enables Android applications to read, write & manipulate PDF document without using any other third party application. It allows PDF compression options, table creation & manipulation, support for graph objects, extended security controls, custom font handling, add or remove bookmarks, create table of contents, add, update, delete attachments & annotations, import or export PDF form data, print PDF docs &  much more.

Tuesday, March 11, 2014

Create FloatingBox Object & Add TextFragment & Table to It inside Android Apps

This technical tip shows how developers can create a simple FloatingBox object and then add a TextFragment to its paragraphs collection inside their Android application. As a sub-class of Paragraph, a FloatingBox is a box that contains one or more paragraphs. It can be positioned by a developer but not by the page render engine. There are methods which can be used to control the position of a floating box. The positioning of FloatingBox is absolute rather than relative. A code snippet depicts the behavior of adding table inside FloatingBox is also provided this post.
The following code snippet shows how to create a simple FloatingBox object and then add a TextFragment to its paragraphs collection.

TextFragment in FloatingBox

// Instantiate Document object
Document doc = new Document();
// Add page to PDF document
Page page = doc.getPages().add();
// Create FloatingBox object
FloatingBox aBox = new FloatingBox(40, 60);
// Set left position for FloatingBox
aBox.setLeft(40);
// Set Top position for FloatingBox
aBox.setTop(80);
// Set the vertical alignment for FloatingBox
aBox.setVerticalAlignment(com.aspose.pdf.VerticalAlignment.Bottom);
// Set Horizontal alignment for FloatingBox
aBox.setHorizontalAlignment(com.aspose.pdf.HorizontalAlignment.Center);
// Add text fragment to paragraphs collection of FloatingBox
aBox.getParagraphs().add(new TextFragment("main text"));
// Set border for FloatingBox
aBox.setBorder(new BorderInfo(15 /*BorderSide.Box*/));
// Set background color for FloatingBox
aBox.setBackgroundColor(com.aspose.pdf.Color.getYellow());
// Add FloatingBox to paragraphs collection of page object
page.getParagraphs().add(aBox);
// Set background of PDF page
page.setBackground(com.aspose.java.awt.Color.LIGHT_GRAY);
// Save the PDF document
doc.save(Environment.getExternalStorageDirectory().getAbsolutePath()+"/FloatingBox.pdf");

Table inside FloatingBox

As table is a paragraph level object, so it can also be added to the FloatinBox class' paragraphs collection. The following code snippet depicts the behavior of adding table inside FloatingBox.
// Instantiate Document object
Document doc = new Document();
// Add page to PDF document
Page page = doc.getPages().add();
// Create FloatingBox object
FloatingBox aBox = new FloatingBox(200, 100);
// Trim the contents exceeding FloatingBox dimensions
aBox.isExtraContentClip(true);
// Specify if you need to repeat the FloatingBox
aBox.isNeedRepeating(false);
// Set left position for FloatingBox
aBox.setLeft(40);
// Set top position for FloatingBox
aBox.setTop(80);
// Set the vertical alignment for FloatingBox
aBox.setVerticalAlignment(com.aspose.pdf.VerticalAlignment.Bottom);
// Set horizontal alignment for FloatingBox
aBox.setHorizontalAlignment(com.aspose.pdf.HorizontalAlignment.Center);
// Set border for FloatingBox
aBox.setBorder(new BorderInfo(15 /*BorderSide.Box*/, com.aspose.pdf.Color.getBlack()));
// Set background color for FloatingBox
aBox.setBackgroundColor(com.aspose.pdf.Color.getYellow());
// Add FloatingBox to paragraphs collection of page object
page.getParagraphs().add(aBox);
// Instantiate Table object
com.aspose.pdf.Table table = new com.aspose.pdf.Table();
// Set width of table columns
table.setColumnWidths("100 100");
// Create a loop object
for (int i = 1; i <= 20; i++)
{
    // Create a new row object and add it to table object
    Row row = table.getRows().add();
    // Add cell to cells collection of newly added row object
    row.getCells().add("Columns 1, line " + i);
    // Add another cell object
    row.getCells().add("Columns 2, line " + i);
}
// Add table to paragraphs collection of FloatingBox
aBox.getParagraphs().add(table);
// Save the PDF document
doc.save(Environment.getExternalStorageDirectory().getAbsolutePath()+"/FloatingBox.pdf");

Overview: Aspose.Pdf for Android

Aspose.Pdf for Android is a PDF document creation & manipulation component that enables Android applications to read, write & manipulate PDF document without using any other third party application. It allows PDF compression options, table creation & manipulation, support for graph objects, extended security controls, custom font handling, add or remove bookmarks, create table of contents, add, update, delete attachments & annotations, import or export PDF form data, print PDF docs &  much more.