"Fossies" - the Fresh Open Source Software Archive

Member "sofastats-1.5.2/sofa_main/exporting/export_output_pdfs.py" (12 May 2019, 5246 Bytes) of package /linux/misc/sofastats-1.5.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "export_output_pdfs.py" see the Fossies "Dox" file reference documentation.

    1 """
    2 export2pdf() does the real work and can be scripted outside the GUI. Set
    3 headless = True when calling.
    4 """
    5 import os
    6 from pathlib import Path
    7 import shutil
    8 
    9 import PyPDF2 as pypdf
   10 
   11 from .. import basic_lib as b  #@UnresolvedImport
   12 from .. import my_globals as mg  #@UnresolvedImport
   13 from . import export_output  #@UnresolvedImport
   14 
   15 RAWPDF_FILE = 'raw.pdf'
   16 RAWPDF_PATH = mg.INT_PATH / RAWPDF_FILE
   17 PDF_SIDE_MM = '420'  ## any larger and they won't be able to display anywhere in one go anyway
   18 
   19 def pdf_tasks(report_path, alternative_path,
   20         gauge_start_pdf, steps_per_pdf, msgs, progbar, *,
   21         save2report_path, headless):
   22     if save2report_path:
   23         if not os.path.exists(report_path):
   24             raise Exception('Report contents cannot be exported. '
   25                 f'No report file "{report_path}" to export.')
   26         rpt_root, rpt_name = os.path.split(report_path)
   27         pdf_root = os.path.splitext(rpt_name)[0]
   28         pdf_name = f'{pdf_root}.pdf'
   29         pdf_path = export2pdf(rpt_root, pdf_name, report_path,
   30             gauge_start_pdf, steps_per_pdf, progbar, headless=headless)
   31         pdf_saved_msg = (_('PDF has been saved to: \"%s\"') % pdf_path)
   32     else:
   33         foldername = os.path.split(alternative_path)[1]
   34         pdf_path = export2pdf(alternative_path, 'SOFA output.pdf',
   35             report_path, gauge_start_pdf, steps_per_pdf, progbar,
   36             headless=headless)
   37         pdf_saved_msg = _('PDF has been saved to your desktop in the '
   38             '\"%s\" folder' % foldername)
   39     msgs.append(pdf_saved_msg)
   40 
   41 def export2pdf(pdf_root, pdf_name, report_path, gauge_start_pdf=0,
   42         steps_per_pdf=None, progbar=None, *, headless=False):
   43     if headless:
   44         if (steps_per_pdf, progbar) != (None, None):
   45             raise Exception(
   46                 "If running headless, don't set the GUI-specific settings")
   47         steps_per_pdf = 1
   48         progbar = export_output.Prog2console()
   49     if mg.OVERRIDE_FOLDER:
   50         pdf_root = mg.OVERRIDE_FOLDER
   51     pdf_path = Path(pdf_root) / pdf_name
   52     html2pdf(html_path=report_path, pdf_path=pdf_path, as_pre_img=False)
   53     gauge2show = min(gauge_start_pdf + steps_per_pdf, mg.EXPORT_IMG_GAUGE_STEPS)
   54     progbar.SetValue(gauge2show)
   55     return pdf_path
   56 
   57 def get_raw_pdf(html_path, pdf_path, width='', height=''):
   58     """
   59     Note - PDFs made by wkhtmltopdf might be malformed from a strict point of
   60     view (ghostscript and Adobe might complain). Best to fix in extra step.
   61     """
   62     debug = False
   63     if mg.EXPORT_IMAGES_DIAGNOSTIC: debug = True
   64     try:
   65         url = html_path.as_uri()
   66         cmd_make_pdf = 'cmd_make_pdf not successfully generated yet'
   67         """
   68         Unless Linux, MUST be in report directory otherwise won't carry across
   69         internal links.
   70 
   71         Re: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true
   72         """
   73         ## clear decks first so we can tell if image made or not
   74         try:
   75             os.remove(pdf_path)
   76         except Exception:
   77             pass
   78         rel_url = os.path.split(url)[1]
   79         cd_path = os.path.split(html_path)[0]
   80         if mg.PLATFORM == mg.WINDOWS:  ## using Pyinstaller
   81             cmd_make_pdf = (
   82                 f'cd "{cd_path}" && '
   83                 f'"{export_output.EXE_TMP}\\wkhtmltopdf.exe" '
   84                 f'{width} {height} "{rel_url}" "{pdf_path}"')
   85         elif mg.PLATFORM == mg.MAC:
   86             cmd_make_pdf = (
   87                 f'cd "{cd_path}" && '
   88                 f'"{mg.MAC_FRAMEWORK_PATH}/wkhtmltopdf" '
   89                 f'{width} {height} "{rel_url}" "{pdf_path}"')
   90         elif mg.PLATFORM == mg.LINUX:
   91             cmd_make_pdf = f'wkhtmltopdf {width} {height} "{url}" "{pdf_path}"'
   92         else:
   93             raise Exception('Encountered an unexpected platform!')
   94         ## wkhtmltopdf uses stdout to actually output the PDF - a good feature but stuffs up reading stdout for message
   95         if debug: print(f'cmd_make_pdf: {cmd_make_pdf}')
   96         export_output.shellit(cmd_make_pdf)
   97         if not os.path.exists(pdf_path):
   98             raise Exception(
   99                 f"wkhtmltopdf didn't generate error but {pdf_path} not made "
  100                 f'nonetheless. cmd_make_pdf: {cmd_make_pdf}')
  101         if debug: print(f'Initial processing of {html_path} complete')
  102     except Exception as e:
  103         raise Exception(
  104             f'get_raw_pdf command failed: {cmd_make_pdf}. Orig error: {b.ue(e)}')
  105     return pdf_path
  106 
  107 def get_pdf_page_count(pdf_path):
  108     try:
  109         #encoding2use = sys.getfilesystemencoding()  ## on win, mbcs
  110         pdf_im = pypdf.PdfFileReader(
  111             open(str(pdf_path), 'rb'))
  112     except Exception as e:
  113         raise Exception(
  114             f'Problem getting PDF page count. Orig error: {b.ue(e)}')
  115     n_pages = pdf_im.getNumPages()
  116     return n_pages
  117 
  118 def html2pdf(html_path, pdf_path, *, as_pre_img=False):
  119     width = f'--page-width {PDF_SIDE_MM}' if as_pre_img else ''
  120     height = f'--page-height {PDF_SIDE_MM}' if as_pre_img else ''
  121     try:
  122         raw_pdf = get_raw_pdf(html_path, RAWPDF_PATH, width, height)
  123     except Exception as e:
  124         raise Exception(f'Unable to make raw PDF: Orig error: {b.ue(e)}')
  125     shutil.copy(raw_pdf, pdf_path)