Archive for the ‘Scripts’ Category

Hello Script for bash

Monday, May 12th, 2008

Hello Script series for Bash. ‘Hello Script’ is 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.

bash

bash is the most commonly used shell in Linux. That makes the bash scripting language the most popular shell scripting language. OK, maybe after batch. But then again, bash is much more powerful than batch(DOS scripting language). If want to learn bash, I will recommend this tutorial - Advanced Bash Scripting

Officially, I hate bash. I use perl or other similar high level language to create shell script. I use bash only for the simplest scripts. But even I admit that bash has its uses. So, here is the hello script for bash…

Hello Script


#!/usr/sh

# Printing(IO)
echo "Hello World"

# Variables, concatenation
name='Binny'
year=2008
echo "Hello, " $name " - welcome to " $year

#If,else conditions
if [ $year -gt 2008 ]; then
	echo “Welcome to the future - yes, we have flying cars!”

elif [ $year -lt 2008 ]; then
	echo “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
	echo “Anything wrong with your time machine? You have not gone anywhere, kiddo.”
fi

# If you are using anything after this, consider using a high level language.
# For loop
for i in 1 2 3
do
	echo $i “) Hi there!”
done

#Numerical Array, foreach
rules[0]=”Do no harm”
rules[1]=”Obey”
rules[2]=”Continue Living”

for ((i=0; i < 3; i++))
do
	echo “Rule” `expr $i + 1` “:” ${rules[$i]}
done

#A While Demo
keys=(hello foo lorem)

i=0
while [ $i -lt 3 ]
do
	echo ${keys[$i]}
	i=`expr $i + 1`
done

# Function, argument, return, call
hello () {
	myname=$1  #First argument.
	echo “Hello” $myname
}
hello “Binny”

# File IO
# File reading
contents=`cat Hello.sh` #For some reason, I’m losing all the \n’s in the file.
echo “Hello has `echo $contents|wc -m` chars” # Or wc -m Hello.sh

# Writing to a file
echo “Hello World from shell script” > /tmp/hello.txt

# Command Executing
ls

# Regular Expressions
string=”Hello World”
evil=`echo $string | grep ‘^Hell’`
if [ "$evil" != "" ]; then
	echo “Yup - its evil”
fi
echo “Hello World” | sed -e ’s/l//g’ #Will return Heo Word

# http://tldp.org/LDP/abs/html/

And, by the way, this will work only in Linux - or if you installed cygwin in your Windows system. Use sh <File_Name> to execute the above code.

URL Lister - My First Firefox Plugin

Wednesday, May 7th, 2008

URL Lister Logo

I just released my first firefox plugin - URL Lister. It shows the URLs of all the open tabs in a textarea so that they can be copied easily.

Download/Install

Install URL Lister

If you have installed it, consider rating it or reviewing it at Firefox plugins sandbox. Go to the public page for URL Lister and write a review for the application. I need reviews to promote it to the main extensions page - sandbox plugins are for registered users only.

Usage

Lets say you have these four tabs open…

Right click any tab and click on the ‘URL Lister…’ to open up the main dialog. You can also use ‘Tools > URL Lister’. You will find the URLs of all the open tabs there.

URL Lister Screenshot

There is a drop down menu at the bottom - it has these three options…

  • Plain Text
  • HTML Anchors
  • Linked List

Open URLs

If you have a list of URLs and want to open them all, all you have to do is copy those URLs into this dialog and press OK - this will open up all the given URLs.

And my thanks goes to…

URL Lister is sort of a response to this post by Matt Cutts. I want to thank him for the idea.

There is another plugin with a similar function - Tab URL Copier. I lifted some code from that plugin when creating URL Lister. Thanks.

Hello Script for Ruby

Thursday, May 1st, 2008

Hello Script is a file that contains the most commonly used elements of a programming language so that it can be used as a cheatsheet when working with that language. This Hello Script for Ruby is the sixth post in this series.

I have some experience with Ruby. I will not call myself an expert - but I am comfortable with Ruby. I like ruby. I even have written a few applications in it.

Hello Code


#!/usr/bin/ruby

print "Hello World\n"

name = "Binny"
year = 2008
print "Hello, " + name + " - welcome to " + year.to_s + "\n"

if (year > 2008) then
	print "Welcome to the future - yes, we have flying cars!"
elsif (year < 2008) then
	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."
end
print "\n\n"

# For loop like structure
0.upto(3) { |i|
	print i.to_s + ") Hi there!\n"
}
print "\n"

# Numerical array
rules = ['Do no harm', 'Obey', 'Continue Living']
i = 0
while i<rules.length do
	print “Rule ” + (i+1).to_s + “: ” + rules[i] + “\n”
	i = i+1
end
print “\n”

# Associated arrays
associated = {
	‘hello’	=>	‘world’,
	‘foo’	=>	‘bar’,
	‘lorem’	=>	‘ipsum’
}
associated.each { |key,value|
	print key + ” : ” + value + “\n”
}
print “\n”

# Using Join and Split
csv_values = “hello,world,how,are,you\n”.split(”,”)
print csv_values.join(”:”)

# Function, argument, return, call
def hello(name)
	return “Hello ” + name
end
hello_string = hello(”Binny”)
print “Function call returned ‘” + hello_string + “‘\n\n”

# One for the OOP fanboys - Class, members, object and stuff.
class Movie
	public
	@name = ”
	@rating = 0

	def initialize(name)
		@name = name
		self.rateMovie()
	end

	def rateMovie()
		@rating = (@name.length % 10) + 1 #IMDBs rating algorithm. True story!
	end

	def printMovieDetails()
		print “Movie : ” + @name + “\n”
		print “Rating : ” + ‘*’ * @rating + “(” + @rating.to_s + “)\n\n”
	end
end
# Create the object
ncfom = Movie.new(”New Country for Old Men”) #It’s a sequel!
ncfom.printMovieDetails()

# File IO
# File reading, easy method…
file_in = File.new(’Hello.rb’, ‘r’)
contents = file_in.read
file_in.close
print “Hello has ” + contents.length.to_s + ” chars\n”

# Writing to a file
file_out = File.new(’/tmp/hello.txt’, ‘w’)
file_out.print “Hello World from Ruby.”
file_out.close

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

# Regular Expressions
string = “Hello World”
print “Yup - its evil\n” if(/^Hell/.match(string))
print string.gsub(/l([^l])/, ‘\1′) #Remove an ‘l’ from both words. Should print ‘Helo Word’ - The second arg must be in single quotes

print “\n”

# Some special/only-in-ruby stuff…
# Using a library
require “fileutils”

#Using yield/code blocks…
def doXTimes(i)
	0.upto(i) {|count|
		yield count+1
	}
end
doXTimes(5) {|count|
	print count.to_s + “th Time\n”
}

Hello Script for Tcl

Thursday, April 24th, 2008

Tcl Logo

Tcl, or Tool Command Language, will not be found in the ‘most popular languages’ hall of fame. That is partly because of its ‘wierd’ syntax. But those who know Tcl will tell you that Tcl is a pleasure to work with. I have a special interest in Tcl - its the language that introduced me to GUI programming(Tcl/Tk). Now, when ever I see a GUI toolkit, I compare it to Tcl.

I have a few years experience in Tcl - I have written a very popular Tcl/Tk Tutorial and also a few small applications in Tcl. I am not using it a lot now a days because Tk apps look really bad in Linux. This problem is not present in Windows.

Hello Code


#!/usr/bin/tclsh

# Printing(IO)
puts "Hello World!\n" 

# Variables, concatenation
set name 'Binny'
set year 2008
puts [concat "Hello, "  $name  " - welcome to "  $year]

#If,else conditions
if { $year > 2008 } {
	 puts “Welcome to the future - yes, we have flying cars!” 

} elseif { $year < 2008 }  {
	 puts “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 {
	 puts “Anything wrong with your time machine? You have not gone anywhere, kiddo.”
}

# For loop
for { set i 0 } { $i<3 } { incr i  }  {
	 puts “$i) Hi there!”
}

#Numerical Array, foreach
set rules [list "Do no harm" "Obey" "Continue Living"]

set i 0
while { $i < [llength $rules] } {
	puts [concat "Rule " [expr $i+1] ” : ”  [lindex $rules $i]]
	incr i
}

# Associated array, while
array set associated {
	hello	“world”
	foo		“bar”
	lorem	“ipsum”
}

foreach key [array names associated] {
	 puts [concat $key " : " $associated($key)]
}

# Using Join and Split
set csv_values [split "hello,world,how,are,you\n" ","]
puts [join $csv_values ":"]

# Function, argument, return, call
proc hello { person_name } {
	return [concat "Hello, " $person_name]
}
puts [hello "Binny"]

# File IO
# File reading, easy method…
set IN [open "Hello.tcl" r]
set contents [read $IN]
close $IN
puts [concat "Hello has " [string length $contents] ” chars”]

# Writing to a file
set OUT [open "/tmp/hello.txt" w]
puts $OUT “Hello World”
close $OUT

# Regular Expressions
set str “Hello World”
if { [regexp {^Hell} $str] } {
	puts “Yup, its evil”
}

puts [regsub -all {l([^l])} $str {\1}]

# Special Tcl Syntax
# Math ops
set answer [expr {3 + 2}]

# Comments
puts $answer ;# Comments in the same line as code must use ;# instead of just #

Tcl/Tk Links

Perl Hello Script

Thursday, April 10th, 2008

Perl Logo

This is the next installment of the Hello Script series - Hello Script for Perl. ‘Hello Script’ is 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.

Introduction to Perl

For those of who are unfamiliar with perl, here is the Wikipedia definition…

Perl is a dynamic programming language created by Larry Wall and first released in 1987. Perl borrows features from a variety of other languages including C, shell scripting (sh), AWK, sed and Lisp. Perl was widely adopted for its strengths in text processing and lack of the arbitrary limitations of many scripting languages at the time.

If you are interested in learning perl, I have written a Perl Tutorial. And here are some more links if you are interested

Hello Script for Perl


#!/usr/bin/perl
use strict;
use warnings;

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

# Variables, concatenation
my $name = 'Binny';
my $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!";
}
elsif($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(my $i=0; $i<3; $i++) {
	print "$i) Hi there!\n";
}

#Numerical Array, foreach
my @rules = (
	'Do no harm',
	'Obey',
	'Continue Living'
);
my $i = 1;
foreach my $rule (@rules) {
	print "Rule " . $i . " : " . $rule . "\n";
	$i++;
}

# Associated array, while
my %associated = (
	'hello'	=>	'world',
	'foo'	=>	'bar',
	'lorem'	=>	'ipsum'
);
while(my ($key, $value) = each(%associated)) {
	print "$key: $value\n";
}

# Using Join and Split
my @csv_values = split(',', "hello,world,how,are,you\n");
print join(":", @csv_values);

# Function, argument, return, call
sub hello {
	$name = shift; #First argument.
	return "Hello " . $name;
}
print hello("Binny");

# File IO
# File reading, easy method...
open(IN,'Hello.pl') or die("Cannot open file : $!");
my @lines = <IN>;
close(IN);
my $contents = join('',@lines);
print "Hello has " . length($contents) . " chars\n";
# Writing to a file
open(OUT, '>/tmp/hello.txt');
print OUT "Hello World";
close(OUT);

# Command Executing
print `ls`; #Execute the command 'ls' and print its output
print "\n";

# Regular Expressions
my $string = "Hello World";
print "Yup - its evil\n" if($string =~ /^Hell/);
$string =~ s/l([^l])/$1/g; #Remove an ‘l’ from both words. Should print ‘Helo Word’
print $string;

print “\n\n”;

Python Hello Script

Wednesday, March 19th, 2008

Python Logo

As promised in the last post(Hello Script for PHP), this is my Hello Script for Python. Hello Script‘ is 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.

A word of caution here - the blocks in Python is created using whitespace - so the indentation is important. So when you see an indentation in the below code, think of it as one tab(instead of four spaces or something).

I want to insert a disclaimer here - I am not that good with python. We never really clicked. I have done very limited work in Python. So if you notice any problems with the below script, let me know and I’ll correct it.


#!/usr/bin/python

print "Hello World\n"

name = "Binny"
year = 2008
print "Hello, " + name + " - welcome to " + str(year) + "\n"

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

# For loop
for i in range(0,3):
	print str(i) + ") Hi there!"

print ""

#Numerical Array, While
rules = ['Do no harm','Obey','Continue Living']
i = 0
while(i<len(rules)):
	print “Rule ” + str(i+1) + ” : ” + rules[i]
	i = i + 1
print “”

# Associated array, foreach
associated = {
	‘hello’	:	‘world’,
	‘foo’	:	‘bar’,
	‘lorem’	:	‘ipsum’
}
for key in associated:
	print key + ” : ” + associated[key]
print “”

import string
csv_values = string.split(”hello,world,how,are,you\n”, “,”)
print string.join(csv_values, “:”)

# Function, argument, return, call
def hello(name):
	return “Hello ” + name + “\n”

hello_string = hello(”Binny”)
print hello_string

# One for the OOP fanboys - Class, members, object and stuff.
class Movie:
	name = ”
	rating = 0

	def __init__(self, name):
		self.name = name
		self.rateMovie()

	def rateMovie(self):
		self.rating = (len(self.name) % 10) + 1 #IMDBs rating algorithm. True story!

	def printMovieDetails(self):
		print “Movie : “,  self.name
		print “Rating : “, ‘*’ * self.rating , “(”, self.rating ,”)\n”

#Create the object
ncfom = Movie(”New Country for Old Men”) #It’s a sequel!
ncfom.printMovieDetails()

# File IO
# File reading, easy method…
file_in  = open(’Hello.py’, ‘r’)
contents = file_in.read()
print “Current file has ” + str(len(contents)) + ” chars\n”
file_in.close()
# Writing to a file
file_out = open(’/tmp/hello.txt’, ‘w’)
file_out.write(”Hello World”)
file_out.close()

# Command Executing
import commands
import os
print “Result of ‘ls’ command is ” + commands.getoutput(’ls’) #Execute the command ‘ls’ and print its output
print

# Regular Expressions
import re
hell_check = re.compile(”^Hell”)
string = “Hello World”
if hell_check.match(string): print “Yup - its evil (Compiled)”
if re.match(’^Hell’, string): print “Yup - its evil (Not Compiled)”
print re.sub(r’l([^l])’, r’\1′, string)

As I said last time, save this to a file and keep it around for future reference.

Next hello script - Perl, Ruby or Tcl/Tk? Which one do you want - leave it in the comments.

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.

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

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

Tk Verses Gtk(And Python verses Tcl)

Wednesday, October 31st, 2007

Back when I was using Windows, I searched for some language that would let me create GUI application. I knew C++ - but creating a GUI using C++ was very, very hard. After some searching I found Tcl/Tk - it was perfect. I liked Tk so much that I used it to create GUI in perl programs. And in Ruby. And in Python. I even wrote tutorials for Tcl/Tk and Perl/Tk. Then I discovered Linux. initially I was glad that I did not choose VB - that would mean that I have to throw away all my custom programs. But since I used open languages like Tcl, Perl, Ruby etc, they will run on Linux as well.

But when I actually ran the programs in Linux, I got the shock of a lifetime. The applications I created looked bad - really bad…

TK Screenshot - Ugly

I still use many Tk programs - but because of the looks issue, I decided to stop using Tk for my new programs. So I decided to try GTK. I even created a small application using PyGTK(my first) to view the harddisk space usage in Linux - Frees.

Frees Screenshot

It was a very simple application - all I had to do is run the ‘df’ command, parse its output, and display a small table using that data. I was expecting around 100, 150 lines of code at the most. But after I created the app, I have 500+ lines of code.

At first, I thought that it was a mistake on my part - I thought that I was not using the best method. But then I came across an article in Reddit - gnocl or PyGtk?.

PyGtk is still the most recommended binding for Gtk. A lot of programs in Linux is written using PyGtk. So naturally there are a few advantages for using it…

  • It will be the more ‘road-tested’ binding.
  • Many system will have it installed by default.
  • Bigger community - so…
    • more support
    • more examples
    • more tutorials
    • etc.

One the other hand, I have to write more code.

Conclusion

If it is a private script - only useful for myself, then I will use Tcl/Tk or Gnometcl. If the script could be distributed, like Frees, then I will use Python GTK.

What about the other options…

  • wxWidgets
  • PyQT
  • Ruby/GTK
  • Perl/GTK

Any recommendations for me on which library to use? Please leave it in the comments.

Subscribe to Feed