pdf.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. '''
  3. PDF Generator
  4. -------
  5. The pdf plugin generates PDF files from RST sources.
  6. '''
  7. from __future__ import unicode_literals, print_function
  8. from pelican import signals
  9. from pelican.generators import Generator
  10. from rst2pdf.createpdf import RstToPdf
  11. import os
  12. import logging
  13. logger = logging.getLogger(__name__)
  14. class PdfGenerator(Generator):
  15. """Generate PDFs on the output dir, for all articles and pages coming from
  16. rst"""
  17. def __init__(self, *args, **kwargs):
  18. super(PdfGenerator, self).__init__(*args, **kwargs)
  19. pdf_style_path = os.path.join(self.settings['PDF_STYLE_PATH'])
  20. pdf_style = self.settings['PDF_STYLE']
  21. self.pdfcreator = RstToPdf(breakside=0,
  22. stylesheets=[pdf_style],
  23. style_path=[pdf_style_path])
  24. def _create_pdf(self, obj, output_path):
  25. if obj.source_path.endswith('.rst'):
  26. filename = obj.slug + ".pdf"
  27. output_pdf = os.path.join(output_path, filename)
  28. # print('Generating pdf for', obj.source_path, 'in', output_pdf)
  29. with open(obj.source_path) as f:
  30. self.pdfcreator.createPdf(text=f.read(), output=output_pdf)
  31. logger.info(' [ok] writing %s' % output_pdf)
  32. def generate_context(self):
  33. pass
  34. def generate_output(self, writer=None):
  35. # we don't use the writer passed as argument here
  36. # since we write our own files
  37. logger.info(' Generating PDF files...')
  38. pdf_path = os.path.join(self.output_path, 'pdf')
  39. if not os.path.exists(pdf_path):
  40. try:
  41. os.mkdir(pdf_path)
  42. except OSError:
  43. logger.error("Couldn't create the pdf output folder in " +
  44. pdf_path)
  45. for article in self.context['articles']:
  46. self._create_pdf(article, pdf_path)
  47. for page in self.context['pages']:
  48. self._create_pdf(page, pdf_path)
  49. def get_generators(generators):
  50. return PdfGenerator
  51. def register():
  52. signals.get_generators.connect(get_generators)