Wednesday, August 12, 2009

Convert html files to pdf

#html2pdf.py
#
#Convert an html file into pdf. This script uses WebKit 
#and runs on OS X 1.5
#
#Usage: 
# python html2pdf.py <inputfile> <outputfile>
#
#Written using code from
#http://cocoadevcentral.com/articles/000074.php
#http://www.paulhammond.org/webkit2png

import WebKit
from Foundation import NSObject, NSMutableDictionary, NSURL, NSURLRequest
from AppKit import (NSPrintInfo, NSPrintSaveJob, NSPrintJobDisposition, 
                    NSPrintJobDisposition, NSPrintSavePath, NSPrintInfo, 
                    NSAutoPagination, NSApplication, NSWindow, 
                    NSBorderlessWindowMask)

class WebkitLoad (NSObject, WebKit.protocols.WebFrameLoadDelegate):
    def webView_didFinishLoadForFrame_(self,webview,frame):
        if (frame == webview.mainFrame()):
            self.printFrame(frame)

    def printFrame(self, frame):
        frameview = frame.frameView()
        sharedInfo = NSPrintInfo.sharedPrintInfo()
        sharedDict = sharedInfo.dictionary()
        printInfoDict = NSMutableDictionary.dictionaryWithDictionary_(
            sharedDict)
        printInfoDict.setObject_forKey_(NSPrintSaveJob,
                                        NSPrintJobDisposition);
        printInfoDict.setObject_forKey_(self.pdffile, 
                                       NSPrintSavePath)
        
        printInfo = NSPrintInfo.alloc().initWithDictionary_(printInfoDict)
        printInfo.setHorizontalPagination_(NSAutoPagination);
        printInfo.setVerticalPagination_(NSAutoPagination);
        printInfo.setVerticallyCentered_(False);
        

        printOp = frameview.printOperationWithPrintInfo_(printInfo)
        printOp.setShowPanels_(False)
        printOp.runOperation()
        NSApplication.sharedApplication().terminate_(None)


def main(args):

    htmlfile=args[1]
    pdffile=args[2]
    rect = ((00),(400400))
    
    app = NSApplication.sharedApplication()
    
    win = NSWindow.alloc()
    win.initWithContentRect_styleMask_backing_defer_ (rect, 
            NSBorderlessWindowMask, 20)

    webview = WebKit.WebView.alloc().init()
    webview.initWithFrame_(rect)

    url = NSURL.alloc().initFileURLWithPath_(htmlfile)
    request = NSURLRequest.alloc().initWithURL_(url)

    mainFrame = webview.mainFrame()
    mainFrame.loadRequest_(request)

    loaddelegate = WebkitLoad.alloc().init()
    loaddelegate.pdffile = pdffile
    webview.setFrameLoadDelegate_(loaddelegate)

    win.setContentView_(webview)

    app.run()

if __name__ == "__main__":
    import sys
    main(sys.argv)