Android Turtorial 2 – Creating A PDF Using the Androids KitKat Library

Most likely you’ll be generating layouts and views programmatically to create the document you wish to export to a pdf.  To do this whenever you generate a new “page” (Relative/Linear Layout) store it’s id in a Arraylist to later use.

Anyway this will be a very simple example of how to use the KitKat inbuilt function to generate pdf using an image/layout.

Download my first android game from the Play Store and give me your thoughts and feedback: Ball Drop Pop

Step 1 Create your Layout within a Layout

First thing you want to do is generate the layout(s) which you will then create an image from and then export.  You will need to use a Relative, Frame, Linear Layout. I used a relative layout to ensure the inserted text/image is placed where it needs to be. Set the height to wrap the content and the width to an appropriate size (refer to step 2). Within that layout place absolutely anything that you want anything displayed in that layout will be exported to the PDF exactly as it is in the same positions and formats.  

This can be tricky to get normalised across all devices so play around with generating views programmatically with a base dpi (dots per inch). Create a pdf class with functions like:

AddPage ()

AddText ()

AddImage ()

AddTable ()

Each adding a view to the current page/layout. With each add remember to check whether or not a new page needs to start. I have my own class which I’m currently using but it is too large to include and explain with the minimal time I have. 

Step 2 Working with the layouts size

In order to correctly convert the image onto the PDF for the paper size you want you’ll need to do some scaling.  Size your layout(s) width so that it can be proportionately stretched to fill say an A4 page.  Otherwise you’ll end up with an A4 document but with very badly scaled writing or pictures.

Step 3 Creating a path to the Folder for your File

CODE!!!!!! Up until now there’s a lot of chat above but no show of code.  Here comes the first set of simple code for creating a folder and then the file:

// The file type can be used for both files and folders the String given in the initialising call determines a path either to a file or a folder.  The variable can then be used to create, read, modify or delete the file or folder and it’s attributes.File FilesFolder = new File(Environment.getExternalStorageDirectory(), [enter folder name here]);

// Environment.getExternalStorageDirectory() will give you the path to the standard storage of the device.  This is handy as different phones can easily have varying file systems. This is the file/folders directory now the second variable will be the file/folder you are accessing or creating

File TheFile = new File(FilesFolder,  “YourFile.pdf”);

After creating the above two file variables you can then create the folder and the file by:

  1. Checking the folder doesnt exist via and If statement:

    if(!FilesFolder.exists())
  2. Creating the directory if it doesn’t: FilesFolder.mkdir();
  3. Creating the file: TheFile.createNewFile()

To avoid overwriting a file you might want to add a unique reference to the files default name.

Step 4 Setting the Parameters for the Export

The following is how you would define the PDFs properties:

// The variable types name itself is a giveaway as is the initialisersPrintAttributes printAttributes = new PrintAttributes.Builder()

// choose whether to export color or not
.setColorMode(PrintAttributes.
COLOR_MODE_COLOR)

// What page size should be used
.setMediaSize(PrintAttributes.MediaSize.
ISO_A4)

// set the margins for the page
.setMinMargins(
new PrintAttributes.Margins(10, 10, 10, 10))

// this does not actually make a difference look ahead for how to resize your canvas to fit an A4 page.
.setResolution(new PrintAttributes.Resolution(“Note3”,“myLabel”,width,height))
.build();

Step 5 Creating a Page and queuing it

This is very straight forward:

// PrintedPdfDocument will hold all the data that needs to be then converted and transferred to the PDF file created note that we apply the attributes we just created in the initialisation of the PrintedPdfDocumentPrintedPdfDocument Doc=

new PrintedPdfDocument(this.getApplicationContext(), printAttributes);

// Now you need to find out the required factor of the scaling to get your View to fill a A4 page.  This requires a float

int docX, docY; // holds the size of an A4 page

int viewX,viewY;  // holds the size of your page
float scaleX, scaleY; // holds the value the page size needs to be increased by



docY = Doc.getPageHeight(); // The height of the page you are printing on


docX = Doc.getPageWidth(); // The width of the page you are printing on


// ——————-Loop would start here for multiple pages
View con = findViewById(R.id.yourLayout); // use an arrayList to store your ids

viewY = con.getHeight();
viewX = con.getWidth();

scaleX = (float) docX/viewX; // this will be lower or higher than 1.0


scaleY = (float) docY/viewY; // higher increasing the size lower decreasing

// start a page in this case 0, if you have multiple pages you can easily use an incrementing integer and a loop

Page currentPage = Doc.startPage(page);

// draw something on the page con being the view that you’ve created  and //  scale it before drawing it

Canvas draw = currentPage.getCanvas();

draw.scale(scaleX,scaleY);
content.draw(drawThis);

// finish the page and assign it to the document to be later be transferred


Doc.finishPage(currentPage);

 

Just place the above in a loop and use your ArrayList which holds all the ids of the views that need to be printed to the document and loop through using the for each method.

Step 6 The Final Step

Writing the document to the file, at this point your loop would end:

try {
Doc.writeTo(new FileOutputStream(OutputFile));
/* self explanitory really write whats been queued in Doc to the file we create whats worth saying is that a String value required for OutputFile not a File type */


}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//close the document
Doc.close();

 

And that’s the end of that chapter…….

endofthatchapt

Get it cause………never-mind.

Hope you have found this tutorial useful if there’s any detail I have missed which you need to be able to understand all of this tutorial of mine then please by all means comment asking for that detail and I will most definitely add it.  Other people will need that information too so don’t just let it slide.

(Example of a pdf generated using the KitKat library)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s