the force that pushes object up
Random header image... Refresh for more!

Merging PDF Files In Linux Using PyPDF

PyPDF is a handy and valuable Python library for merging and splitting PDF files in Linux. It’s pure Python library built as a PDF toolkit. It is capable of:

  • extracting document information (title, author, …),
  • splitting documents page by page,
  • merging documents page by page,
  • cropping pages,
  • merging multiple pages into a single page,
  • encrypting and decrypting PDF files.

PyPDF is a great Python library use by many Python applications which handles PDF files directly. PDF-Shuffler is a one of the tools written based on PyPDF which you can use to merge PDF files easily in Linux. In Ubuntu you can install it using following command.

sudo apt-get install pdfshuffler

Here is a sample code that merge PDF files together using PyPDF library. In this code I have used PdfFileWriter and PdfFileReader classes from PyPDF module to read and append PDF files together. This sample doesn’t contain completed error handling logic for file handling.

# Copyright (C) 2010 Milinda Pathirage

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
from pyPdf import PdfFileWriter, PdfFileReader

def mergePDFFiles(outputFile, filesToBeMerged):
    output = PdfFileWriter()
   
    if(len(filesToBeMerged) == 0):
        print 'Empty Input File List'
        return;
   
    for inFile in filesToBeMerged:
        print 'Adding file' + inFile + ' to the out put'
        # Read the input PDF file
        input = PdfFileReader(file(inFile, "rb"))
        # Add every page in input PDF file to output
        for page in input.pages:
            output.addPage(page)
    print 'Writing the final out put to file system'
    # Out put stream for output file        
    outputStream = file(outputFile, "wb")
    output.write(outputStream)
    outputStream.close()
   

if __name__ == '__main__':
    i = 0
    outputFile = ''
    inputFiles = []
    for arg in sys.argv:
        i = i + 1
       
        # Getting out file
        if arg == '-o':
            outputFile = sys.argv[i]
            print 'Output File: ' + outputFile
           
        # Extracting Input files
        if arg == '-i':
            outfileOptionPos = sys.argv.index('-o')
            if i < outfileOptionPos:
                inputFiles = sys.argv[i: outfileOptionPos]
                filesStr = ",".join(inputFiles).replace(",", " ")
                print 'Input Files: ' + filesStr
            else:    
                inputFiles = sys.argv[i:]
                filesStr = ",".join(inputFiles).replace(",", " ")
                print 'Input Files: ' + filesStr
               
    # Merging PDF files
    print 'Merging PDF Files......'            
    mergePDFFiles(outputFile, inputFiles)

You can get more understanding about usages of PyPDF if you explore more about open source projects which uses PyPDF. Here are some of the projects which use PyPDF.

Related Resources:

January 16, 2010   1 Comment

Install Adobe Air 2 On Ubuntu 9.10 64-bit

Adobe AIR is a cross-operating system runtime that lets developers combine HTML, Ajax, Adobe Flash, and Adobe Flex technologies to deploy rich Internet applications (RIAs) on the desktop. The most recent version is Adobe Air 2 with more features than ever for the users as well as developers.

AIR 2 builds on the success of AIR 1 by giving developers new capabilities, and even tighter integration with the desktop. Some new features of AIR 2 include:

  • Support for the detection of mass storage devices.
  • Advanced networking capabilities like secure sockets, UDP support, and the ability to listen on sockets.
  • Support for native code integration.
  • The ability to open a file with its default application.
  • Multi-touch and gesture support.
  • New APIs for access to raw microphone data.
  • Webkit update with HTML5/CSS3 support.
  • Global error handling.
  • Improved cross-platform printing
  • Improved security and support for enterprise and government standards.

The beta release of Adobe Air 2 is available for download from Adobe site. But the problem is they don’t provide us with a 64-bit Linux version(for Ubuntu 9.10 64-bit). But there are some workarounds to this problem. You can install 32-bit version in 64-bit Ubuntu by installing some 32-bit libraries.

First, install ‘getlibs‘ tool from http://frozenfox.freehostia.com/cappy/getlibs-all.deb. Then install ‘libhal-storage.so.1′ library using following command.

sudo getlibs -l libhal-storage.so.1

After the above step please download the Adobe Air 2 beta version’s Linux *.bin file from Adobe, and install it by making it a executable and run the bin file in command line.

If every things went well, now you have Adobe Air 2 beta installed on your system. Please restart your browsers and try to navigate to some Adobe Air application sites and install your favorite Air applications from them.

Please note that I have ‘ia32-libs‘ installed in my Ubuntu 9.10 previously. If you have any problem running Adobe Air using above two steps, try to install the ‘ia32-libs’ using Ubuntu package manager. Also refer this knowledge base article from Adobe on installing Adobe Air 1.5 in 64-bit Linux including Ubuntu.

For more information Adobe Air 2:

December 24, 2009   No Comments

How To Disable Dynamic Frequency Scaling(CPU Throttling) In Ubuntu Jaunty(9.04)

The management of energy consumption in laptops and other mobile devices is increasingly important in order to extend the battery lifetime or to increase the number of applications that can use the system’s resources. It is also used in quiet computing settings and to decrease energy and cooling costs for lightly loaded machines.

Even though this technology has many advantages when using laptop with battery power, it makes me annoying sometimes when I work using AC power.In some situation it makes my laptop very slow when I run several applications like Firefox, IntelliJ IDEA and Adobe Acrobat simultaneously. I have to always switch frequency scaling to performance to get required level of responsiveness and sometimes my Ubuntu 9.04 failed to scale the frequency when I want it to do it. Because I have AC power most of the times I decided to switch to performance mode permanently.

As I found out, sudo dpkg-reconfigure gnome-applets method does not work anymore and instead I have to install rcconf and configure CPU throttling using rcconf.

First we need to install rcconf using sudo apt-get install rcconf command and then run it with administrative privileges using sudo rcconf . You will following configuration view on you terminal. Then search for ‘ondemand‘ option and disable(un-check the check-box) it using space-bar. To save the configuration hit the tab key so that “OK” is highlighted then enter to save and reboot.

rcconf

Now from the add CPU Frequency Scaling Monitor applet to your Gnome panel and select ‘Performance’ option by clicking applet.

How to revert the change

Open the rcconf application again with administrative privileges and scroll to bottom. There will be un-checked ‘ondemand’ option, check it using space-bar and save. The change will be available from the next restart.

October 4, 2009   2 Comments

Using libnotify in Ubuntu 9.04

There are some applications which need to send notifications to users. Ubuntu 9.04 has new on-screen-display notification agent called Notify OSD which implmeents freedesktop.org Desktop Notifications Specification with semi-transparent click-through bubbles. This post is not about Notify OSD, but about how you can use libnotify to send notifications in you shell scripts, C programs and Python programs.

Send notifications from your shell scripts

You have to install libnotify-bin package in Ubuntu and you can use notify-send command to send notifications from your shell script. After installing libnotify-bin you can try notify-send command just like following.

notify-send "First Notification"

By default the message will be displayed for 5 seconds. To change how long a message stays displayed use the “-t” switch. You can use “-t 0″ leave the message up until the user closes it. But in new Ubuntu notification agent will display these notifications as alert box. You can find great explanations about Notify OSD here.

notify-send "This message will be displayed for 3 seconds" -t 3000
notify-send "Click me to close me." -t 0

Add title to your notification like following:

notify-send "This is the Title"  "This is the message body"

Add icon with title and message body(You can find icon codes here):

notify-send "New Mail" "Hey buddy, you got a new E-mail" -i notification-message-email

Send notifications from your Python application

You need to install python-notify package first and then you can use pynotify to send notification from your Python script. There are different capabilities in different notification agents. I am ignoring getting those information in this example.

#!/usr/bin/python

import sys
import pynotify

if __name__ == "__main__":
    # Check whether your notification agent support
    # incon-summary-body layout.
    if not pynotify.init("icon-summary-body"):
        sys.exit(1)

    n = pynotify.Notification(
            "You have a mail",
            "You have new e-mail from Milinda",
            "notification-message-email")
    n.show()

Sample code in C
You need to install libnotify-dev, libglib2.0-dev and libgtk2.0-dev packages first. You can compile this sample using following gcc command.

gcc test_notify.c `pkg-config --cflags glib-2.0` `pkg-config --cflags --libs gtk+-2.0` -lnotify
#include
#include
#include

void closed_handler (NotifyNotification* notification, gpointer data){
    g_print ("closed_handler() called");
    return;
}

int main(int argc, char** argv){
    NotifyNotification* notification;
    gboolean            success;
    GError*             error = NULL;

    if (!notify_init ("icon-summary-body")){
        return 1;
    }

    notification = notify_notification_new (
                 "You have a mail",
                 "You have mail from Milinda",
                 "notification-message-email",
                 NULL);

    error = NULL;
    success = notify_notification_show (notification, &amp;error);
    if (!success)
        g_print ("That did not work ... \"%s\".\n", error-&gt;message);

    g_signal_connect (G_OBJECT (notification),
        "closed",
        G_CALLBACK (closed_handler),
        NULL);
    notify_uninit ();

    return 0;
}

For more information please refer Ubuntu Notification Development Guidelines document.

September 12, 2009   4 Comments