""" Copyright (C) 2008 Prognus Software Livre - www.prognus.com.br Author: Diorgenes Felipe Grzesiuk """ from trac.core import * from trac.util import escape from trac.mimeview.api import IContentConverter from trac.wiki.formatter import wiki_to_html from tempfile import mkstemp import os import re import random EXCLUDE_RES = [ re.compile(r'\[\[PageOutline([^]]*)\]\]'), re.compile(r'\[\[TracGuideToc([^]]*)\]\]'), re.compile(r'----(\r)?$\n^Back up: \[\[ParentWiki\]\]', re.M|re.I) ] class WikiToPdfPage(Component): """Convert Wiki pages to PDF using HTMLDOC (http://www.htmldoc.org/).""" implements(IContentConverter) # IContentConverter methods def get_supported_conversions(self): yield ('pdf', 'WikiToPdf', 'pdf', 'text/x-trac-wiki', 'application/pdf', 7) def convert_content(self, req, input_type, text, output_type): os.system("rm -f /tmp/tmp*wikitopdf") tracuri = self.env.config.get('wikitopdf', 'trac_uri') tmp_dir = self.env.config.get('wikitopdf', 'tmp_dir') os.system('mkdir %s 2>/dev/null' % (tmp_dir)) if tmp_dir == "": tmp_dir = "/tmp/wikitopdf" random.seed() tmp_dir += '/%(#)04x_' %{"#":random.randint(0,65535)} hfile, hfilename = mkstemp('wikitopdf') # htmldoc doesn't support utf-8, we need to use some other input encoding codepage = self.env.config.get('trac', 'charset', 'iso-8859-1') for r in EXCLUDE_RES: text = r.sub('', text) page = wiki_to_html(text, self.env, req).encode(codepage, 'replace') self.env.log.debug('WikiToPdf => HTML output for WikiToPdf in charset: %s' % codepage) self.env.log.debug('WikiToPdf => HTML intput for WikiToPdf: %s' % text) page = page.replace('attachment', 'attachments') page = page.replace('?format=raw','') page = page.replace('
', ''
	                                        + '
')
        page = page.replace('
', '
') page = page.replace('', '
') imgcounter = 0 imgpos = page.find('>/dev/null 2>>/dev/null' % (theimg, newimg)) page = page[:addrpos+5] + newimg + page[addrpos+5+thepos:] imgcounter += 1 imgpos = page.find(' Html code: %r' % page) meta = ('' % codepage).encode(codepage) os.write(hfile, '' + meta + '' + page + '') os.close(hfile) pfile, pfilename = mkstemp('wikitopdf') os.close(pfile) os.environ["HTMLDOC_NOCGI"] = 'yes' htmldoc_args = { 'webpage': None, 'format': 'pdf14', 'charset': codepage } htmldoc_args.update(dict(self.env.config.options('wikitopdf-page'))) args_string = ' '.join(['--%s %s' % (arg, value or '') for arg, value in htmldoc_args.iteritems()]) self.env.log.debug('WikiToPdf => Htmldoc code out: %s' % args_string) os.system('htmldoc %s %s -f %s' % (args_string, hfilename, pfilename)) os.system('rm %s* 2>/dev/null' % (tmp_dir)) out = open(pfilename, 'rb').read() os.unlink(pfilename) os.unlink(hfilename) return (out, 'application/pdf')