better_figures_and_images.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Better Figures & Images
  3. -------
  4. This plugin:
  5. - Adds a style="width: ???px;" to each image in the content
  6. - Also adds the width of the contained image to any parent div.figures.
  7. <div class="figure">
  8. <img alt="map to buried treasure" src="/static/images/dunc_smiling_192x192.jpg" />
  9. <p class="caption">
  10. This is the caption of the figure (a simple&nbsp;paragraph).
  11. </p>
  12. <div class="legend">
  13. The legend consists of all elements after the caption. In this
  14. case, the legend consists of this paragraph.
  15. </div>
  16. </div>
  17. """
  18. import types
  19. import os
  20. from pelican import signals
  21. from bs4 import BeautifulSoup
  22. from PIL import Image
  23. def content_object_init(instance):
  24. def _get_content(self):
  25. content = self._content
  26. return content
  27. instance._get_content = types.MethodType(_get_content, instance)
  28. if instance._content is not None:
  29. content = instance._content
  30. soup = BeautifulSoup(content)
  31. if 'img' in content:
  32. for img in soup('img'):
  33. src = instance.settings['PATH'] + '/images/' + os.path.split(img['src'])[1]
  34. im = Image.open(src)
  35. extra_style = 'width: {}px;'.format(im.size[0])
  36. if img.get('style'):
  37. img['style'] += extra_style
  38. else:
  39. img['style'] = extra_style
  40. fig = img.find_parent('div', 'figure')
  41. if fig:
  42. if fig.get('style'):
  43. fig['style'] += extra_style
  44. else:
  45. fig['style'] = extra_style
  46. instance._content = soup.decode()
  47. def register():
  48. signals.content_object_init.connect(content_object_init)