~ubuntu-branches/ubuntu/karmic/calibre/karmic

« back to all changes in this revision

Viewing changes to src/calibre/ebooks/lrf/pdf/convert_from.py

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2009-07-30 12:49:41 UTC
  • mfrom: (1.3.2 upstream)
  • Revision ID: james.westby@ubuntu.com-20090730124941-qjdsmri25zt8zocn
Tags: 0.6.3+dfsg-0ubuntu1
* New upstream release. Please see http://calibre.kovidgoyal.net/new_in_6/
  for the list of new features and changes.
* remove_postinstall.patch: Update for new version.
* build_debug.patch: Does not apply any more, disable for now. Might not be
  necessary any more.
* debian/copyright: Fix reference to versionless GPL.
* debian/rules: Drop obsolete dh_desktop call.
* debian/rules: Add workaround for weird Python 2.6 setuptools behaviour of
  putting compiled .so files into src/calibre/plugins/calibre/plugins
  instead of src/calibre/plugins.
* debian/rules: Drop hal fdi moving, new upstream version does not use hal
  any more. Drop hal dependency, too.
* debian/rules: Install udev rules into /lib/udev/rules.d.
* Add debian/calibre.preinst: Remove unmodified
  /etc/udev/rules.d/95-calibre.rules on upgrade.
* debian/control: Bump Python dependencies to 2.6, since upstream needs
  it now.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
__license__   = 'GPL v3'
2
 
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
3
 
''''''
4
 
 
5
 
import sys, os, subprocess, logging
6
 
import errno
7
 
from functools import partial
8
 
from calibre import isosx, setup_cli_handlers, filename_to_utf8, iswindows, islinux
9
 
from calibre.ebooks import ConversionError, DRMError
10
 
from calibre.ptempfile import PersistentTemporaryDirectory
11
 
from calibre.ebooks.lrf import option_parser as lrf_option_parser
12
 
from calibre.ebooks.lrf.html.convert_from import process_file as html_process_file
13
 
from calibre.ebooks.metadata import MetaInformation
14
 
from calibre.ebooks.metadata.opf import OPFCreator
15
 
from calibre.ebooks.metadata.pdf import get_metadata
16
 
 
17
 
PDFTOHTML = 'pdftohtml'
18
 
popen = subprocess.Popen
19
 
if isosx and hasattr(sys, 'frameworks_dir'):
20
 
    PDFTOHTML = os.path.join(getattr(sys, 'frameworks_dir'), PDFTOHTML)
21
 
if iswindows and hasattr(sys, 'frozen'):
22
 
    PDFTOHTML = os.path.join(os.path.dirname(sys.executable), 'pdftohtml.exe')
23
 
    popen = partial(subprocess.Popen, creationflags=0x08) # CREATE_NO_WINDOW=0x08 so that no ugly console is popped up
24
 
if islinux and getattr(sys, 'frozen_path', False):
25
 
    PDFTOHTML = os.path.join(getattr(sys, 'frozen_path'), 'pdftohtml')
26
 
 
27
 
def generate_html(pathtopdf, tdir):
28
 
    '''
29
 
    Convert the pdf into html.
30
 
    @return: Path to a temporary file containing the HTML.
31
 
    '''
32
 
    if isinstance(pathtopdf, unicode):
33
 
        pathtopdf = pathtopdf.encode(sys.getfilesystemencoding())
34
 
    if not os.access(pathtopdf, os.R_OK):
35
 
        raise ConversionError, 'Cannot read from ' + pathtopdf
36
 
    index = os.path.join(tdir, 'index.html')
37
 
    # This is neccessary as pdftohtml doesn't always (linux) respect absolute paths
38
 
    pathtopdf = os.path.abspath(pathtopdf)
39
 
    cmd = (PDFTOHTML, '-enc', 'UTF-8',  '-noframes',  '-p',  '-nomerge',
40
 
            '-nodrm', pathtopdf, os.path.basename(index))
41
 
    cwd = os.getcwd()
42
 
 
43
 
    try:
44
 
        os.chdir(tdir)
45
 
        try:
46
 
            p = popen(cmd, stderr=subprocess.PIPE)
47
 
        except OSError, err:
48
 
            if err.errno == 2:
49
 
                raise ConversionError(_('Could not find pdftohtml, check it is in your PATH'), True)
50
 
            else:
51
 
                raise
52
 
 
53
 
        '''
54
 
        print p.stdout.read()
55
 
        '''
56
 
        while True:
57
 
            try:
58
 
                ret = p.wait()
59
 
                break
60
 
            except OSError, e:
61
 
                if e.errno == errno.EINTR:
62
 
                    continue
63
 
                else:
64
 
                    raise
65
 
 
66
 
        if ret != 0:
67
 
            err = p.stderr.read()
68
 
            raise ConversionError, err
69
 
        if not os.path.exists(index) or os.stat(index).st_size < 100:
70
 
            raise DRMError()
71
 
 
72
 
        raw = open(index, 'rb').read()
73
 
        open(index, 'wb').write('<!-- created by calibre\'s pdftohtml -->\n'+raw)
74
 
        if not '<br' in raw[:4000]:
75
 
            raise ConversionError(os.path.basename(pathtopdf) + _(' is an image based PDF. Only conversion of text based PDFs is supported.'), True)
76
 
        try:
77
 
            mi = get_metadata(open(pathtopdf, 'rb'))
78
 
        except:
79
 
            mi = MetaInformation(None, None)
80
 
        if not mi.title:
81
 
            mi.title = os.path.splitext(os.path.basename(pathtopdf))[0]
82
 
        if not mi.authors:
83
 
            mi.authors = [_('Unknown')]
84
 
        opf = OPFCreator(tdir, mi)
85
 
        opf.create_manifest([('index.html', None)])
86
 
        opf.create_spine(['index.html'])
87
 
        opf.render(open('metadata.opf', 'wb'))
88
 
    finally:
89
 
        os.chdir(cwd)
90
 
    return index
91
 
 
92
 
def option_parser():
93
 
    return lrf_option_parser(
94
 
_('''%prog [options] mybook.pdf
95
 
 
96
 
 
97
 
%prog converts mybook.pdf to mybook.lrf''')
98
 
        )
99
 
 
100
 
def process_file(path, options, logger=None):
101
 
    if logger is None:
102
 
        level = logging.DEBUG if options.verbose else logging.INFO
103
 
        logger = logging.getLogger('pdf2lrf')
104
 
        setup_cli_handlers(logger, level)
105
 
    pdf = os.path.abspath(os.path.expanduser(path))
106
 
    tdir = PersistentTemporaryDirectory('_pdf2lrf')
107
 
    htmlfile = generate_html(pdf, tdir)
108
 
    if not options.output:
109
 
        ext = '.lrs' if options.lrs else '.lrf'
110
 
        options.output = os.path.abspath(os.path.basename(os.path.splitext(path)[0]) + ext)
111
 
    else:
112
 
        options.output = os.path.abspath(options.output)
113
 
    options.pdftohtml = True
114
 
    if not options.title:
115
 
        options.title = filename_to_utf8(os.path.splitext(os.path.basename(options.output))[0])
116
 
    html_process_file(htmlfile, options, logger)
117
 
 
118
 
 
119
 
def main(args=sys.argv, logger=None):
120
 
    parser = option_parser()
121
 
    options, args = parser.parse_args(args)
122
 
    if len(args) != 2:
123
 
        parser.print_help()
124
 
        print
125
 
        print 'No pdf file specified'
126
 
        return 1
127
 
    process_file(args[1], options, logger)
128
 
    return 0
129
 
 
130
 
if __name__ == '__main__':
131
 
    sys.exit(main())