Archive for the ‘Web Development’ Category

Hello Script for PHP

Saturday, March 15th, 2008

In the last post I introduced the concept of ‘Hello Script’ - a file that contains the most commonly used elements of a programming language so that it can be used as a cheat sheet when working with that language. I thought I can elaborate on that concept by creating Hello Scripts for all the languages that I am familiar with.

Let’s start with PHP - I already provided this as an example for the last post. Here is the entire PHP Hello Script…


<?php
// Printing(IO)
print "Hello World!\n";

// Variables, concatenation
$name = 'Binny';
$year = 2008;
print "Hello, " . $name . " - welcome to " . $year . "\n";

//If,else conditions
if ($year > 2008) {
	print "Welcome to the future - yes, we have flying cars!";
}
else if($year < 2008) {
	print "The past - please don't change anything. Don't step on any butterflies. And for the sake of all that's good and holy, stay away from your parents!";
}
else {
	print "Anything wrong with your time machine? You have not gone anywhere, kiddo.";
}
print "\n";

// For loop
for($i=0; $i<3; $i++) {
	print "$i) Hi there!\n";
}

//Numerical Array, While
$rules = array(
	'Do no harm',
	'Obey',
	'Continue Living'
);
$i = 0;
while($i<count($rules)) {
	print "Rule " . ($i+1) . " : " . $rules[$i] . “\n”;
	$i++;
}

// Associated array, foreach
$associated = array(
	‘hello’	=>	‘world’,
	‘foo’	=>	‘bar’,
	‘lorem’	=>	‘ipsum’
);
foreach($associated as $key => $value) {
	print “$key: $value\n”;
}

// Using Join and Split
$csv_values = explode(’,', “hello,world,how,are,you\n”);
print implode(”:”, $csv_values);

// Function, argument, return, call
function hello($name) {
	return “Hello ” . $name;
}
$hello_string = hello(”Binny”);

// One for the OOP fanboys - Class, members, object and stuff.
class Movie {
	public $name = ”;
	public $rating = 0;

	function __construct($name) {
		$this->name = $name;
		$this->rateMovie();
	}
	function rateMovie() {
		$this->rating = (strlen($this->name) % 10) + 1; //IMDBs rating algorithm. True story!
	}

	function printMovieDetails() {
		print “Movie : {$this->name}\n”;
		print “Rating : ” . str_repeat(’*', $this->rating) . “({$this->rating})\n\n”;
	}
}
//Create the object
$ncfom = new Movie(”New Country for Old Men”); //It’s a sequel!
$ncfom->printMovieDetails();

// File IO
// File reading, easy method…
$contents = file_get_contents(’Hello.php’);
print “Hello has ” . strlen($contents) . ” chars\n”;
// Writing to a file
$file_handle = fopen(’/tmp/hello.txt’, ‘w’);
fputs($file_handle, “Hello World”);
fclose($file_handle);

// Command Executing
print `ls`; //Execute the command ‘ls’ and print its output
print “\n”;

// Regular Expressions
$string = “Hello World”;
if(preg_match(’/^Hell/’, $string)) print “Yup - its evil\n”;
print preg_replace(’/l([^l])/’, “$1″, $string); //Remove an ‘l’ from both words. Should print ‘Helo Word’

/*
 * Specialized code
 */
// Database connectivity(native)
mysql_connect(’localhost’, ‘root’, ”) or die(”Cannot connect to the Database server”);
mysql_select_db(’Data’) or die(’Could not find a database called “Data”‘);

// Executing Query
$sql_handle = mysql_query(’SELECT name,url,description FROM Comment LIMIT 1′) or die(’Query Error: ‘ . mysql_error());
while($row = mysql_fetch_assoc($sql_handle)) {
	print “Name	:	$row[name]\n”;
	print “URL	:	$row[url]\n”;
	print “Desc	:	$row[description]\n\n”;
}
/* Just a note here - if you are going to use PHP with database in a production
 * system(and you will, trust me), use a Database abstraction layer rather than
 * the above mentioned native methods.
 */

print $_REQUEST['username']; // Method to get the value of the field ‘username’ after a form submit. Will not work at CLI execution

Save this to a file and keep it around for future reference - if you are just starting out with PHP

Coming up next - Python Hello Script.

Learning a New Programming Language: The ‘Hello World’ Method

Thursday, March 6th, 2008

Hello World Learning

Learning a new programming language is fun - and essential if you want to stay competitive. I try to learn new languages all the time(my latest target is Haskell). As a result, I have a system to make learning new languages easier. This is for people who already know a programming language and want to learn another one.

Requirements

What you must have…

The interpreter/compiler of the language you are learning
You must be able to run the program after writing it.
Language reference manual/documentation
Usually found at the site of the language. Put a shortcut to that on your desktop - because you will be using this all the time.
An easy to follow tutorial
Search for it in Google. If you find one and its hard to follow, ditch it and get another. You may not need this - as manual for most languages have a tutorial in them.
A ‘todo’ project that you cannot live without
This is what forces you to learn the language - more on this later.

What I would recommend you have…

Having this will help you learn - but its not necessary.

A Net Connection
You may want to ask your doubt on the IRC channel. Or on a forum. Or to google the error message you got.
A Decent IDE
This may make your job easier - but if you have notepad, that’s enough.

What you don’t need

Books on the language
You may need a book to master the language - but you don’t need one to learn it.
A Teacher
Its helpful to have someone to clarify the doubts you may have - but no one can teach you anything you cannot learn yourself.

The Hello World Script

First you have to create the ‘hello world’ application. This is more than just ‘print “Hello World”‘ - it will act as a cheatsheet for you until you familiarize yourself with the language. The point of this application is to use all the most commonly used elements of a language and putting it in a single place so that you can refer to it later.

Your first job is to go to the tutorial, the manual and the internet until you create the Hello World application with the following stuff in it. I will provide an example - how the ‘hello world’ application will look in PHP.

After each step run the application and make sure it works.

Print “Hello World\n”

Why do you think we call it a hello world application? Write the code to print a string ‘hello world’ and save it to a file. Now run it using the interpreter - and make sure it works - see it in action.


// Printing(IO)
print "Hello World!\n";
	
Comments

Put a single line comment(like //) on top of the “print ‘hello world’” code and if your language supports it, a multiline comment(/* - */) as well. Run the script to make sure the comments work as advertised.


// Single line comment.
/*
Mulitline comment.
*/
	

I was just kidding about running the script to test the comments - you did’nt do it, did you?

Use a variable(a string and an integer) and a concatenation operator.

Create a variable called name(string) - and give it your name as the value. Create another integer variable and give it the current year. You don’t have to find it programatically - just put it as 2008 or something. Now you have to print out the a string “Hello, <name> - Welcome to year <$year>”. This string will let you concatenate two different type variable to a string - and it makes me feel like a time traveler ;-).

Yeah - the value of variable name should appear at <name>. Use the concatenation operator if possible - in PHP, write

print "Hello, " . $name . " - welcome to year " . $year;

instead of

print "Hello, $name - welcome to year $year";

This is because different languages have different concatenation operators. The other stuff is the same almost universally. + refers to addition. - refers to subtraction. * is multiplication. My point is that if you know the operators for one language, you know the operators for almost all languages. But the concatenation operator differs from language to language - its ‘+’ in javascript, ruby. Its ‘.’ in Perl, PHP, etc.

There are exceptions to this rule - ‘=’ is the equality operator in SQL while it all other language its ‘==’. The assignment operator is ‘:=’ in pascal - in all other it is ‘=’. If you notice any difference in any operator write some code using that operator in this section.

Use if/else if/else

Create something like this pseudo code…

if (year > 2008) {
	print "Welcome to the future - yes we have flying cars!"
}
else if(year < 2008) {
	print "The past - please don't change anything. Don't step on any butterflies. And for the sake of all that's good and holy, stay away from your parents!"
}
else {
	print "Anything wrong with your time machine? You have not gone anywhere, kiddo."
}

In PHP, this section will look like this…

//If,else conditions
if ($year > 2008) {
	print "Welcome to the future - yes, we have flying cars!";
}
else if($year < 2008) {
	print "The past - please don't change anything. Don't step on any butterflies. And for the sake of all that's good and decent, stay away from your parents!";
}
else {
	print "Anything wrong with your time machine? You have not gone anywhere, kiddo.";
}
print "\n";
	

If you use switch(and the new language supports switch), you can write an example of switch here.

Print ‘Hi there!’ 3 times using a for loop

A PHP example of using for loop(my all time favorite loop)…

// For loop
for($i=0; $i<3; $i++) {
	print "$i) Hi there!\n";
}
	
Create a list(array) and iterate through it using while/for/foreach loop.

I am using a while loop here - to keep things different…


//Numerical Array, While
$rules = array(
	'Do no harm',
	'Obey',
	'Continue Living'
);
$i = 0;
while($i<count($rules)) {
	print "Rule " . ($i+1) . " : " . $rules[$i] . “\n”;
	$i++;
}	
Create a hash(associative array) and iterate through it.

If the language you are going to learn have ‘foreach’, this maybe the best time to use it…

// Associated array, foreach
$associated = array(
	'hello'	=>	'world',
	'foo'	=>	'bar',
	'lorem'	=>	'ipsum'
);
foreach($associated as $key => $value) {
	print "$key: $value\n";
}
Create a function with an argument and a return.

If you need, you can create an example for call by reference, optional arguments, default argument value, variable argument count etc. as well - but they are not essential. Make sure you include the code to call a function as well.

// Function, argument, return, call
function hello($name) {
	return "Hello " . $name;
}
$hello_string = hello("Binny");

Optional Code

I don’t usually included some of these in my ‘hello world’ scripts - but they can be useful in some cases. Some may find them useful - so if you think you are going to use any of these, include it in your file.

Class, Objects, Member variables and functions

If you are a big fan of OOP, create the code for a class. Make sure it has all the following elements…

  • At least one member variable
  • At least two member functions
  • Access the member variable and the other function from within a member function.
  • Create an object of this class
  • Call a member function using the object.
// One for the OOP fanboys - Class, members, objects and stuff.
class Movie {
	public $name = '';
	public $rating = 0;

	function __construct($name) {
		$this->name = $name;
		$this->rateMovie();
	}
	function rateMovie() {
		$this->rating = (strlen($this->name) % 10) + 1; //IMDBs rating algorithm. True story!
	}

	function printMovieDetails() {
		print "Movie : {$this->name}\n";
		print "Rating : " . str_repeat('*', $this->rating) . "({$this->rating})\n\n";
	}
}
//Create the object
$ncfom = new Movie("New Country for Old Men"); //It's a sequel!
$ncfom->printMovieDetails();
File IO

Include this code - it is sure to come in useful someday. Unless you are learning JavaScript.

// File IO
// File reading, easy method...
$contents = file_get_contents('hello.php');
// Writing to a file
$file_handle = fopen(’/tmp/hello.txt’, ‘w’);
fputs($file_handle, “Hello World”);
fclose($file_handle);
	
Command Execution

I tend to include this - but it may be unnecessary for you.

// Command Executing
print `ls`; //Execute the command 'ls' and print its output
Regular Expressions

I always include them - I am a big fan of regular expressions. I have lost count of how many times they have saved the day.

// Regular Expressions
$string = "Hello World";
if(preg_match('/^Hell/', $string)) print "Yup - its evil\n";
print preg_replace('/l([^l])/’, “$1″, $string); //Remove an ‘l’ from both words. Should print ‘Helo Word’
	

Specialized Code

The language you learn may have a specialized field which we may have not used yet. If so, put it down here.

If you are learning javascript, write some code to access DOM nodes here. If you are using PHP, database connectivity will go well here. If you are learning any web server side languages, write the code to fetch the POST/GET request values. For PHP, it may look something like this…


// Database connectivity(native)
mysql_connect('localhost', 'root', '') or die("Cannot connect to the Database server");
mysql_select_db('Data') or die('Could not find a database called "Data"');

// Executing Query
$sql_handle = mysql_query('SELECT name,url,description FROM Comment LIMIT 1') or die('Query Error: ' . mysql_error());
while($row = mysql_fetch_assoc($sql_handle)) {
	print "Name	:	$row[name]\n”;
	print “URL	:	$row[url]\n”;
	print “Desc	:	$row[description]\n\n”;
}
// Just a note here - if you are going to use PHP with database in a production system(and you will, trust me), use a Database abstraction layer rather than the above mentioned native methods.

print $_REQUEST['username']; // Method to get the value of the field ‘username’ after a form submit. Will not work at CLI execution
	

Project

Next thing you need is a project - which you are going to build using the new language. Some points that you have to look for when choosing the new project…

  1. It should not be a huge project.
  2. At the same time, it should not be something trivial.
  3. There must be something about the project which would force you to finish it.

The third point needs a little explaining. You should not just pick any project that pops into your mind. It must be something that you need - something you could not live without. If it is important to you, you will have a motivation to finish the project. Otherwise, you will drop the project at the first sign of trouble. But if its important to you, you will spend more time on it - you will look at documentation, post the problem in forums, ask others in IRC channels. And eventually, you will fix the problem. And you will finish the project.

While working on the project, keep the ‘hello world’ open - you will find yourself referring to it often.

Alertle Launched

Sunday, February 10th, 2008

Alertle Screenshot

I am one of the geeks behind Alertle. Its a web based RSS Reader. I am responsible for a good amount of the JavaScript areas of this app :-)

Features

Single Page Application
The entire application is contained in a single page - everything is done through Ajax. I will not advice that you make something like this(its a maintenance nightmare) but I can say one thing about it - its Cool. With a capital ‘C’.
Keyboard Shortcuts
I got the idea of creating a Keyboard Shortcut Library for JavaScript when I was working on this feature.
Autoplay
You can view articles as you are viewing a slideshow if you enable this.
Feedpacks
You can bunch a group of feeds together into a feedpack - and see all the posts from such a group together.
Sharing
You can share your feedpacks with other users

Perfect for High Volume Feeds

There is one major feature that sets Alertle appart from other RSS readers - it does not tell you if a post is read or not. Yeah, first you will think its a missing feature - but its not. I have used a lot of feed readers - once you subscribe to a couple of high volume feed - like say, BoingBoing or Slashdot or something, you can say goodbye to your sanity. It creates so many new items that the only way of staying away the mess is to click on the ‘Mark all as read’ button once every four seconds. You know what I mean - I am sure you have unsubscribed from many feeds for this reason.

With alertle, you can subscribe all these high volume feeds. And there is no pressure to view all the posts.

If you are an info junkie, I can guaranty that your will get lost for hours in Alertle.

Problems

IE is not Supported

We are still working on this - and due to deadline constraints, we decided to release Alertle without IE support. So if you are an IE user, I am sorry - but What in the World are you Doing? Ditch that terrible browser and get a real browser right now!

If we can get a few people to switch to firefox before we add support for IE, I will say that Alertle gone beyond and above the call of duty to make the web a better place! ;-)

Posts don’t have a Read Flag (pun unintended)

Um., yeah, I know - this is both an advantage and a disadvantage. This will prevent me from using Alertle for all my feeds. For my must-read feeds, I will still be using Google Reader. For the high volume stuff, I will use Alertle.

Getting to Know Alertle

So, what are you waiting for? Head over to Alertle and sign up for an account. Its FREE!

But if you are still unconvinced, here is a demo…

Links

Defining Web 2.0 - At 3 Levels

Wednesday, January 23rd, 2008

Web 2.0

Web 2.0 - almost everyone have heard the term - but few are sure about its meaning. Unfortunately, it cannot be defined easily. People in different fields have their own unique definitions for the term. In this article, I will attempt to define the term at three different level - the Philosophy, the Technology and the Design.

Disclaimer: Before anyone reacts violently to the term Web 2.0, let me make myself very clear…
Web 2.0 is an ambiguous buzz word. It has been used and abused so many times that it does not have a consistent meaning - so people are free to interpret it as they see fit. And this is how I interpret it.

Philosophy

The design philosophy of a web site can make it a Web 2.0 site. This is perhaps the key difference between a Web 1.0 site and a Web 2.0 site…

Web 1.0 is a web site where there is a one way communication between the web master to the visitor. A Web 2.0 site is a site where the visitors can communicate with each other.

For example, compare the Encyclopedia Britannica to Wikipedia. In Encyclopedia Britannica, the web master creates the content and gives it to the visitor - the visitor has no way of talking back. But in Wikipedia, the visitor create the content for other visitors.

Technology

The keyword here is “Internet as a platform”. In Web 2.0, the net became the platform rather than just a data transfer mechanism. For a simple example, when you visit a site, the videos in it come from YouTube, the images from Flickr, the search is done using Google API and you can bookmark pages using the API from del.icio.us.

Some technologies that are described as Web 2.0…

  • Ajax
  • Valid Markup
  • Microformats
  • Tagging, Tag Clouds
  • APIs
  • Feeds
  • Mashups

Some features that makes a technology Web 2.0…

Speed
For example, Ajax makes simple tasks much faster.
Ease of Use
A good example of this is Tagging. It is a much easier approach when compared to hierarchies.
Enabling Mashups
APIs, Feeds, etc. makes this possible.
Bringing Web Apps closer to the Desktop
Ajax, AIR, etc.

Design

This is perhaps the only area where the term Web 2.0 can be defined with a reasonable level of accuracy. A site with a Web 2.0 design is one that has at least some of these elements…

Simple Design

Stonewall

Lots of white space

Browse Happy

Nice Icons

37Signal Icons

Violators/Badges/Star Flashes

A List Apart Violator

Big Fonts

37Signal Font

Gradients

Stonewall

Reflections

Curve 2 Reflections

Shadows

Shadows

And More…

Web 2.0 Design Style Guide

For More Information

Kerala BarCamp 2 - In Cochin

Thursday, January 10th, 2008

Barcamp Logo

Following the success of the first barcamp in Kerala, we are organizing a second one. This time it will be at Cochin. The date and venue has not been decided yet - we want it to be decided by the community.

For those of you who don’t know what a BarCamp is, here is the Wikipedia definition

BarCamp is an international network of user generated conferences - open, participatory workshop-events, whose content is provided by participants - often focusing on early-stage web applications, and related open source technologies, social protocols, and open data formats.

Attending

If you are in or around Cochin at the end of January 2008, consider coming to the event. If you wish to attend, please add your name to this wiki page.
BarCamp Kerala 2. You can do that by filling out the following form…






Sessions

The sessions are decided and presented by the members themselves - here is a list of the proposed sessions(so far)…

Visual Programming Language, Demo
by Kenney Jacob
Search Engine Marketing
by Mani Karthik
Xtend IVR - A RAD Toolkit for Telephony
by Jayakrishnan K
Visual Studio 2008 - What’s in it for me?
by Jadeja Dushyantsinh
SAAS - Software As A Service
by Linoy Joseph

There are some more proposed sessions.

People

I hope I can meet my fellow Cochin bloggers at this event. Anand and Mani Karthik has promised to come. I hope Nirmal will be there too.

More Details Available at…

Installing the acts_as_taggable Rails Plugin

Thursday, December 20th, 2007

You don’t have to write a lot of code to get tagging support in your Ruby on Rails application - you just have to install a plugin. This is how you install the ‘acts_as_taggable’ plugin…

First go to the Ruby on Rails application folder and open a terminal at that location. Now run this commad…

ruby script/plugin install acts_as_taggable

If your have previously installed some plugins from the same repository, that command will work. If not, you will get this error…

Plugin not found: ["acts_as_taggable"]

This is because the ‘acts_as_taggable’ plugin is not in any of the repositories you check. To see the all the repositories on your check list, run this command…

ruby script/plugin list #Shows the list of all the repositories you check.

To add new repositories to your list, you have to run this command…

ruby script/plugin discover

This will shows a list of repositories - just press ‘y’ to select all the repositories you need. I added every repository in the list.

Now run the first command again…

ruby script/plugin install acts_as_taggable

Installing the Gem

The above instructions are for installing the acts_as_taggable plugin - not the acts_as_taggable gem. To install the gem run the command…

gem install acts_as_taggable

Related Links

A Secret Source for Great Free Icons for your Desktop and Web Apps

Wednesday, December 5th, 2007

Desktop and Web application needs icons. Icons make the app more usable than an all-text application. If you are building a desktop application, your framework may provide some stock icons. But if you are making a web application, you will need external icons.

I have seen a lot of pages that lists many icon sets…

But when I want some icons I have a better place to look.

KDE and Gnome Icon themes.

I prefer using these icons because of the following reasons…

Multiple Size Icons

Most themes provide the same icon in various sizes. The available sizes are 128×128, 64×64, 48×48, 32×32, 24×24, 22×22, 16×16 and sometimes even a scalable SVG set. Not all themes have all the sizes - but most have. I don’t have to tell you how useful this is.

Multiple Size Icons

Lots of Choice

KDE Look Icons page have 86 pages with 15 icon themes per page. That makes a total of 1290 icon sets. And I am not counting the Gnome Look Icons.

That’s a lot of choice. Granted, not all will be good. Not all will have the icon I am searching for. Not all have the size I way want. There will be some duplication. But its still a lot.

Free - in both sense of the word

Most of these icons uses GPL and LGPL licenses. So you can use if for your application without paying for them. You can modify them. You can share it with others. You can… you get the idea. The point is there are no restrictions.

Even if you are building a proprietary application, I think you can use the icons because you are not compiling it into the application. But I am not sure about that - if anyone reading this knows, please leave a comment.

I have to warn you that not all icons sets use these licenses - so make sure you look at the license of an icon set before using it.

Great Icons

Most of the icons are created by professional designers. Sure there are some duds among the collection - but the majority of them are good.

Some Recommended Icon Sets

Crystal Project

Crystal Project

Nuvola

Nuvola

Crystal Diamond

Crystal Diamond

black + white icons

Black White

Crystal Clear

Crystal Clear

And there are hundreds more for you to find out…

BarCamp Kerala 2007

Sunday, November 25th, 2007

Barcamp Kerala 2007

Yesterday I went to the first Kerala BarCamp. It was held at Techno Park, Trivandrum. I had to travel 225 kilometers to attend it - and it was totally worth it!

Sessions

Open Social

By Kenney Jacob

About the new OpenSocial API provided by Google. The talk was concentrated on its application on Orkut - as it is the most popular social networking site here.

Game Development in Ruby

By Vishnu Gopal

This session was about creating small 2D games in Ruby using the ‘Gosu’ library. You can get a small sample game he created for this session at N3wton Google Code

Presentation

Home Automation using Bluetooth

By Hari Krishnan

Using your mobile phone as an universal remote for all applications within your home.

Asterisk

By Bipin

Asterisk is a Open Source software PBX(Private branch exchange)

QT

By Dhaneesh and Dev

Using QT Designer to create GUI applications.

Computer Memory Based on Bacteriorhodopsin

By Jidhu

A new way of storing information - by changing the state of a protein. This is done by shining a different colour light on the protein. It is much faster and cheaper than the fastest RAMs available today. Also, it is non-volatile - so it can be as both the HardDisk and as the RAM. I found this the most interesting of all session.

Open Network Project

By Linoy Joseph

A implementation of a mesh style open network.

Android

by Renjith Ramachandran

Developing mobile application using the Android SDK provided by Google. The presentation showed us how to do it using Eclipse.

PHP Wiz

by Sreekanth G S

A small introduction to PHP and Web Application Development.

The People

The best part of the camp is the people you meet. I met a lot of people who I only knew only through the internet. Some of the people I met…

Until next time…

AGPL License

Tuesday, November 20th, 2007

License

AGPL or Affero General Public License Version is a new License released by FSF. This is aimed at Web Applications.

The GNU GPL allows people to modify the software they receive, and share those modified versions with others, as long as they make source available to the recipients when they do so. However, a user can modify the software and run the modified version on a network server without releasing it. Since use of the server does not imply that people can download a copy of the program, this means the modifications may never be released. Many programmers choose to use the GNU GPL to cultivate community development; if many of the modifications developed by the programs users are never released, this can be discouraging for them. The GNU AGPL addresses their concerns. The FSF recommends that people consider using the GNU AGPL for any software which will commonly be run over a network. (Emphasis mine)

Say I used AGPL for Nexty. You decide that it is a nice program - so you download it and use it. Then you make some changes to the code. So far so good.

Then you decide that you can put the modified version on your web server. The visitors can use the modified version of nexty - that is, you are not ‘distributing’ the software. If I used GPL, you could have gotten away with it - but if I use AGPL, you have to publish the code you modified as well.

The end result is that the end user is in a lot of confusion about what they should do with respect to the license. If they are not lawyers, they will not be able to understand what the license says. I have opted to use the BSD license due to factors like this - BSD license basically gives you the right to do anything with it - except claim that you wrote it.

Related Links

Creating PDF in Ruby on Rails - PDF::Writer

Monday, November 12th, 2007

PDF::Writer is my choice for creating PDF files in Ruby on Rails. Its simple, easy to use, and has all the features I am looking for.

Install PDF::Writer in Linux systems using this command…

gem install pdf-writer -y

Includes

We will require rubygems and pdf/writer.

require "rubygems"
require "pdf/writer"

The next line creates a new instance of PDF::Writer

pdf = PDF::Writer.new

Create a Heading(big font size)

pdf.select_font "Times-Roman"
pdf.text "Sample PDF Document", :font_size => 32, :justification => :center

The text function will add a string of text to the document, starting at the current position. It will wrap to keep within the margins - so you can specify text as big blocks. The text will go to the start of the next line when a return code “\n” is found.

The other arguments available for this function are…

:font_size
The font size to be used. If not specified, is either the last font size or the default font size of 12 points. Setting this value changes the current font_size.
:left
Gap to leave from the left margin
:right
Gap to leave from the right margin
:absolute_left
Absolute left position (overrides :left)
:absolute_right
Absolute right position (overrides :right)
:justification
This can be :left, :right, :center, :full
:leading
This defines the total height taken by the line, independent of the font height.
:spacing
Line spacing - usually set to one of 1, 1.5, 2 (line spacing as used in word processing)

Writing Text

pdf.text "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam sodales velit ac ante. Suspendisse felis mi, convallis at, semper id, malesuada eu, mauris. Integer orci. Sed consectetuer orci. In hac habitasse platea dictumst. Duis nec pede. Ut lacinia eros ut magna. Maecenas lectus dui, lacinia vel, porttitor a, fringilla nec, turpis. Nulla odio nisi, mattis ac, porttitor at, malesuada ac, nibh. Nam suscipit mi ut justo. Phasellus aliquam lorem non velit ornare bibendum. Nullam mollis. Ut elementum rutrum justo. Pellentesque ac sapien. In facilisis lorem a enim. Curabitur vitae felis. In eget tellus nec ligula egestas semper. Nulla facilisis urna nec magna. Pellentesque fringilla pulvinar risus. Aliquam rutrum, nisi ut lobortis consequat, nisl felis posuere risus, at sollicitudin nibh dui et felis.

Fusce tristique dapibus neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut felis mi, dictum ut, vehicula non, fermentum quis, elit. Quisque ultricies purus quis enim. Integer turpis elit, porttitor quis, volutpat consequat, interdum vitae, quam. Donec tempus, dolor eget bibendum euismod, metus dolor imperdiet purus, vitae nonummy est mi non orci. Aenean eu massa. Fusce euismod. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Nullam quis massa id sem commodo eleifend. Cras eu velit rutrum leo egestas adipiscing. Nulla volutpat, lectus sit amet sagittis gravida, erat tortor condimentum sem, vitae sollicitudin lectus diam eget felis. Aliquam augue. Vestibulum viverra est. Fusce tellus ligula, euismod sed, placerat vel, cursus dictum, erat.", :font_size => 12

I used the text() - but this time with 12 as the font_size. The long text will wrap around and the \n will be converted to line breaks.

Inserting Images

PDF::Writer provides an easy way to insert images…

pdf.image "default.png"

That’s it - it will insert an image called ‘default.png’. The other option are…

:pad
The number of PDF userspace units that will be on all sides of the image. The default is 5 units.
:width
The desired width of the image. The image will be resized to this width with the aspect ratio kept. If unspecified, the image’s natural width will be used.
:resize
How to resize the image, either :width (resizes the image to be as wide as the margins) or :full (resizes the image to be as large as possible). May be a numeric value, used as a multiplier for the image size (e.g., 0.5 will shrink the image to half-sized). If this and :width are unspecified, the image’s natural size will be used. Mutually exclusive with the :width option.
:justification
The placement of the image. May be :center, :right, or :left. Defaults to :left.
:border
The border options. No default border. If specified, must be either true, which uses the default border, or a Hash.

Tables

Inserting tables are slightly more complicated than the last two items. If you are using SimpleTable, you have to add
require "pdf/simpletable"
along with the other includes.

table = PDF::SimpleTable.new
table.title = "Sample Tables"
table.column_order.push(*%w(first second))

table.columns["first"] = PDF::SimpleTable::Column.new(”first”)
table.columns["first"].heading = “First”

table.columns["second"] = PDF::SimpleTable::Column.new(”second”)
table.columns["second"].heading = “Second”

table.show_lines    = :all
table.show_headings = true
table.orientation   = :center
table.position      = :center

data = [
	{"first"=> "1", "second"=> "2"}, # First row
	{"first"=> "One", "second"=> "Two"}, # Second row
	{"first"=> "Mono", "second"=> "Di"}, # Third row
]

table.data.replace data
table.render_on(pdf)

The above code will create a table with two column and three rows of data. The code should be easy to decipher - so I am not going into any more explanation.

Saving the PDF

Finally, saving the created PDF…

pdf.save_as("report.pdf") 

Links

Subscribe to Feed