This repository has been archived on 2023-03-26. You can view files and clone it, but cannot push or open issues or pull requests.
md-pdf/md_pdf/build/pdf.py

62 lines
1.9 KiB
Python
Raw Normal View History

2017-03-27 09:17:49 +01:00
import pdfkit
2017-04-05 14:44:22 +01:00
from md_pdf.consts import TEMPLATES_DIR, STATIC_DIR
2017-05-17 17:52:57 +01:00
from md_pdf.build.templates import FILE_NAME_FORMAT
from md_pdf.exceptions import PDFRenderException
2017-03-28 21:59:11 +01:00
import os
2017-04-01 16:12:03 +01:00
import logging
2017-04-01 16:12:03 +01:00
logger = logging.getLogger(__file__)
2017-03-27 09:17:49 +01:00
2017-03-28 21:59:11 +01:00
DEFAULT_MARGIN_VERTICAL = '1.5cm'
DEFAULT_MARGIN_HORIZONTAL = '2.5cm'
2017-04-05 14:44:22 +01:00
STYLE_FILE = os.path.join(STATIC_DIR, 'style.css')
2017-06-01 22:04:21 +01:00
HEADER_FILE = FILE_NAME_FORMAT.format('header')
FOOTER_FILE = FILE_NAME_FORMAT.format('footer')
2017-05-17 14:46:11 +01:00
TOC_OPTIONS = {
2017-05-17 17:52:57 +01:00
'xsl-style-sheet': os.path.join(TEMPLATES_DIR, 'toc.xsl')
2017-05-17 14:46:11 +01:00
}
2017-03-28 21:59:11 +01:00
PDF_OPTIONS = {
2017-03-27 09:17:49 +01:00
"no-pdf-compression": "",
2017-05-10 21:42:03 +01:00
"enable-internal-links": "",
2017-03-27 09:17:49 +01:00
2017-03-28 21:59:11 +01:00
"header-html": HEADER_FILE,
"footer-html": FOOTER_FILE,
2017-03-27 09:17:49 +01:00
"footer-spacing": 5,
"header-spacing": 5,
2017-05-03 13:30:38 +01:00
"user-style-sheet": STYLE_FILE
2017-03-27 09:17:49 +01:00
}
2017-03-30 08:52:35 +01:00
def export_pdf(content, config):
if logger.getEffectiveLevel() > logging.DEBUG:
PDF_OPTIONS['quiet'] = ""
2017-03-30 18:26:06 +01:00
PDF_OPTIONS['title'] = config.get('title', 'Output')
2017-06-01 22:04:21 +01:00
context = config.get('context', {})
2017-06-01 22:04:21 +01:00
PDF_OPTIONS['replace'] = [(key, str(value)) for key, value in context.items()]
PDF_OPTIONS['margin-top'] = context.get('margin_vertical', DEFAULT_MARGIN_VERTICAL)
PDF_OPTIONS['margin-bottom'] = context.get('margin_vertical', DEFAULT_MARGIN_VERTICAL)
PDF_OPTIONS['margin-left'] = context.get('margin_horizontal', DEFAULT_MARGIN_HORIZONTAL)
PDF_OPTIONS['margin-right'] = context.get('margin_horizontal', DEFAULT_MARGIN_HORIZONTAL)
2017-04-01 16:12:03 +01:00
logger.info("Rendering PDF...")
2017-06-01 22:04:21 +01:00
try:
pdfkit.from_string(
content,
os.path.join(os.path.abspath(config['output_dir']), 'output.pdf'),
options=PDF_OPTIONS,
cover=FILE_NAME_FORMAT.format('cover'),
toc=TOC_OPTIONS if config.get('toc') else {},
cover_first=True
)
except OSError as e:
raise PDFRenderException('Failed to render PDF. ' + str(e))
return PDF_OPTIONS # mostly for testing