{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Document Python Code\n\nA simple solution to insert Python source code into your document.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import pylatex as pltx\nfrom pylatex import NoEscape\nfrom latexdocs import Document\nfrom latexdocs.preamble import append_packages, append_cover, __default__packages__\nfrom copy import copy\n\n\nlistings_config = r\"\"\"\n\\definecolor{mygreen}{rgb}{0,0.6,0}\n\\definecolor{mygray}{rgb}{0.5,0.5,0.5}\n\\definecolor{mymauve}{rgb}{0.58,0,0.82}\n\n\\lstset{ \n  backgroundcolor=\\color{white},   % choose the background color; you must add \\usepackage{color} or \\usepackage{xcolor}; should come as last argument\n  basicstyle=\\footnotesize,        % the size of the fonts that are used for the code\n  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace\n  breaklines=true,                 % sets automatic line breaking\n  captionpos=b,                    % sets the caption-position to bottom\n  commentstyle=\\color{mygreen},    % comment style\n  deletekeywords={...},            % if you want to delete keywords from the given language\n  escapeinside={\\%*}{*)},          % if you want to add LaTeX within your code\n  extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8\n  firstnumber=1000,                % start line enumeration with line 1000\n  frame=single,\t                   % adds a frame around the code\n  keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)\n  keywordstyle=\\color{blue},       % keyword style\n  language=Octave,                 % the language of the code\n  morekeywords={*,...},            % if you want to add more keywords to the set\n  numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)\n  numbersep=5pt,                   % how far the line-numbers are from the code\n  numberstyle=\\tiny\\color{mygray}, % the style that is used for the line-numbers\n  rulecolor=\\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))\n  showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'\n  showstringspaces=false,          % underline spaces within strings only\n  showtabs=false,                  % show tabs within strings adding particular underscores\n  stepnumber=2,                    % the step between two line-numbers. If it's 1, each line will be numbered\n  stringstyle=\\color{mymauve},     % string literal style\n  tabsize=2,\t                   % sets default tabsize to 2 spaces\n  title=\\lstname                   % show the filename of files included with \\lstinputlisting; also try caption instead of title\n}\n\"\"\"\n\nclass MyDocument(Document):\n    \n    def init_doc(self, **kwargs) -> pltx.Document:\n        \"\"\"\n        Initializes the document. This covers appending packages\n        and the preamble.\n\n        \"\"\"\n        dcls = self.__class__.documentclass\n        kwargs['documentclass'] = kwargs.get('documentclass', dcls)\n        kwargs['geometry_options'] = self._geometry_options\n        doc = pltx.Document(**kwargs)\n        packages = copy(__default__packages__)\n        packages['verbatim']\n        packages['listings']\n        packages['color']\n        doc = append_packages(doc, packages)\n        doc.preamble.append(NoEscape(listings_config))\n        doc = append_cover(doc, self._title, self._author, self._date)\n        return doc\n\ndoc = MyDocument()\n\nimport inspect\n\n#pycontent = open('plot_2_pycode.py').read()\npycontent = inspect.getsource(MyDocument.init_doc)\n#\\lstinputlisting[language=Python]{source_filename.py}\n\ncontent = r\"\"\"\n\\begin{env}[language=Python]\n{content}\n\\end{env}\n\"\"\".format(env=r'{lstlisting}', content=pycontent)\ndoc['Python code', 'Document a Python function'].append(NoEscape(content))\n\ncontent = r\"\"\"\n\\lstinputlisting[language=Python]{plot_1_mpl.py}\n\"\"\"\ndoc['Python code', 'Document a Python file'].append(NoEscape(content))\n\ndoc.build().generate_pdf('python_code', clean_tex=True, compiler='pdflatex')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import pypdfium2 as pdfium\nimport matplotlib.pyplot as plt\n\npdf = pdfium.PdfDocument(\"python_code.pdf\")\npage = pdf.get_page(0)\npil_image = page.render_topil()\nplt.imshow(pil_image)"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.8.13"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}