changeset 555:f1ee661e1c46

macro pdf2svg renamed to pdf2img: can use a wider range of convertors
author Reimar Bauer <rb.proj AT googlemail DOT com>
date Thu, 10 Mar 2011 08:53:01 +0100
parents fde88c905588
children 47d9180d02ed
files data/plugin/macro/pdf2img.py data/plugin/macro/pdf2svg.py
diffstat 2 files changed, 149 insertions(+), 149 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/data/plugin/macro/pdf2img.py	Thu Mar 10 08:53:01 2011 +0100
@@ -0,0 +1,149 @@
+# -*- coding: iso-8859-1 -*-
+"""
+    MoinMoin - pdf2svg converts pdf files to svg and shows rendered svg
+
+    Features:
+    * fetches pdf files from urls and converts them to svg,
+      The new svg image is stored and rendered from its cachefile
+    * can also be used for an attached pdf file 
+    * checks timestamp of content for updating cached image
+
+    Requires posix platform and pdf2svg
+
+    @copyright: 2011 MoinMoin:ReimarBauer
+    @license: GNU GPL, see COPYING for details.
+"""
+
+from MoinMoin import log
+logging = log.getLogger(__name__)
+
+import httplib
+import os
+import tempfile
+import urllib2
+from urlparse import urlparse
+
+from MoinMoin import caching, config
+from MoinMoin.util.SubProcess import exec_cmd
+from MoinMoin.action import AttachFile, cache
+from MoinMoin.Page import Page
+
+CACHE_ARENA = 'sendcache'
+CACHE_SCOPE = 'wiki'
+
+def url_exists(url):
+    content = ""
+    try:
+        item = urllib2.urlopen(url)
+        content = item.read(size=1)
+        item.close()
+    except (IOError, urllib2.HTTPError, ValueError):
+        return False
+    if content:
+        return True
+    return False
+
+def last_modified(request=None, pagename=None, attachment=None, url=""):
+    if not url:
+        pdf_file = os.path.join(AttachFile.getAttachDir(request, pagename), attachment).encode(config.charset)
+        st = os.stat(pdf_file)
+        return request.user.getFormattedDateTime(st.st_mtime)
+
+    parse_result = urlparse(url)
+    conn = httplib.HTTPConnection(parse_result.netloc)
+    conn.request("GET", parse_result.path)
+    response = conn.getresponse()
+    return response.getheader('last-modified')
+
+def get_svg_key(request, url, pageno, identifier):
+    """
+    gets the key needed for the svg cache file 
+    """
+    return cache.key(request, itemname="SVG", content="%s.%s.%s.SVG" % (url, pageno, identifier))
+
+def prepare_svg_cache(request, url, pageno, identifier):
+    """
+    prepares the svg cache file and returns its file name
+    """
+    key = get_svg_key(request, url, pageno, identifier)
+    cache.put(request, key, "<svg></svg>",
+              content_type="image/svg+xml")
+    data_cache = caching.CacheEntry(request, CACHE_ARENA, key+'.data', CACHE_SCOPE, do_locking=False)
+    return data_cache._fname
+
+def fetch_pdf_item(request, url):
+    """
+    fetches the pdf item and stores it as cache file 
+    """
+    key = cache.key(request, itemname="PDF", content=url)
+    try:
+        item = urllib2.urlopen(url)
+    except (IOError, urllib2.HTTPError, ValueError), err:
+        logging.info(url)
+        logging.debug("%s: %s" % (url, err))
+        return ""
+    else:
+        cache.put(request, key, item.read(),
+                  content_type="application/pdf")
+        item.close()
+        data_cache = caching.CacheEntry(request, CACHE_ARENA, key+'.data', CACHE_SCOPE, do_locking=False)
+        return data_cache._fname
+
+def macro_pdf2svg(macro, attachment='', url='', width=1200, height=800, pageno=1):
+    """
+    converts pdf from urls to svg files using MoinMoins cache and renders from there
+    """
+    request = macro.request
+    pagename = request.page.page_name
+    content_type = 'image/svg+xml'
+    template_cmd = "pdf2svg %(pdf_file)s %(svg_file)s %(pageno)s"
+    pdf_file = None
+
+    if os.name == 'posix':
+        if attachment:
+            if not AttachFile.exists(request, pagename, attachment):
+                return "attachment: %s does not exists" % attachment
+            url = AttachFile.getAttachUrl(pagename, attachment, request)
+            identifier = last_modified(request, pagename, attachment)
+        else:
+            if not url_exists(url):
+                return "url: %s does not exists" % url
+            identifier = last_modified(url=url)
+        logging.debug("%s: %s" % (url, identifier))
+
+        key = get_svg_key(request, url, pageno, identifier)
+        if not cache.exists(request, key):
+            if attachment and attachment.lower().endswith('.pdf') and AttachFile.exists(request, pagename, attachment):
+                pdf_file = os.path.join(AttachFile.getAttachDir(request, pagename), attachment).encode(config.charset)
+            elif url:
+                #TODO: a mimetype check is needed beforehand 
+                pdf_file = fetch_pdf_item(request, url)
+            if pdf_file:
+                svg_file = prepare_svg_cache(request, url, pageno, identifier)
+                cmd = template_cmd % {"pdf_file": pdf_file,
+                                      "svg_file": svg_file,
+                                      "pageno": pageno
+                                      }
+                data, errors, rc = exec_cmd(cmd, timeout=300)
+                logging.debug("Command '%s', rc: %d, stdout: %d bytes, stderr: %s" % (cmd, rc, len(data), errors))
+                if not errors:
+                    svg_image = open(svg_file, 'rb')
+                    cache.put(request, key, svg_image.read(),
+                              content_type="image/svg+xml")
+                    svg_image.close()
+
+        if cache.exists(request, key):
+            cache_url = "%s%s%s" % (request.getQualifiedURL(), Page(request, pagename).url(request), cache.url(request, key))
+            from MoinMoin import macro as _macro
+            from MoinMoin.parser.text import Parser
+            _macro.formatter = request.html_formatter
+            parser = Parser("##\n", request)
+            m = _macro.Macro(parser)
+            html_object = m.execute('EmbedObject', u'width=%s, height=%s, target=%s, url_mimetype=%s' % (width, height, cache_url, content_type))
+            if attachment:
+                url = AttachFile.getAttachUrl(pagename, attachment, request, addts=0, do='get')
+                return '<B>SVG Image from:</B> "<a href=%s>%s</a>"<hr>%s<br>' % (url, attachment, html_object)
+            else:
+                return '<B>SVG Image from:</B> "<a href=%s>%s</a>"<hr>%s<br>' % (url, url, html_object)
+        else:
+             return ""
--- a/data/plugin/macro/pdf2svg.py	Sun Mar 06 12:11:51 2011 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,149 +0,0 @@
-# -*- coding: iso-8859-1 -*-
-"""
-    MoinMoin - pdf2svg converts pdf files to svg and shows rendered svg
-
-    Features:
-    * fetches pdf files from urls and converts them to svg,
-      The new svg image is stored and rendered from its cachefile
-    * can also be used for an attached pdf file 
-    * checks timestamp of content for updating cached image
-
-    Requires posix platform and pdf2svg
-
-    @copyright: 2011 MoinMoin:ReimarBauer
-    @license: GNU GPL, see COPYING for details.
-"""
-
-from MoinMoin import log
-logging = log.getLogger(__name__)
-
-import httplib
-import os
-import tempfile
-import urllib2
-from urlparse import urlparse
-
-from MoinMoin import caching, config
-from MoinMoin.util.SubProcess import exec_cmd
-from MoinMoin.action import AttachFile, cache
-from MoinMoin.Page import Page
-
-CACHE_ARENA = 'sendcache'
-CACHE_SCOPE = 'wiki'
-
-def url_exists(url):
-    content = ""
-    try:
-        item = urllib2.urlopen(url)
-        content = item.read(size=1)
-        item.close()
-    except (IOError, urllib2.HTTPError, ValueError):
-        return False
-    if content:
-        return True
-    return False
-
-def last_modified(request=None, pagename=None, attachment=None, url=""):
-    if not url:
-        pdf_file = os.path.join(AttachFile.getAttachDir(request, pagename), attachment).encode(config.charset)
-        st = os.stat(pdf_file)
-        return request.user.getFormattedDateTime(st.st_mtime)
-
-    parse_result = urlparse(url)
-    conn = httplib.HTTPConnection(parse_result.netloc)
-    conn.request("GET", parse_result.path)
-    response = conn.getresponse()
-    return response.getheader('last-modified')
-
-def get_svg_key(request, url, pageno, identifier):
-    """
-    gets the key needed for the svg cache file 
-    """
-    return cache.key(request, itemname="SVG", content="%s.%s.%s.SVG" % (url, pageno, identifier))
-
-def prepare_svg_cache(request, url, pageno, identifier):
-    """
-    prepares the svg cache file and returns its file name
-    """
-    key = get_svg_key(request, url, pageno, identifier)
-    cache.put(request, key, "<svg></svg>",
-              content_type="image/svg+xml")
-    data_cache = caching.CacheEntry(request, CACHE_ARENA, key+'.data', CACHE_SCOPE, do_locking=False)
-    return data_cache._fname
-
-def fetch_pdf_item(request, url):
-    """
-    fetches the pdf item and stores it as cache file 
-    """
-    key = cache.key(request, itemname="PDF", content=url)
-    try:
-        item = urllib2.urlopen(url)
-    except (IOError, urllib2.HTTPError, ValueError), err:
-        logging.info(url)
-        logging.debug("%s: %s" % (url, err))
-        return ""
-    else:
-        cache.put(request, key, item.read(),
-                  content_type="application/pdf")
-        item.close()
-        data_cache = caching.CacheEntry(request, CACHE_ARENA, key+'.data', CACHE_SCOPE, do_locking=False)
-        return data_cache._fname
-
-def macro_pdf2svg(macro, attachment='', url='', width=1200, height=800, pageno=1):
-    """
-    converts pdf from urls to svg files using MoinMoins cache and renders from there
-    """
-    request = macro.request
-    pagename = request.page.page_name
-    content_type = 'image/svg+xml'
-    template_cmd = "pdf2svg %(pdf_file)s %(svg_file)s %(pageno)s"
-    pdf_file = None
-
-    if os.name == 'posix':
-        if attachment:
-            if not AttachFile.exists(request, pagename, attachment):
-                return "attachment: %s does not exists" % attachment
-            url = AttachFile.getAttachUrl(pagename, attachment, request)
-            identifier = last_modified(request, pagename, attachment)
-        else:
-            if not url_exists(url):
-                return "url: %s does not exists" % url
-            identifier = last_modified(url=url)
-        logging.debug("%s: %s" % (url, identifier))
-
-        key = get_svg_key(request, url, pageno, identifier)
-        if not cache.exists(request, key):
-            if attachment and attachment.lower().endswith('.pdf') and AttachFile.exists(request, pagename, attachment):
-                pdf_file = os.path.join(AttachFile.getAttachDir(request, pagename), attachment).encode(config.charset)
-            elif url:
-                #TODO: a mimetype check is needed beforehand 
-                pdf_file = fetch_pdf_item(request, url)
-            if pdf_file:
-                svg_file = prepare_svg_cache(request, url, pageno, identifier)
-                cmd = template_cmd % {"pdf_file": pdf_file,
-                                      "svg_file": svg_file,
-                                      "pageno": pageno
-                                      }
-                data, errors, rc = exec_cmd(cmd, timeout=300)
-                logging.debug("Command '%s', rc: %d, stdout: %d bytes, stderr: %s" % (cmd, rc, len(data), errors))
-                if not errors:
-                    svg_image = open(svg_file, 'rb')
-                    cache.put(request, key, svg_image.read(),
-                              content_type="image/svg+xml")
-                    svg_image.close()
-
-        if cache.exists(request, key):
-            cache_url = "%s%s%s" % (request.getQualifiedURL(), Page(request, pagename).url(request), cache.url(request, key))
-            from MoinMoin import macro as _macro
-            from MoinMoin.parser.text import Parser
-            _macro.formatter = request.html_formatter
-            parser = Parser("##\n", request)
-            m = _macro.Macro(parser)
-            html_object = m.execute('EmbedObject', u'width=%s, height=%s, target=%s, url_mimetype=%s' % (width, height, cache_url, content_type))
-            if attachment:
-                url = AttachFile.getAttachUrl(pagename, attachment, request, addts=0, do='get')
-                return '<B>SVG Image from:</B> "<a href=%s>%s</a>"<hr>%s<br>' % (url, attachment, html_object)
-            else:
-                return '<B>SVG Image from:</B> "<a href=%s>%s</a>"<hr>%s<br>' % (url, url, html_object)
-        else:
-             return ""