Changes

Jump to navigation Jump to search
=Introduction=
 
'''After [http://www.ntg.nl/EuroTeX2009 eurotex meeting 2009],
I'm going to fix some typos here and there and
maybe expand some examples too. I estimated that around 20 September article and site will be in synch.'''
 
 
----
'''!! W A R N I N G !! '''
* ghostscript 8.64 ✔ [[#Ghostscript|here]]
* graphviz 2.24.0 ✔ [[#Graphviz|here]]
* ImageMagick-6.4.9 with pythonmagickwand ✔[[#ImageMagick|here]]
* fontforge 20090224 ✔ [[#Fontforge|here]] Useful to check symbols collision, and if one want to play with the last fontforge, eg to draw the outline of a glyph .
* R-2.8.1 with rpy2-2.0.3 (For Maurizio "Mau" Himmelman , GUIT) ✔ [[#R|here]] (see someone says also [http://micahelliott.com/2009/03/considering-r-as-python-supplement hereconsidering-r-as-python-supplement ]) .* quantlib 0.9.7 ✔ (need an example with output in pdf)* dbxml-2.4.16 (and sqlite) [[#dbxml|here]]
= Dedicated systems =
$HOME_LUN/sage/local/bin/python setup.py build
cd $HOME_LUN
mkdir tests-SAGEMATH && cd tests-SAGEMATH
##
## I have already installed prev. python.so, I don't want mess things
For more infos, see [http://root.cern.ch here] ([http://root.cern.ch/cgi-bin/print_hit_bold.pl/root/HowtoPyROOT.html?python#first_hit here] for python stuffs).
Under Linux installation is not difficult at all, so but in this case I choose to not create a luatex-lunatic apart, as done above for sagemath.<br/>See an example [[#ROOT| here]] .
= ConTeXt mkIV examples=This example shot how to literally embedHere I will collect some tex snippets,just to show some ideasoriginal python source code .
== Scipy ==Watch how python code <tttable> z = x*np.exp(-x**2-y**2) </tttr>is translated in lua code <tttd> z = x.__mul__( np.exp( (x.__pow__(2).__add__(y.__pow__(2))).__neg__() ) )</tt>  {| class="wikitable" |-|<texcode>
\startluacode
function testSCIPYtest_ROOT(figname,dpifilename)
require("python")
pg = python.globals()
python.apply = python.eval('apply') or {}
np = python.import("numpy")
mlab = python.import("matplotlib.mlab")
griddata = mlab.griddata
plt = python.import("matplotlib.pyplot")
ma = np.ma
random = python.import("numpy.random")
uniform = random.uniform
-- make up some randomly distributed data npts = 200 x = uniform(-2,2,npts) y = uniform(-2,2,npts) -- z = x*nppython.expexecute(-x**2-y**2)[[ z = x.__mul__( np.exp( (x.__pow__def run(2).__add__(y.__pow__(2))).__neg__() ) ) -- define grid. xi = np.linspace(-2.1,2.1,100filename): yi = np.linspace(-2.1 from ROOT import TCanvas,2.1,100)TGraph -- grid the data. from ROOT import gROOT zi = griddata(x,y,z,xi,yi) from math import sin -- contour the gridded data, plotting dots from array import array -- at the randomly spaced data points. -- we put this in python globals space -- CS = plt gROOT.contourReset(xi,yi,zi,15,linewidths=0.5,colors='k') pg.xi = xi ; pg.yi = yi ; pg.zi = zi args c1 = python.evalTCanvas("[xi,yi,zi,15]") kv = python.eval("{'linewidthc1': 0.5 ,'colors' :'kA Simple Graph Example'}") CS = python.apply(plt.contour, args,kv) -- pg.jet = plt.cm.jet args = python.eval("[xi200,yi10,zi700,15]"500 ) kv = python.eval("{'cmap': jet}") CS = python c1.applySetFillColor(plt.contourf, args,kv42 ) -- draw colorbar plt c1.colorbarSetGrid() -- plot data points. pg.x n = x; pg.y = y 20 args = python.eval("[ x,y]") kv = python.evalarray("{'marker': 'od'), array( 'cd':'b','s':5}") CS = python.apply(plt.scatter, args,kv) plt.xlim(-2,2) plt.ylim for i in range(-2,2n ): plt x.titleappend(string0.format('griddata test (%1*i points)',npts)) --plt y.savefigappend(figname, dpi, 'white') -- pg.figname = figname ; pg.dpi = dpi args = python.eval10*sin("x[fignamei]") kv = python+0.eval("{'dpi': dpi ,'facecolor' :'white'}"2 ) CS = python.apply(plt.savefig, args,kv)end\stopluacode
gr = TGraph( n, x, y ) gr.SetLineColor( 2 ) gr.SetLineWidth( 4 ) gr.SetMarkerColor( 4 ) gr.SetMarkerStyle( 21 ) gr.SetTitle( 'a simple graph' ) gr.GetXaxis().SetTitle( 'X title' )\def\testSCIPY[#1]{% gr.GetYaxis().SetTitle( 'Y title' ) gr.Draw( 'ACP' ) c1.Update() c1.Print(filename)\getparameters[scipy][#1]%)\ctxlua{testSCIPY run = pg.run run("\csname scipyfigname\endcsname",filename) "\csname scipydpi\endcsname")}%end\externalfigure[\csname scipyfigname\endcsname]%}stopluacode
\starttext
\startTEXpage
\testSCIPYctxlua{test_ROOT("testsin.pdf")}\rotate[fignamerotation=90]{test-scipy-1\externalfigure[testsin.pdf},dpi][width={1505cm]}]
\stopTEXpage
\stoptext
</texcode>|| </td><td> [[Image:Test-scipyTestsin.pngjpg|600px512px]] </td> </tr></table>|}We can do a bit better: separate python code from lua code .<br/>Save this in <tt>test-ROOT1.py</tt> (so it's also easy to test) :<pre>from ROOT import TCanvas, TGraph ,TGraphErrors,TMultiGraphfrom ROOT import gROOTfrom math import sinfrom array import array
def run(filename): c1 == Python Imaging Library TCanvas("c1","multigraph",200,10,700,500) c1.SetGrid(PIL) ==
{| class # draw a frame to define the range mg = TMultiGraph() # create first graph n = 24; x = array('d',range(24)) data = file('data').readlines() for line in data: line = line.strip() y = array('d',[float(d) for d in line.split()]) gr = TGraph(n,x,y) gr.Fit("pol6","wikitableq" ) mg.Add(gr)  mg.Draw("ap")  #force drawing of canvas to generate the fit TPaveStats c1.Update() c1.Print(filename) </pre>Here file 'data' is a 110 lines file with 24 floats values space separated,ie <br/><tt> 20.6000 19.4000 19.4000 18.3000 17.8000 16.1000 16.7000 21.1000 23.3000 26.1000 26.1000 27.2000 27.8000 28.3000 28.3000 27.2000 25.6000 22.8000 21.7000 21.7000 21.7000 21.7000 21.7000 21.7000 </tt>.<br/>Now a tex file, with a simple layer in lua as interface for python:{||-|<texcode>
\startluacode
function testPILtest_ROOT(imageorig,imagesepiafilename)
require("python")
PIL_Image test = python.import("PIL.Image") PIL_ImageOps = python.import("PIL.ImageOps"'test-ROOT1') python.execute([[def make_linear_ramp(white): ramp = [] r, g, b = white for i in range(255): ramp.extend((r*i/255, g*i/255, b*i/255)) return ramp]]) -- make sepia ramp (tweak color as necessary) sepia = python.eval("make_linear_ramp((255, 240, 192))") im = PIL_Image.open(imageorig) -- convert to grayscale if not(im.mode == "L") then im = im.convert("L") end -- optional: apply contrast enhancement here, e.g. im = PIL_ImageOps.autocontrast(im)  -- apply sepia palette im.putpalette(sepia)  -- convert back to RGB so we can save it as JPEG -- (alternatively, save it in PNG or similar) im = im.convert("RGB")  imtest.saverun(imagesepiafilename)end
\stopluacode
\defstarttext\SepiaImage#1#2{%startTEXpage\ctxlua{testPILtest_ROOT("#1","#2data.pdf")}%\startcombinationrotate[2*1rotation=90]{\externalfigure[#1]}{\ss Origdata.}{\externalfigure[#2pdf]}{\ss Sepia}\stopcombination}  \starttext\startTEXpage\SepiaImage{lena.jpg}{lena-sepia.jpg}
\stopTEXpage
\stoptext
</texcode> || [[Image:Test-PILROOT1.pngjpg|330px300px]]
|}
=ConTeXt mkIV examples= ROOT Here I will collect some tex snippets,just to show some ideas. == Scipy ==This example shot Watch how to literally embedpython code <tt> z = x*np.exp(-x**2-y**2) </tt>original python source is translated in lua code <tt> z = x.__mul__( np.exp( (x.__pow__(2).__add__(y.__pow__(2))).__neg__() ) )</tt> 
{|class="wikitable"
|-
|<texcode>
\startluacode
function test_ROOTtestSCIPY(filenamefigname,dpi)
require("python")
pg = python.globals()
python.apply = python.eval('apply') or {}
np = python.import("numpy")
mlab = python.import("matplotlib.mlab")
griddata = mlab.griddata
plt = python.import("matplotlib.pyplot")
ma = np.ma
random = python.import("numpy.random")
uniform = random.uniform
python-- make up some randomly distributed data npts = 200 x = uniform(-2,2,npts) y = uniform(-2,2,npts) -- z = x*np.executeexp([[-x**2-y**2)def run z = x.__mul__( np.exp( (x.__pow__(2).__add__(y.__pow__(2))).__neg__(filename):) ) -- define grid. from ROOT import TCanvas xi = np.linspace(-2.1,2.1, TGraph100) from ROOT import gROOT yi = np.linspace(-2.1,2.1,100) -- grid the data. from math import sin zi = griddata(x,y,z,xi,yi) from array import array -- contour the gridded data, plotting dots -- at the randomly spaced data points. -- we put this in python globals space gROOT -- CS = plt.Resetcontour(xi,yi,zi,15,linewidths=0.5,colors='k') pg.xi = xi ; pg.yi = yi ; pg.zi = zi args = python.eval("[xi,yi,zi,15]") c1 kv = TCanvaspython.eval( "{'c1linewidth': 0.5 , 'A Simple Graph Examplecolors':'k'}") CS = python.apply(plt.contour, args, 200kv) -- pg.jet = plt.cm.jet args = python.eval("[xi, 10yi, 700zi, 500 15]") kv = python.eval("{'cmap': jet}") c1 CS = python.SetFillColorapply( 42 plt.contourf, args,kv) c1 -- draw colorbar plt.SetGridcolorbar() -- plot data points. n pg.x = x; pg.y = 20y args = python.eval("[x, y ]") kv = arraypython.eval("{'marker': 'o', 'c':'b','s':5}") CS = python.apply(plt.scatter, args,kv) plt.xlim(-2,2) plt.ylim(-2,2) plt.title(string.format( 'dgriddata test (%i points)' ,npts)) --plt.savefig(figname, dpi, array'white') -- pg.figname = figname ; pg.dpi = dpi args = python.eval("[figname]") kv = python.eval( "{'dpi'd: dpi ,' facecolor' :'white'}") CS = python.apply(plt.savefig, args,kv)end\stopluacode
for i in range( n ): x.append( 0.\def\testSCIPY[#1*i )]{% y.append( 10*sin( x\getparameters[scipy][i#1]+0.2 ) )%  gr = TGraph\ctxlua{testSCIPY( n"\csname scipyfigname\endcsname", x, y ) gr.SetLineColor( 2 ) gr.SetLineWidth( 4 ) gr.SetMarkerColor( 4 ) gr.SetMarkerStyle( 21 ) gr.SetTitle( 'a simple graph' ) gr.GetXaxis().SetTitle( 'X title' ) gr.GetYaxis().SetTitle( 'Y title' ) gr.Draw( 'ACP' ) c1.Update() c1.Print(filename "\csname scipydpi\endcsname")}%\externalfigure[\csname scipyfigname\endcsname]]) run = pg.run run(filename)end%\stopluacode}
\starttext
\startTEXpage
\ctxluatestSCIPY[figname={test_ROOT("testsintest-scipy-1.pdf")}\rotate[rotation,dpi=90]{\externalfigure[testsin.pdf][width=5cm150}]}
\stopTEXpage
\stoptext
</texcode> || [[Image:TestsinTest-scipy.jpgpng|512px600px]]
|}
We can do a bit better: separate python code from lua code .<br/>Save this in <tt>test-ROOT1.py</tt> == Python Imaging Library (so it's also easy to testPIL) :<pre>from ROOT import TCanvas, TGraph ,TGraphErrors,TMultiGraphfrom ROOT import gROOTfrom math import sinfrom array import array==
def run{| class="wikitable" |-|<texcode>\startluacodefunction testPIL(filenameimageorig,imagesepia): c1 = TCanvas require("c1python",) PIL_Image = python.import("multigraphPIL.Image",200,10,700,500) c1 PIL_ImageOps = python.SetGridimport("PIL.ImageOps") python.execute([[ # draw a frame to define the range mg = TMultiGraphdef make_linear_ramp(white): # create first graphramp = [] n r, g, b = 24;white x = array('d',for i in range(24)255): data = file ramp.extend(('data'r*i/255, g*i/255, b*i/255).readlines() for line in data:return ramp]]) line = line.strip -- make sepia ramp (tweak color as necessary) y sepia = arraypython.eval("make_linear_ramp('d'(255, 240,[float(d192))") for d in line im = PIL_Image.splitopen(imageorig)]) gr -- convert to grayscale if not(im.mode == TGraph(n,x,y"L") then grim = im.Fitconvert("pol6L") end -- optional: apply contrast enhancement here,"q")e.g. mg im = PIL_ImageOps.Addautocontrast(grim)
mg-- apply sepia palette im.Drawputpalette("ap"sepia)
#force drawing of canvas -- convert back to generate the fit TPaveStatsRGB so we can save it as JPEG c1-- (alternatively, save it in PNG or similar) im = im.Updateconvert("RGB"c1im.Printsave(filenameimagesepia)end\stopluacode \def\SepiaImage#1#2{%\ctxlua{testPIL("#1","#2")}%\startcombination[2*1]{\externalfigure[#1]}{\ss Orig.}{\externalfigure[#2]}{\ss Sepia}\stopcombination}
</pre>
Here file 'data' is a 110 lines file with 24 floats values space separated,
ie <br/><tt> 20.6000 19.4000 19.4000 18.3000 17.8000 16.1000 16.7000 21.1000 23.3000 26.1000 26.1000 27.2000 27.8000 28.3000 28.3000 27.2000 25.6000 22.8000 21.7000 21.7000 21.7000 21.7000 21.7000 21.7000 </tt>.<br/>
Now a tex file, with a simple layer in lua as interface for python:
{|
|-
|<texcode>
\startluacode
function test_ROOT(filename)
require("python")
test = python.import('test-ROOT1')
test.run(filename)
end
\stopluacode
\starttext
\startTEXpage
\ctxluaSepiaImage{test_ROOT("datalena.pdf")jpg}\rotate[rotation=90]{\externalfigure[datalena-sepia.pdf]jpg}
\stopTEXpage
\stoptext
</texcode> || [[Image:Test-ROOT1PIL.jpgpng|300px330px]]
|}
== Fontforge ==
In this example, we will use Metapost to draw a bezier curve of a glyph (''Note: starting from Metapost 1.200 it is now possible to get the actual path drawing routines from a font glyph, so this example is only to show how to translate a path in metapost'').<br/>
We will use 3-layer approach:
# a python layer that export a class,
# a lua layer to manage objects of this class
# a (con)TeX(t) layer that exports macros, because tex works very well with macros .
Let== ImageMagick ==''ImageMagick® '' ([http://www.imagemagick.org/script/index.php here]) ''is a software suite to create, edit, and compose bitmap images. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF. Use ImageMagick to translate, flip, mirror, rotate, scale, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.''s start with There are at least two python codebindings, <tt>test-fontforgeand this time I consider[http://www.procoders.py<net/tt>:?p=39 PythonMagickWand] which is a binding "ala" ctypes way . Code is simple<pretexcode>import sys\usetypescriptfile[type-gentium]\usetypescript[gentium]\setupbodyfont[gentium,10pt]import fontforge\setuppapersize[A5][A5]\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]
class simpledraw\startluacodefunction testimagemagick(objectbox,t): local w local h local d local f local res = 118.11023622047244094488 -- 300 dpi local opacity = 25 local sigma = 15 local x = 10 local y = 10
def __init__ require(self,font_file"python") pg = python.globals() PythonMagickWand = python.import("PythonMagickWand") w = math.floor((tex.wd[box] / 65536 ) / 72.27 * 2.54 * res ): self h = math.floor(((tex.ht[box] / 65536) + (tex.font dp[box] / 65536)) / 72.27 *2.54 *res ) f = fontforgestring.openformat(font_file"%s.png",t)
def getcurve wand = PythonMagickWand.NewMagickWand(self,letter): self background = PythonMagickWand.glname = letter res = dictNewPixelWand(0) try : glyph_letter = [ g for g in self -- PythonMagickWand.font.glyphsMagickNewImage() if g.glyphname == self.glname][0] except Exception wand,w,h,e : res['err'] = str(ebackground) return res cnt= glyph_letter.layers[1][0] res['is_quadratic'] = cnt.is_quadratic res['closed'] = cnt PythonMagickWand.closed res['points'] = [MagickNewImage(p.xwand,w,p.yh,"%i" %p.on_curvebackground) for p in cnt ] res['design_size'] = self.font.design_size res['em'] = self.font.em return res
PythonMagickWand.MagickSetImageResolution(wand,res,res)
PythonMagickWand.MagickSetImageUnits(wand,PythonMagickWand.PixelsPerCentimeterResolution)
PythonMagickWand.MagickShadowImage(wand,opacity,sigma,x,y)
PythonMagickWand.MagickWriteImage(wand ,f)
def getmpostoutline print(selfw,letter): res = self.getcurve(letterh,f) path = '..'.join( [str((p[0],p[1])) for p in res['points'] if p[2] == '1'] )end return path\stopluacode
def getmpostpoints(self,letter):
res = self.getcurve(letter)
path = [str((p[0],p[1])) for p in res['points'] if p[2] == '1']
return path
def getmpostpointsSugar(self,letter):
res = self.getcurve(letter)
path = 'drawdot '.join( ["%s;" %str((p[0],p[1])) for p in res['points'] if p[2] == '1'] )
return 'drawdot ' +path
\def\testimagemagick[#1]{%
\getparameters[imagemagick][#1]%
\ctxlua{testimagemagick(\csname imagemagickbox\endcsname,"\csname imagemagickfilename\endcsname")}%
}
if __name__ \newcount\shdw\long\def\startShadowtext#1\stopShadowtext{%\bgroup%\setbox0=\vbox{#1}%\testimagemagick[box=0,filename= '__main__':{shd-\the\shdw}]%%% s = simpledraw("koeieletters\defineoverlay[backg][{\externalfigure[shd-\the\shdw.pfb")png]}]% res \framed[background=backg,frame=off,offset= s.getmpostpointsSugar('C')4pt]{\box0}%%%\framed{\box0}\global\advance\shdw by 1% print res\egroup%</pre>}
Note the <tt>'__main__'</tt> check, so we can test this class from python. <br/>Next lua layer, which in this case is embed in a tex file:<texcode>\startluacodefunction testFontforge(fontfile,letter) require("python") testoutlines = python.import("test-fontforge") s = testoutlines.simpledraw(fontfile) g = s.getmpostoutline(letter) p = s.getmpostpointsSugar(letter) tex.sprint(tex.ctxcatcodes,"\\startMPcode") tex.sprint(tex.ctxcatcodes,"pickup pencircle scaled 1pt;") tex.sprint(tex.ctxcatcodes,string.format("draw %s .. cycle;",g) ) tex.sprint(tex.ctxcatcodes,"pickup pencircle scaled 8pt;") tex.sprint(tex.ctxcatcodes,string.format("%s",p) ) tex.sprint(tex.ctxcatcodes,"\\stopMPcode")end\stopluacode  \def\Outline[#1]{%\getparameters[test][#1]%\ctxlua{testFontforge("\testfontfile", "\testletter")}%} \starttext\startTEXpage\Outline[letter={C}, fontfile={lmmono10-regular.otf}]%\Outline[letter={o}, fontfile={lmmono10-regular.otf}]startShadowtext%\Outline[letter={n}, fontfile={lmmono10-regular.otf}]%\Outline[letter={T}, fontfile={lmmono10-regular.otf}]%\Outline[letter={e}, fontfile={lmmono10-regular.otf}]%\Outline[letter={X}, fontfile={lmmono10-regular.otf}]%input tufte\Outline[letter={t}, fontfile={lmmono10-regular.otf}]stopShadowtext%
\stopTEXpage
\stoptext
</texcode>
And here is the result:
Here we use <tt>tex.sprint(tex.ctxcatcodes,"\\stopMPcode")</tt> to inject tex code (actually Metapost code) into TeX parser .<br/><tt>\Outline</tt> is the TeX layer: of course one can write <tt>\Outline</tt> and <tt>testFontforge</tt> in a different manner to avoid use of tex.sprint(..) <br/>And this is the result: <br/>[[Image:Test-fontforgeimagemagick.png|900px]]
== Fontforge ==In this example, we will use Metapost to draw a bezier curve of a glyph (''Note: starting from Metapost 1.200 it is now possible to get the actual path drawing routines from a font glyph, so this example is only to show how to translate a path in metapost'')..ok<br/>We will use 3-layer approach:# a python layer that export a class,it's not correct # a lua layer to manage objects of this class# a (con)TeX(why?t)layer that exports macros, but it looks funny :)because tex works very well with macros .
== Ghostscript ==Let's start with python code, <tt>test-fontforge.py</tt>:There are essentially 2 kind of use of ghostscript :<pre>* convert an existing eps / ps file in pdf ;import sys* use a program in postscript that take an input, do something and make a ps output ( e.g. a barcode/label generator ).import fontforge
For the first case, we consider an implementation of eps2pdf, being ps2pdf virtually the same .<br/>
Actually there is not a python binding of ghostscript, so we build a simple wrapper
using ctypes module.
<pre>import ctypesimport sysclass simpledraw(object):
def __init__(self,font_file):
self.font = fontforge.open(font_file)
 
def getcurve(self,letter):
self.glname = letter
res_Array = []
res = dict()
try :
#glyph_letter = [ g for g in self.font.glyphs() if g.glyphname == self.glname][0]
g = self.font[letter]
except Exception ,e :
res['err'] = str(e)
res_Array.append(res)
return res_Array
layer_idx = 0;
for layer_name in g.layers:
layer = g.layers[layer_name]
for contour_idx in range(len(layer)):
res = dict()
contour = layer[contour_idx]
contour_name = contour.name
res['name'] = contour.name
res['is_quadratic'] = contour.is_quadratic
res['closed'] = contour.closed
res['points'] = [(p.x,p.y,"%i" %p.on_curve) for p in contour ]
res['design_size'] = self.font.design_size
res['em'] = self.font.em
res_Array.append(res)
return res_Array
class gs(object):
def __init__drawmpostpath(self,letter): res_Array = self.getcurve(letter) state = 0 paths = '' for res in res_Array: temp = '' for p in res['points'] : if p[2]=='1' : if state == 1 : temp = temp + '-- (%s,%s)' %(p[0] ,p[1]) ; state = 1; continue else: temp = temp + '.. (%s,%s)' %(p[0] ,p[1]) ; state = 1; continue if state == 1 : temp = temp + ' .. controls (%s,%s)' %(p[0],p[1]) ; state =2; continue if state == 2 : temp = temp + ' and (%s,%s) ' %(p[0],p[1]) ; state =0; continue if res['closed'] : if state == 1 : temp = 'draw ' + temp[2:] + " -- cycle;\n" else: temp = 'draw ' + temp[2:] + " .. cycle;\n" else: temp = 'draw ' + temp[2:] + ";\n" paths = paths + temp return paths 
self.ierrors = dict()
self.ierrors['e_unknownerror'] = -1
self.ierrors['e_dictfull'] = -2
self.ierrors['e_dictstackoverflow'] = -3
self.ierrors['e_dictstackunderflow'] = -4
self.ierrors['e_execstackoverflow'] = -5
self.ierrors['e_interrupt'] = -6
self.ierrors['e_invalidaccess'] = -7
self.ierrors['e_invalidexit'] = -8
self.ierrors['e_invalidfileaccess'] = -9
self.ierrors['e_invalidfont'] = -10
self.ierrors['e_invalidrestore'] = -11
self.ierrors['e_ioerror'] = -12
self.ierrors['e_limitcheck'] = -13
self.ierrors['e_nocurrentpoint'] = -14
self.ierrors['e_rangecheck'] = -15
self.ierrors['e_stackoverflow'] = -16
self.ierrors['e_stackunderflow'] = -17
self.ierrors['e_syntaxerror'] = -18
self.ierrors['e_timeout'] = -19
self.ierrors['e_typecheck'] = -20
self.ierrors['e_undefined'] = -21
self.ierrors['e_undefinedfilename'] = -22
self.ierrors['e_undefinedresult'] = -23
self.ierrors['e_unmatchedmark'] = -24
self.ierrors['e_VMerror'] = -25
self.ierrors['e_configurationerror'] = -26
self.ierrors['e_undefinedresource'] = -27
self.ierrors['e_unregistered'] = -28
self.ierrors['e_invalidcontext'] = -29
self.ierrors['e_invalidid'] = -30
self.ierrors['e_Fatal'] = -100
self.ierrors['e_Quit'] = -101
self.ierrors['e_InterpreterExit'] = -102
self.ierrors['e_RemapColor'] = -103
self.ierrors['e_ExecStackUnderflow'] = -104
self.ierrors['e_VMreclaim'] = -105
self.ierrors['e_NeedInput'] = -106
self.ierrors['e_Info'] = -110
def drawmpostpoints(self,letter): res_Array = self.libgspath getcurve(letter) dots = '' for res in res_Array: temp = '/opt/luatex/luatex-lunatic/lib/libgs\n'.sojoin( ["drawdot %s;" %str((p[0],p[1])) for p in res['points'] if p[2] == '1'] ) + "\n" dots = dots + temp return dots
self.OutFile = ''
self.InFile = ''
self.args = []
if __name__ == '__main__': s = simpledraw("lmmono10-regular.otf") def appendargs #res = s.getmpostpointsSugar(self,arg'C'): if arg #print res #print s.findgetmpostoutline('-sOutputFileC')>= 0: return if arg print s.findgetcurve('-c quite')>= 0: return self print s.argsdrawmpostpath('e') print s.appenddrawmpostpoints(arg'e')
</pre>
def rawappendargs(selfNote the <tt>'__main__'</tt> check,arg)so we can test this class from python. <br/>Next lua layer, which in this case is embed in a tex file: self.args.append(arg)<texcode>
\setupcolors[state=start]
\startluacodefunction testFontforge(fontfile,letter) def runrequire(self"python"): libgs testoutlines = ctypespython.CDLLimport(self"test-fontforge") s = testoutlines.libgspathsimpledraw(fontfile) g = s.drawmpostpath(letter) exit_status p = ctypess.c_intdrawmpostpoints(letter) code --print( string.format("\%s = \%s == ctypes", letter,g )) tex.sprint(tex.ctxcatcodes,"\\startMPcode") tex.c_intsprint(1tex.ctxcatcodes,"pickup pencircle scaled 1pt;") code1 = ctypes tex.sprint(tex.ctxcatcodes,string.format("\%s",g) ) tex.c_intsprint(tex.ctxcatcodes,"pickup pencircle scaled 8pt;") instance = ctypes tex.sprint(tex.ctxcatcodes,string.c_void_pformat(None"\%s",p) ) exit_code = ctypes tex.c_intsprint(tex.ctxcatcodes,"\\stopMPcode")end\stopluacode
code.value = libgs.gsapi_new_instance(ctypes.byref(instance), None) if code.value == 0 :\def\Outline[#1]{% libgs.gsapi_set_stdio(instance, None, None, None) self.args.insert(0,'') \getparameters[test][# if len(self.OutFile) > 0: self.args.append('-sOutputFile=%s' 1]%self.OutFile) if len(self.InFile) > 0: self.args.append\ctxlua{testFontforge("%s\testfontfile", "\testletter" )}%self.InFile) self.args.append('-c quit') arguments = self.args # argc = ctypes.c_int(len(arguments)) argv = (ctypes.c_char_p * argc.value)(*arguments) code.value = libgs.gsapi_init_with_args(instance, argc, argv)}
code1\starttext\startTEXpage\Outline[letter={C}, fontfile={lmmono10-regular.otf}]%\Outline[letter={o}, fontfile={lmmono10-regular.otf}]%\Outline[letter={n}, fontfile={lmmono10-regular.otf}]%\Outline[letter={T}, fontfile={lmmono10-regular.value otf}]%\Outline[letter={e}, fontfile={lmmono10-regular.otf}]%\Outline[letter={X}, fontfile={lmmono10-regular.otf}]%\Outline[letter={t}, fontfile= libgs{lmmono10-regular.gsapi_exit(instance)otf}]%\stopTEXpage\stoptext</texcode>
if Here we use <tt>tex.sprint(tex.ctxcatcodes,"\\stopMPcode")</tt> to inject tex code (actually Metapost code) into TeX parser .<br/><tt>\Outline</tt> is the TeX layer: of course one can write <tt>\Outline</tt> and <tt>testFontforge</tt> in a different manner to avoid use of tex.sprint(..) <br/>And this is the result: <br/>[[Image:Test-fontforge.value png|900px]] == 0 or code.value Ghostscript == self.ierrors['e_Quit']There are essentially 2 kind of use of ghostscript : code* convert an existing eps / ps file in pdf ;* use a program in postscript that take an input, do something and make a ps output ( e.g.value = code1a barcode/label generator ).value
if codeFor the first case, we consider an implementation of eps2pdf, being ps2pdf virtually the same .value == self<br/>Actually there is not a python binding of ghostscript, so we build a simple wrapper using ctypes module <tt>testgs.ierrors['e_Quit']py</tt> : code.value = 0
libgs.gsapi_delete_instance(instance)<pre>import ctypesimport sys
exit_status.value = 0
if __name__ == '__main__': pyctyps = class gs(object) pyctyps.appendargs('-q') pyctyps.appendargs('-dNOPAUSE') pyctyps.appendargs('-dEPSCrop') pyctyps.appendargs('-sDEVICE=pdfwrite') pyctyps.InFile = 'test.eps' pyctyps.OutFile = 'test.pdf' pyctyps.run():
</pre> def __init__(self):
The tex code self.ierrors = dict() self.ierrors['e_unknownerror'] = -1 self.ierrors['e_dictfull'] = -2 self.ierrors['e_dictstackoverflow'] = -3 self.ierrors['e_dictstackunderflow'] = -4 self.ierrors['e_execstackoverflow'] = -5 self.ierrors['e_interrupt'] = -6 self.ierrors['e_invalidaccess'] = -7 self.ierrors['e_invalidexit'] = -8 self.ierrors['e_invalidfileaccess'] = -9<texcode> self.ierrors['e_invalidfont'] = -10\startluacode self.ierrors['e_invalidrestore'] = -11function testgs(epsin,pdfout) self.ierrors['e_ioerror'] = -12 require("python") self.ierrors['e_limitcheck'] = -13 gsmodule self.ierrors['e_nocurrentpoint'] = python-14 self.import("testgs") ierrors['e_rangecheck'] = -15 ghost self.ierrors['e_stackoverflow'] = gsmodule-16 self.gs()ierrors['e_stackunderflow'] = -17 ghost self.appendargs(ierrors['e_syntaxerror'] = -q18 self.ierrors[')e_timeout'] = -19 ghost self.appendargs(ierrors['e_typecheck'] = -dNOPAUSE20 self.ierrors[')e_undefined'] = -21 ghost self.appendargs(ierrors['e_undefinedfilename'] = -dEPSCrop22 self.ierrors[')e_undefinedresult'] = -23 ghost self.appendargs(ierrors['e_unmatchedmark'] = -sDEVICE24 self.ierrors['e_VMerror'] =pdfwrite-25 self.ierrors[')e_configurationerror'] = -26 ghost self.InFile ierrors['e_undefinedresource'] = epsin-27 ghost self.OutFile ierrors['e_unregistered'] = pdfout-28 ghost self.run()ierrors['e_invalidcontext'] = -29end self.ierrors['e_invalidid'] = -30\stopluacode self.ierrors['e_Fatal'] = -100 self.ierrors['e_Quit'] = -101\def\epstopdf#1#2{\ctxlua{testgs("#1","#2")}} self.ierrors['e_InterpreterExit'] = -102\def\EPSfigure self.ierrors[#1'e_RemapColor']{%lazy way to load eps= -103\epstopdf{#1 self.eps}{#1ierrors['e_ExecStackUnderflow'] = -104 self.pdf}%ierrors['e_VMreclaim'] = -105\externalfigure self.ierrors[#1'e_NeedInput'] = -106 self.pdfierrors['e_Info']%= -110  self.libgspath = '/opt/luatex/luatex-lunatic/lib/libgs.so'} self.OutFile = '' self.InFile = ''
\starttext\startTEXpage\startcombination[2*1]{\EPSfigure[tiger]}{\ss tiger.eps}{\EPSfigure[golfer]}{\ss golfer self.eps}\stopcombination\stopTEXpage\stoptext</texcode>and the result :<br/>args = [[Image:Testgs.png|900px]]
Another example:<br/>here we use a library to generate barcodes [http://www.terryburton.co.uk/barcodewriter (see here)] .<texcode>\startluacodefunction epstopdf(epsin,pdfout) require("python") gsmodule = python.import("testgs") ghost = gsmodule.gs() ghost. def appendargs('-q'self,arg): ghost if arg.appendargsfind('-dNOPAUSEsOutputFile')>= 0: return ghost if arg.appendargsfind('-dEPSCropc quit') ghost.appendargs('-sDEVICE>=pdfwrite') ghost.InFile = epsin0: return ghost self.OutFile = pdfout ghostargs.runappend(arg)end
function barcode(text,type,options,savefile)
require("python")
gsmodule = python.import("testgs")
barcode_string = string.format def rawappendargs("%%!\n100 100 moveto (%sself,arg) : self.args.append(%s) %s barcode showpage" ,text,options,typearg)
psfile = string.format("%s.ps",savefile)
epsfile = string.format("%s.eps",savefile)
pdffile = string.format("%s.pdf",savefile)
temp = io.open(psfile,'w')
temp:write(tostring(barcode_string),"\n")
temp:flush()
io.close(temp)
ghost = gsmodule.gs()
ghost.rawappendargs('-q')
ghost.rawappendargs('-dNOPAUSE')
ghost.rawappendargs('-sDEVICE=epswrite')
ghost.rawappendargs(string.format('-sOutputFile=%s',epsfile))
ghost.rawappendargs('barcode.ps')
ghost.InFile= psfile
ghost.run()
end
\stopluacode
\ def\epstopdf#1#2{\ctxlua{epstopdfrun("#1","#2"self)}}:\def\EPSfigure[#1]{%lazy way to load eps\epstopdf{#1 libgs = ctypes.eps}{#1CDLL(self.pdf}%\externalfigure[#1.pdf]%}libgspath)
\def\PutBarcode[#1]{% exit_status = ctypes.c_int()\getparameters[bc][# code = ctypes.c_int(1]%)\ctxlua{barcode code1 = ctypes.c_int("\csname bctext\endcsname","\csname bctype\endcsname","\csname bcoptions\endcsname","\csname bcsavefile\endcsname" )}%\expanded{\EPSfigure[\csname bcsavefile\endcsname]}% instance = ctypes.c_void_p(None)} exit_code = ctypes.c_int()
\starttext
\startTEXpage
\startcombination[2*2]
{\PutBarcode[text={CODE 39},type={code39},options={includecheck includetext},savefile={TEMP1}]}{\ss code39}
{\PutBarcode[text={CONTEXT},type={code93},options={includecheck includetext},savefile={TEMP2}]}{\ss code93}
{\PutBarcode[text={977147396801},type={ean13},options={includetext},savefile={TEMP3}]}{\ss ean13}
{\PutBarcode[text={0123456789},type={interleaved2of5},options={includecheck includetext},savefile={TEMP4}]}{\ss interleaved2of5}
\stopcombination
\stopTEXpage
\stoptext
</texcode>
[[Image code.value = libgs.gsapi_new_instance(ctypes.byref(instance), None) if code.value == 0 : libgs.gsapi_set_stdio(instance, None, None, None) self.args.insert(0,'') # if len(self.OutFile) > 0:Test self.args.append('-ghostscriptsOutputFile=%s' %self.OutFile) if len(self.InFile) > 0: self.args.append("%s" %self.InFile) self.args.append('-barcodec quit') arguments = self.args # argc = ctypes.c_int(len(arguments)) argv = (ctypes.c_char_p * argc.value)(*arguments) code.value = libgs.png|900px]]gsapi_init_with_args(instance, argc, argv)
code1.value == Graphviz == [http://wwwlibgs.graphviz.org Graphviz] is a Graph Visualization Software .<br/>Standard distribution comes with several binding gsapi_exit(lua and python among othersinstance) so it's not difficult to integrate in luatex lunatic .<br/>In this example, we draw a graph of the nodes of <context>\TeX</context><pre>\def\StudyBox#1{%\startluacoderequire "python"gv if code.value == python0 or code.import("gv")g value == gvself.digraph("G")ierrors['e_Quit']:gv code.setv(g,'rankdir','LR')value = code1.value
nodes if code.value = nodes or {}= self.ierrors['e_Quit']: code.value = 0
local nd = {};local kd = {}; libgs.gsapi_delete_instance(instance)
local k exit_status.value = 0;local function nodesprint(head,n) while head do local id = head.id local oldn = n ndlbl = string.format("nd_\%03d",k) texio.write_nl(string.format("id=\%s, ndlbl=\%s",id,ndlbl))
if id __name__ == node.id("vlist") then k = k + 1'__main__': nd[n] pyctyps = gv.nodegs(g,ndlbl) res = gv pyctyps.setvappendargs(nd[n],"shape","record"'-q') res = gv pyctyps.setvappendargs(nd[n],"label",tostring(k'-dNOPAUSE') .. " " .. "vlist" pyctyps.. "\|id:" .. tostringappendargs(head.id'-dEPSCrop') .. "\|subtype:" pyctyps.. tostringappendargs(head.subtype'-sDEVICE=pdfwrite') .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") pyctyps.InFile = 'test. eps' "\|width:" .. tostring(head.width) pyctyps.OutFile = 'test. pdf' "\|depth:" pyctyps.. tostringrun(head.depth) .. "\|height:" .. tostring(head.height) .. "\|dir:" .. tostring(head.dir) .. "\|shift:" .. tostring(head.shift) .. "\|glue_order:" .. tostring(head.glue_order) .. "\|glue_sign:" .. tostring(head.glue_sign) .. "\|glue_set:" .. tostring(head.glue_set) .. "\|list:" .. string.gsub(tostring(head.list),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") .. "\|next:" .. string.gsub(tostring(head.next),"([/pre><])","\\\%1")) end
if id The tex code<texcode>\startluacodefunction testgs(epsin,pdfout) require("python") gsmodule == nodepython.idimport("ruletestgs") then k ghost = k + 1gsmodule.gs() ghost.appendargs('-q') nd[n] = gv ghost.nodeappendargs(g,ndlbl'-dNOPAUSE') res = gv ghost.setvappendargs('-dEPSCrop') ghost.appendargs('-sDEVICE=pdfwrite') ghost.InFile = epsin ghost.OutFile = pdfout ghost.run()end\stopluacode \def\epstopdf#1#2{\ctxlua{testgs(nd[n],"shape#1","record#2")}} res = gv.setv(nd\def\EPSfigure[n#1],"label",tostring(k) {%lazy way to load eps\epstopdf{#1.eps}{#1. " " .. "rule" .pdf}%\externalfigure[#1. pdf]%}  "\|id:" .. tostring(head.id) .. starttext "\|subtype:" .. tostring(head.subtype) startTEXpage\startcombination[2*1]{\EPSfigure[tiger]}{\ss tiger.eps}{\EPSfigure[golfer]}{\ss golfer. eps} "\stopcombination\stopTEXpage\stoptext</texcode>and the result :<br/>[[Image:Testgs.png|attr900px]] Another example:<br/>here we use a library to generate barcodes [http:" //www.terryburton. stringco.gsubuk/barcodewriter (tostringsee here)] .<texcode>\startluacodefunction epstopdf(head.attrepsin,pdfout), require("python") gsmodule = python.import([><])","\\\%1testgs") ghost = gsmodule.gs() ghost. appendargs('-q') "\|width:" ghost.appendargs('-dNOPAUSE') ghost. tostringappendargs(head'-dEPSCrop') ghost.widthappendargs('-sDEVICE=pdfwrite') ghost.. InFile = epsin "\|depth:" ghost.OutFile = pdfout ghost. tostringrun()end function barcode(head.depthtext,type,options,savefile) .. require("\|height:python" ) gsmodule = python.. tostringimport(head.height"testgs")   barcode_string = string.. format("%%!\|dir:" .. tostringn100 100 moveto (head.dir%s) (%s) %s barcode showpage" ,text,options,type) .. "\|next:" .. psfile = string.gsubformat(tostring(head"%s.nextps",savefile)," epsfile = string.format([><])","\\\%1s.eps",savefile) pdffile = string.format("%s. pdf"\|prev,savefile)  temp = io.open(psfile,'w') temp:" .. string.gsubwrite(tostring(head.prevbarcode_string),"\n") temp:flush([><])","\\\%1")) end if id io.close(temp) ghost == nodegsmodule.idgs("ins") then k = k + 1 nd[n] = gv ghost.rawappendargs('-q') ghost.noderawappendargs(g,ndlbl'-dNOPAUSE') res = gv ghost.setvrawappendargs(nd[n]'-sDEVICE=epswrite') ghost.rawappendargs(string.format('-sOutputFile=%s',"shape","record"epsfile)) res = gv ghost.setvrawappendargs(nd[n],"label",tostring(k'barcode.ps') ghost.InFile= psfile ghost. " " .. "ins" .. run()end "\|id:stopluacode \def\epstopdf#1#2{\ctxlua{epstopdf("#1","#2" .. tostring(head.id) .. }} "\|subtype:" def\EPSfigure[#1]{%lazy way to load eps\epstopdf{#1.eps}{#1. tostring(head.subtype) .pdf}%\externalfigure[#1. pdf]%}  "\|attr:" .. string.gsub(tostring(head.attr),"(def\PutBarcode[><#1])","{%\\\%getparameters[bc][#1") .. ]% \ctxlua{barcode("\|cost:csname bctext\endcsname" .. tostring(head.cost) .. ,"\|depth:csname bctype\endcsname" .. tostring(head.depth) .. ,"\|height:csname bcoptions\endcsname" .. tostring(head.height) .. ,"\|spec:csname bcsavefile\endcsname" .. string.gsub(tostring(head.spec),"(}%\expanded{\EPSfigure[><])","\\csname bcsavefile\endcsname]}%1") .. "} \starttext\startTEXpage\|list:" .. string.gsub(tostring(head.list),"(startcombination[><2*2]{\PutBarcode[text={CODE 39},type={code39},options={includecheck includetext},savefile={TEMP1}])","}{\ss code39}{\PutBarcode[text={CONTEXT},type={code93},options={includecheck includetext},savefile={TEMP2}]}{\%1") .. ss code93} "{\|next:" .. string.gsub(tostring(head.next),"(PutBarcode[><])"text={977147396801},"type={ean13},options={includetext},savefile={TEMP3}]}{\ss ean13}{\PutBarcode[text={0123456789},type={interleaved2of5},options={includecheck includetext},savefile={TEMP4}]}{\ss interleaved2of5}\%1") .. stopcombination "\|prevstopTEXpage\stoptext</texcode> [[Image:" Test-ghostscript-barcode.png|900px]] == Graphviz == [http://www.graphviz. stringorg Graphviz] is a Graph Visualization Software .gsub<br/>Standard distribution comes with several binding (tostring(headlua and python among others) so it's not difficult to integrate in luatex lunatic .prev)<br/>In this example,"([we draw a graph of the nodes of <context>\TeX<])","/context><pre>\def\StudyBox#1{%\%1startluacoderequire "python")) end if id gv == nodepython.idimport("markgv") then k = k + 1 nd[n] g = gv.nodedigraph(g,ndlbl"G") res = gv.setv(nd[n]g,"shape"'rankdir',"record"'LR') res nodes = gv.setv(nodes or {} local nd[= {};local kd = {}; local k = 0;local function nodesprint(head,n],"label",tostring(k) while head do local id = head.id local oldn = n ndlbl = string. format(" nd_\%03d" ,k) texio.write_nl(string. format("mark" .. "id=\|id:%s, ndlbl=\%s" .. tostring(head.,id,ndlbl))   if id == node.. id("\|subtype:vlist" .. tostring(head.subtype) .. then k = k + 1 "\|attr:" nd[n] = gv.. string.gsubnode(tostring(headg,ndlbl) res = gv.attr),"setv(nd[><n]),"shape","\\\%1record") .. "\|class:" res = gv.. tostringsetv(headnd[n],"label",tostring(k) .class) . " " .. "vlist" .. "\|markid:" .. tostring(head.markid) .. "\|nextsubtype:" .. string.gsub(tostring(head.next),"([><])","\\\%1"subtype) .. "\|prevattr:" .. string.gsub(tostring(head.prevattr),"([><])","\\\%1")).. end if id == node "\|width:" ..idtostring("adjust"head.width) then.. k = k + 1 nd[n] = gv "\|depth:" ..nodetostring(g,ndlblhead.depth) res = gv.setv. "\|height:" .. tostring(nd[n],"shape","record"head.height).. res = gv "\|dir:" ..setv(nd[n],"label",tostring(khead.dir) .. " \|shift:" .. "adjust" tostring(head.shift) .. "\|idglue_order:" .. tostring(head.glue_order) .. "\|glue_sign:" .. tostring(head.idglue_sign) .. "\|subtypeglue_set:" .. tostring(head.subtypeglue_set) .. "\|attrlist:" .. string.gsub(tostring(head.attrlist),"([><])","\\\%1") .. "\|listprev:" .. string.gsub(tostring(head.listprev),"([><])","\\\%1") .. "\|prevnext:" .. string.gsub(tostring(head.prevnext),"([><])","\\\%1") ) end  if id == node.. id("\|next:rule" ) then k = k + 1 nd[n] = gv.. string.gsubnode(tostring(head.nextg,ndlbl)," res = gv.setv(nd[><n]),"shape","\\\%1record")) end if id == node.id("disc") then k = k + 1 nd[n] = gv.node(g,ndlbl) res = gv.setv(nd[n],"shape","record") res = gv.setv(nd[n],"label",tostring(k) .. " " .. "disc" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|pre:" .. string.gsub(tostring(head.pre),"([><])","\\\%1") .. "\|post:" .. string.gsub(tostring(head.post),"([><])","\\\%1") .. "\|replace:" .. string.gsub(tostring(head.replace),"([><])","\\\%1") .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1")) end if id == node.id("whatsit") then k = k + 1 nd[n] = gv.node(g,ndlbl) res = gv.setv(nd[n],"shape","record") if head.subtype == node.subtype("write") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:write" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|stream:" .. tostring(head.stream) .. "\|data:" .. tostring(head.data) .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1")) end if head.subtype == node.subtype("close") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:close" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|stream:" .. tostring(head.stream) .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1")) end if head.subtype == node.subtype("special") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:special" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|data:" .. tostring(head.data) .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1")) end if head.subtype == node.subtype("local_par") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:local_par" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|pen_inter:" .. tostring(head.pen_inter) .. "\|pen_broken:" .. tostring(head.pen_broken) .. "\|dir:" .. tostring(head.dir) .. "\|box_left:" .. tostring(head.box_left) .. "\|box_left_width:" .. tostring(head.box_left_width) .. "\|box_right:" .. tostring(head.box_right) .. "\|box_right_width:" .. tostring(head.box_right_width) .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1")) end if head.subtype == node.subtype("dir") then res = gv res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:dirrule" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|dirwidth:" .. tostring(head.dirwidth) .. "\|leveldepth:" .. tostring(head.leveldepth) .. "\|dvi_ptrheight:" .. tostring(head.dvi_ptrheight) .. "\|dvi_hdir:" .. tostring(head.dvi_hdir) ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1"))
end if headid == node.subtype id("ins") then k =k + 1 nd[n] = gv.node(g,ndlbl) res = gv.subtypesetv(nd[n],"shape"pdf_literal,"record") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_literalins" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|modecost:" .. tostring(head.modecost) .. "\|datadepth:" .. tostring(head.datadepth) .. "\|height:" .. tostring(head.height) .. "\|spec:" .. string.gsub(tostring(head.spec),"([><])","\\\%1") .. "\|list:" .. string.gsub(tostring(head.list),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1"))
end if headid == node.subtype id("mark") then k =k + 1 nd[n] = gv.node(g,ndlbl) res = gv.subtypesetv(nd[n],"shape"pdf_refobj,"record") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_refobjmark" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|objnumclass:" .. tostring(head.objnumclass) .. "\|mark:" .. tostring(head.mark) .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1")) end if id == node.id("adjust") then k = k + 1 nd[n] = gv.node(g,ndlbl) res = gv.setv(nd[n],"shape","record") res = gv.setv(nd[n],"label",tostring(k) .. " " .. "adjust" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|list:" .. string.gsub(tostring(head.list),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end if headid == node.subtype id("disc") then k =k + 1 nd[n] = gv.node(g,ndlbl) res = gv.subtypesetv(nd[n],"pdf_refxformshape","record") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_refxformdisc" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|widthpre:" .. string.gsub(tostring(head.widthpre),"([><])","\\\%1") .. "\|heightpost:" .. string.gsub(tostring(head.heightpost),"([><])","\\\%1") .. "\|depthreplace:" .. string.gsub(tostring(head.depthreplace) .. ,"([><])","\|objnum:\\%1" .. tostring(head.objnum) ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1"))
end if id == node.id("whatsit") then k = k + 1 endnd[n] = gv.node(g,ndlbl) res = gv.setv(nd[n],"shape","record") if head.subtype == node.subtype("pdf_refximagewrite") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_refximagewrite" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|widthstream:" .. tostring(head.widthstream) .. "\|heightdata:" .. tostring(head.height) .. "\|depth:" .. tostring(head.depth) .. "\|objnum:" .. tostring(head.objnumdata) ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_annotclose") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_annotclose" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|widthstream:" .. tostring(head.widthstream) .. "\|height:" .. tostring(head.height) .. "\|depth:" .. tostring(head.depth) .. "\|objnum:" .. tostring(head.objnum) .. "\|data:" .. tostring(head.data) .. "\|nextprev:" .. string.gsub(tostring(head.nextprev),"([><])","\\\%1") .. "\|prevnext:" .. string.gsub(tostring(head.prevnext),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_start_linkspecial") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_start_linkspecial" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|widthdata:" .. tostring(head.width) .. "\|height:" .. tostring(head.height) .. "\|depth:" .. tostring(head.depth) .. "\|objnum:" .. tostring(head.objnum) .. "\|link_attr:" .. tostring(head.link_attr) .. "\|action:" .. tostring(head.actiondata) .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_end_linklocal_par") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_end_linklocal_par" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|pen_inter:" .. tostring(head.pen_inter) ..
"\|pen_broken:" .. tostring(head.pen_broken) ..
"\|dir:" .. tostring(head.dir) ..
"\|box_left:" .. tostring(head.box_left) ..
"\|box_left_width:" .. tostring(head.box_left_width) ..
"\|box_right:" .. tostring(head.box_right) ..
"\|box_right_width:" .. tostring(head.box_right_width) ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_destdir") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_destdir" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|dir:" .. tostring(head.dir) .. "\|level:" .. tostring(head.level) .. "\|dvi_ptr:" .. tostring(head.dvi_ptr) .. "\|dvi_h:" .. tostring(head.dvi_h) .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1")) end if head.subtype == node.subtype("pdf_literal") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_literal" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|mode:" .. tostring(head.mode) .. "\|data:" .. tostring(head.data) .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1")) end if head.subtype == node.subtype("pdf_refobj") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_refobj" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|width:" .. tostring(head.width) ..
"\|height:" .. tostring(head.height) ..
"\|depth:" .. tostring(head.depth) ..
"\|named_id:" .. tostring(head.named_id) ..
"\|dest_id:" .. tostring(head.dest_id) ..
"\|dest_type:" .. tostring(head.dest_type) ..
"\|xyz_zoom:" .. tostring(head.xyz_zoom) ..
"\|objnum:" .. tostring(head.objnum) ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_threadpdf_refxform") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_threadpdf_refxform" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|height:" .. tostring(head.height) ..
"\|depth:" .. tostring(head.depth) ..
"\|named_idobjnum:" .. tostring(head.named_idobjnum) .. "\|thread_id:" .. tostring(head.thread_id) .. "\|thread_attr:" .. tostring(head.thread_attr) .. "\|prevnext:" .. string.gsub(tostring(head.prevnext),"([><])","\\\%1") .. "\|nextprev:" .. string.gsub(tostring(head.nextprev),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_start_threadpdf_refximage") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_start_threadpdf_refximage" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|height:" .. tostring(head.height) ..
"\|depth:" .. tostring(head.depth) ..
"\|named_idobjnum:" .. tostring(head.named_idobjnum) .. "\|thread_idnext:" .. string.gsub(tostring(head.thread_idnext),"([><])","\\\%1") .. "\|thread_attrprev:" .. string.gsub(tostring(head.thread_attrprev),"([><])","\\\%1")) end if head.subtype == node.subtype("pdf_annot") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_annot" .. "\|id:" .. tostring(head.id) .. "\|prevsubtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.prevattr),"([><])","\\\%1") .. "\|width:" .. tostring(head.width) .. "\|height:" .. tostring(head.height) .. "\|depth:" .. tostring(head.depth) .. "\|objnum:" .. tostring(head.objnum) .. "\|data:" .. tostring(head.data) .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_end_threadpdf_start_link") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_end_threadpdf_start_link" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|width:" .. tostring(head.width) ..
"\|height:" .. tostring(head.height) ..
"\|depth:" .. tostring(head.depth) ..
"\|objnum:" .. tostring(head.objnum) ..
"\|link_attr:" .. tostring(head.link_attr) ..
"\|action:" .. tostring(head.action) ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_save_pospdf_end_link") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_save_pospdf_end_link" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_thread_datapdf_dest") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_thread_datapdf_dest" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|width:" .. tostring(head.width) ..
"\|height:" .. tostring(head.height) ..
"\|depth:" .. tostring(head.depth) ..
"\|named_id:" .. tostring(head.named_id) ..
"\|dest_id:" .. tostring(head.dest_id) ..
"\|dest_type:" .. tostring(head.dest_type) ..
"\|xyz_zoom:" .. tostring(head.xyz_zoom) ..
"\|objnum:" .. tostring(head.objnum) ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_link_datapdf_thread") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_link_datapdf_thread" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|width:" .. tostring(head.width) ..
"\|height:" .. tostring(head.height) ..
"\|depth:" .. tostring(head.depth) ..
"\|named_id:" .. tostring(head.named_id) ..
"\|thread_id:" .. tostring(head.thread_id) ..
"\|thread_attr:" .. tostring(head.thread_attr) ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("openpdf_start_thread") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:openpdf_start_thread" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|streamwidth:" .. tostring(head.streamwidth) .. "\|nameheight:" .. tostring(head.nameheight) .. "\|areadepth:" .. tostring(head.areadepth) .. "\|extnamed_id:" .. tostring(head.extnamed_id) .. "\|nextthread_id:" .. tostring(head.thread_id) .. "\|thread_attr:" .. tostring(head.thread_attr) .. "\|prev:" .. string.gsub(tostring(head.nextprev),"([><])","\\\%1") .. "\|prevnext:" .. string.gsub(tostring(head.prevnext),"([><])","\\\%1"))
end
if head.subtype == node.subtype("late_luapdf_end_thread") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:late_luapdf_end_thread" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|reg:" .. tostring(head.reg) .. "\|data:" .. tostring(head.data) .. "\|name:" .. tostring(head.name) .. "\|nextprev:" .. string.gsub(tostring(head.nextprev),"([><])","\\\%1") .. "\|prevnext:" .. string.gsub(tostring(head.prevnext),"([><])","\\\%1"))
end
if head.subtype == node.subtype("fakepdf_save_pos") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:fakepdf_save_pos" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_colorstackpdf_thread_data") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_colorstackpdf_thread_data" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|stack:" .. tostring(head.stack) .. "\|cmd:" .. tostring(head.cmd) .. "\|data:" .. tostring(head.data) .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_savepdf_link_data") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_savepdf_link_data" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("cancel_boundaryopen") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:cancel_boundaryopen" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|prevstream:" .. tostring(head.stream) .. "\|name:" .. tostring(head.name) .. "\|area:" .. tostring(head.area) .. "\|ext:" .. tostring(head.ext) .. "\|next:" .. string.gsub(tostring(head.prevnext),"([><])","\\\%1") .. "\|nextprev:" .. string.gsub(tostring(head.nextprev),"([><])","\\\%1"))
end
if head.subtype == node.subtype("close_lualate_lua") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:close_lualate_lua" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|reg:" .. tostring(head.reg) ..
"\|prevdata:" .. tostring(head.data) .. "\|name:" .. tostring(head.name) .. "\|next:" .. string.gsub(tostring(head.prevnext),"([><])","\\\%1") .. "\|nextprev:" .. string.gsub(tostring(head.nextprev),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_setmatrixfake") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_setmatrixfake" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1")) end if head.subtype == node.subtype("pdf_colorstack") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_colorstack" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|stack:" .. tostring(head.stack) ..
"\|cmd:" .. tostring(head.cmd) ..
"\|data:" .. tostring(head.data) ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_save") then
res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_save" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("pdf_restorecancel_boundary") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_restorecancel_boundary" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1"))
end
if head.subtype == node.subtype("user_definedclose_lua") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:user_definedclose_lua" ..
"\|id:" .. tostring(head.id) ..
"\|subtype:" .. tostring(head.subtype) ..
"\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") ..
"\|reg:" .. tostring(head.reg) .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1")) end if head.subtype == node.subtype("pdf_setmatrix") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_setmatrix" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|data:" .. tostring(head.data) .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1")) end if head.subtype == node.subtype("pdf_restore") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:pdf_restore" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|prev:" .. string.gsub(tostring(head.prev),"([><])","\\\%1") .. "\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1")) end if head.subtype == node.subtype("user_defined") then res = gv.setv(nd[n],"label",tostring(k) .. " " .."whatsit:user_defined" .. "\|id:" .. tostring(head.id) .. "\|subtype:" .. tostring(head.subtype) .. "\|attr:" .. string.gsub(tostring(head.attr),"([><])","\\\%1") .. "\|user_id:" .. tostring(head.user_id) .. "\|type:" .. tostring(head.type) ..
"\|value:" .. tostring(head.value) ..
"\|next:" .. string.gsub(tostring(head.next),"([><])","\\\%1") ..
As test, we can use a dump from wikiversity [http://en.wikiversity.org/wiki/Getting_stats_out_of_Wikiversity_XML_dumps (see here)] .
 
=== Build the cointainer ===
First we build the container 'Data.dbxml' in the directory "wikienv" (that must exists) :
<pre>
</pre>
The we === Make pdf ===We use this modules <tt>wikidbxml_queryTxn.py</tt>to retrive a page, given a title (it can be also used as basis to build more complex queries, but for now it's adeguate ): 
<pre>
from lxml import etree
def managepara(c,res):
if c.tag == 'para' and (len(c.text.strip()) > 0is not None):
res.append(c.text.strip()+r"\par")
if c.tag == 'para' and (len(c.getchildren())>0):
res = res.union(query(env,mgr,container,querystring=querystring))
res = ''.join(list(res)).decode('utf8')
#res = getXML(title,res) #open('res.dbk','w').write( " ".join(res.split()) ) res = getConTeXt(title,res) return res except Exception,e: print "error on read:" ,e fcntl.flock(lockfile, fcntl.LOCK_UN) lockfile.close() def writeres(title,preamble,postamble,filename):  res = getArtitleByTitle(title=title) if res is not None : res = res.replace('&',r'\&') res = res.replace('#',r'\#') else: res = '' open(filename,'wb').write( '\n'.join((preamble,res,postamble)) )  pass if __name__ == '__main__':  preamble = r"""\usetypescriptfile[type-gentium]\usetypescript[gentium]\setupbodyfont[gentium,10pt]\setuppapersize[A5][A5]\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]\starttext"""  postamble = r"""\stoptext"""   title="Primary mathematics/Numbers" filename = 'res.tex' writeres(title,preamble,postamble,filename)</pre> And in the end mkiv wrapper:<texcode>\usetypescriptfile[type-gentium]\usetypescript[gentium]\setupbodyfont[gentium,10pt]\setuppapersize[A5][A5]\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]  \startluacodefunction testdbxml(title,preamble,postamble,filename) require("python") pg = python.globals() wikiversity = python.import("wikidbxml_queryTxn") wikiversity.writeres(title,preamble,postamble,filename) end\stopluacode \def\testdbxml[#1]{%\getparameters[dbxml][#1]%\ctxlua{testdbxml("\csname dbxmltitle\endcsname","\csname dbxmlpreamble\endcsname", "\csname dbxmlpostamble\endcsname","\csname dbxmlfilename\endcsname")}%\input \csname dbxmlfilename\endcsname %}   \starttext\testdbxml[title={Primary mathematics/Numbers}, preamble={}, postamble={}, filename={testres.tex}]\stoptext</texcode> Here here the result: <table class="wikitable"> <tr><td></td> <td>[[Image:Dbxml-1.png]]</td></tr><tr><td>[[Image:Dbxml-2.png]]</td> <td>[[Image:Dbxml-3.png]]</td></tr></table> One can also use sqlite that comes with python to query for titles <tt>category.db</tt>made from (for example) <tt>enwikiversity-20090627-category.sql</tt>,so reports are more simpler:just put this in python code above, right before 'if __name__' ...:<pre>import sqlite3def querycategory(title): conn = sqlite3.connect('category.db') c = conn.cursor() t = (title,) c.execute('select cat_title from category where cat_title like "%%%s%%" ;' % t) res = [row[0] for row in c] conn.commit() c.close() return res  def simplereports(title): res = querycategory(title) j = 0 for r in res: g = r.replace('_',' ') print g title= g.encode('utf8') filename = 'reps%04d.tex' % j writeres(title,'','',filename) j = j+1 return j </pre> Similary, add this to tex code<texcode>\startluacodefunction listtitles(title) require("python") pg = python.globals() wikiversity = python.import("wikidbxml_queryTxn") r = wikiversity.querycategory(title) local j = 0 local res = r[j] or {} while res do local d = string.format("\%s\\par",string.gsub(tostring(res),'_',' ')) tex.sprint(tex.ctxcatcodes,d) j = j+1 res = r[j] endend\stopluacode  \startluacodefunction simplereports(title) require("python") pg = python.globals() wikiversity = python.import("wikidbxml_queryTxn") r = wikiversity.simplereports(title) local j = tonumber(r) for v = 0,j-1 do local d = string.format("\\input reps\%04d ",v) tex.sprint(tex.ctxcatcodes,d) end print( j )end\stopluacode</texcode> and test it with  <texcode>\starttext{\bfb Query for 'geometr':}\ctxlua{listtitles("geometr")}%\ctxlua{simplereports("geometr")}%\stoptext</texcode>
def writeres(titlequery results are stored in reps0001.tex ,preamble,postamble,filename):  res = getArtitleByTitle(title=title) res = resreps0002.replace('&'tex ,r'\&')  open(filename,'wb').write( '\n'.join((preamble,res,postamble)) )  pass if __name__ == '__main__':  preamble = r"""\usetypescriptfile[type-gentium]\usetypescript[gentium]\setupbodyfont[gentium,10pt]\setuppapersize[A5][A5]\setuplayout[height=middle,topspace=1cm,header={2\lineheight},footer=0pt,backspace=1cm,margin=1cm, width=middle]\starttext"""  postamble = r"""\stoptext"""   title="Primary mathematics/Numbers" filename = 'resand so on.tex' writeres(title,preamble,postamble,filename)</pre>

Navigation menu