def make_pdf_to_png_converter(): """ Returns a function that converts a pdf file to a png file. """ tools_available = [] # check for pdftocairo try: check_output(["pdftocairo", "-v"], stderr=subprocess.STDOUT) tools_available.append("pdftocairo") except: pass # check for ghostscript gs, ver = mpl.checkdep_ghostscript() if gs: tools_available.append("gs") # pick converter if "pdftocairo" in tools_available: def cairo_convert(pdffile, pngfile, dpi): cmd = ["pdftocairo", "-singlefile", "-png", "-r %d" % dpi, pdffile, os.path.splitext(pngfile)[0]] # for some reason this doesn't work without shell check_output(" ".join(cmd), shell=True, stderr=subprocess.STDOUT) return cairo_convert elif "gs" in tools_available: def gs_convert(pdffile, pngfile, dpi): cmd = [gs, '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT', '-sDEVICE=png16m', '-dUseCIEColor', '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE', '-sOutputFile=%s' % pngfile, '-r%d' % dpi, pdffile] check_output(cmd, stderr=subprocess.STDOUT) return gs_convert else: raise RuntimeError("No suitable pdf to png renderer found.")
def gs_convert(pdffile, pngfile, dpi): cmd = [str(gs), '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT', '-dUseCIEColor', '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE', '-sDEVICE=png16m', '-sOutputFile=%s' % pngfile, '-r%d' % dpi, pdffile] check_output(cmd, stderr=subprocess.STDOUT)
def _print_pdf_to_fh(self, fh, *args, **kwargs): w, h = self.figure.get_figwidth(), self.figure.get_figheight() try: # create temporary directory for compiling the figure tmpdir = tempfile.mkdtemp(prefix="mpl_pgf_") fname_pgf = os.path.join(tmpdir, "figure.pgf") fname_tex = os.path.join(tmpdir, "figure.tex") fname_pdf = os.path.join(tmpdir, "figure.pdf") # print figure to pgf and compile it with latex self.print_pgf(fname_pgf, *args, **kwargs) latex_preamble = get_preamble() latex_fontspec = get_fontspec() latexcode = """ \\documentclass[12pt]{minimal} \\usepackage[paperwidth=%fin, paperheight=%fin, margin=0in]{geometry} %s %s \\usepackage{pgf} \\begin{document} \\centering \\input{figure.pgf} \\end{document}""" % ( w, h, latex_preamble, latex_fontspec, ) with codecs.open(fname_tex, "w", "utf-8") as fh_tex: fh_tex.write(latexcode) texcommand = get_texcommand() cmdargs = [texcommand, "-interaction=nonstopmode", "-halt-on-error", "figure.tex"] try: check_output(cmdargs, stderr=subprocess.STDOUT, cwd=tmpdir) except subprocess.CalledProcessError as e: raise RuntimeError("%s was not able to process your file.\n\nFull log:\n%s" % (texcommand, e.output)) # copy file contents to target with open(fname_pdf, "rb") as fh_src: shutil.copyfileobj(fh_src, fh) finally: try: shutil.rmtree(tmpdir) except: TmpDirCleaner.add(tmpdir)
def skip_if_command_unavailable(cmd): """ skips a test if a command is unavailable. Parameters ---------- cmd : list of str must be a complete command which should not return a non zero exit code, something like ["latex", "-version"] """ from matplotlib.compat.subprocess import check_output try: check_output(cmd) except: return skipif(True, reason='missing command: %s' % cmd[0]) return lambda f: f
def gs_convert(pdffile, pngfile, dpi): cmd = [ gs, "-dQUIET", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dNOPROMPT", "-sDEVICE=png16m", "-dUseCIEColor", "-dTextAlphaBits=4", "-dGraphicsAlphaBits=4", "-dDOINTERPOLATE", "-sOutputFile=%s" % pngfile, "-r%d" % dpi, pdffile, ] check_output(cmd, stderr=subprocess.STDOUT)
def _call_fc_list(): """Cache and list the font filenames known to `fc-list`. """ # Delay the warning by 5s. timer = Timer(5, lambda: warnings.warn( 'Matplotlib is building the font cache using fc-list. ' 'This may take a moment.')) timer.start() try: out = subprocess.check_output([str('fc-list'), '--format=%{file}\\n']) except (OSError, subprocess.CalledProcessError): return [] finally: timer.cancel() fnames = [] for fname in out.split(b'\n'): try: fname = six.text_type(fname, sys.getfilesystemencoding()) except UnicodeDecodeError: continue fnames.append(fname) return fnames
def cairo_convert(pdffile, pngfile, dpi): cmd = ["pdftocairo", "-singlefile", "-png", "-r %d" % dpi, pdffile, os.path.splitext(pngfile)[0]] # for some reason this doesn't work without shell check_output(" ".join(cmd), shell=True, stderr=subprocess.STDOUT)
############################################################################### # create a list of system fonts, all of these should work with xe/lua-latex system_fonts = [] if sys.platform.startswith('win'): from matplotlib import font_manager for f in font_manager.win32InstalledFonts(): try: system_fonts.append(font_manager.get_font(str(f)).family_name) except: pass # unknown error, skip this font else: # assuming fontconfig is installed and the command 'fc-list' exists try: # list scalable (non-bitmap) fonts fc_list = check_output(['fc-list', ':outline,scalable', 'family']) fc_list = fc_list.decode('utf8') system_fonts = [f.split(',')[0] for f in fc_list.splitlines()] system_fonts = list(set(system_fonts)) except: warnings.warn('error getting fonts from fc-list', UserWarning) def get_texcommand(): """Get chosen TeX system from rc.""" texsystem_options = ["xelatex", "lualatex", "pdflatex"] texsystem = rcParams.get("pgf.texsystem", "xelatex") return texsystem if texsystem in texsystem_options else "xelatex" def get_fontspec(): """Build fontspec preamble from rc."""
def cairo_convert(pdffile, pngfile, dpi): cmd = [str("pdftocairo"), "-singlefile", "-png", "-r", "%d" % dpi, pdffile, os.path.splitext(pngfile)[0]] check_output(cmd, stderr=subprocess.STDOUT)
# create a list of system fonts, all of these should work with xe/lua-latex system_fonts = [] if sys.platform.startswith("win"): from matplotlib import font_manager for f in font_manager.win32InstalledFonts(): try: system_fonts.append(font_manager.get_font(str(f)).family_name) except: pass # unknown error, skip this font else: # assuming fontconfig is installed and the command 'fc-list' exists try: # list scalable (non-bitmap) fonts fc_list = check_output(["fc-list", ":outline,scalable", "family"]) fc_list = fc_list.decode("utf8") system_fonts = [f.split(",")[0] for f in fc_list.splitlines()] system_fonts = list(set(system_fonts)) except: warnings.warn("error getting fonts from fc-list", UserWarning) def get_texcommand(): """Get chosen TeX system from rc.""" texsystem_options = ["xelatex", "lualatex", "pdflatex"] texsystem = rcParams.get("pgf.texsystem", "xelatex") return texsystem if texsystem in texsystem_options else "xelatex" def get_fontspec():
def gs_convert(pdffile, pngfile, dpi): cmd = [gs, '-dQUIET', '-dSAFER', '-dBATCH', '-dNOPAUSE', '-dNOPROMPT', '-sDEVICE=png16m', '-dUseCIEColor', '-dTextAlphaBits=4', '-dGraphicsAlphaBits=4', '-dDOINTERPOLATE', '-sOutputFile=%s' % pngfile, '-r%d' % dpi, pdffile] check_output(cmd, stderr=subprocess.STDOUT)
# Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # This is the default encoding, but it doesn't hurt to be explicit source_encoding = "utf-8" # The master toctree document. master_doc = 'contents' # General substitutions. from matplotlib.compat.subprocess import check_output SHA = check_output(['git', 'describe', '--dirty']).decode('utf-8').strip() html_context = {'sha': SHA} project = 'Matplotlib' copyright = ('2002 - 2012 John Hunter, Darren Dale, Eric Firing, ' 'Michael Droettboom and the Matplotlib development ' 'team; 2012 - 2018 The Matplotlib development team') # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version.