itikz icon indicating copy to clipboard operation
itikz copied to clipboard

Using itikz inside functions to return SVG objects

Open xblahoud opened this issue 5 years ago • 1 comments

  • itikz version: 0.1.5
  • Python version: 3.8.2
  • Operating System: Ubuntu 20.04

Description

I would like to call itikz to create an SVG object, without returning the TikZ-code first. In other words, I want to create a function that returns the SVG object returned by itikz. How can I do that?

What I Did

I've tried importing itikz and creating an TikzMagics object, but I do not know what arguments should I give to the constructor of TikzMagics.

import itikz
itikz.TikZMagics().itikz("--implicit-pic", "a")

The traceback is:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-62-b8977ef3b628> in <module>
----> 1 itikz.TikZMagics().itikz("--implicit-pic", "a")

<decorator-gen-156> in itikz(self, line, cell)

/usr/local/lib/python3.8/dist-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

/usr/local/lib/python3.8/dist-packages/itikz/__init__.py in itikz(self, line, cell)
    190             return
    191 
--> 192         ipython_ns = self.shell.user_ns
    193 
    194         if cell is None:

AttributeError: 'NoneType' object has no attribute 'user_ns'

xblahoud avatar Jun 11 '20 20:06 xblahoud

OK, I figured out a solution. The key is the fetch_or_compile_svg function.

I suggest adding the following into README or Quickstart notebook.

Using itikz as a library

The key function that itikz relies on is fetch_or_compile_svg. The usage is:

import itikz
itikz.fetch_or_compile_svg(complete_TeX_code, file_prefix='', 
                           working_dir=None, full_err=False, 
                           tex_program='pdflatex')

You can also use the predefined templates to build the complete TeX code.

tikzcode = r"""\draw[help lines] grid (5, 5);
\draw[fill=green] (1, 1) rectangle (2, 2);
\draw[fill=green] (2, 1) rectangle (3, 2);
\draw[fill=green] (3, 1) rectangle (4, 2);
\draw[fill=green] (3, 2) rectangle (4, 3);
\draw[fill=green] (2, 3) rectangle (3, 4);
"""
d = {"src": tikzcode, 
         "extras": "",
         "scale": 1.0
        }
texcode = itikz.IMPLICIT_PIC_TMPL.substitute(d)
itikz.fetch_or_compile_svg(texcode)

xblahoud avatar Jun 12 '20 20:06 xblahoud