developer.jelix.org is not used any more and exists only for history. Post new tickets on the Github account.
developer.jelix.org n'est plus utilisée, et existe uniquement pour son historique. Postez les nouveaux tickets sur le compte github.

Opened 13 years ago

Closed 13 years ago

Last modified 13 years ago

#130 closed new feature (fixed)

Adding a latex/pdf response

Reported by: Aubanel Owned by: laurentj
Priority: low Milestone: Jelix 1.0beta2
Component: jelix:core response Version: 1.0 beta1
Severity: minor Keywords: latex pdf response
Cc: aubanel@…, laurentj Blocked By:
Blocking: Documentation needed:
Hosting Provider: Php version:

Description

As I need to generate pdf, I figured that the latex way was the shorter for me. So here is a new response to generate latex content + 2 jTpl plugins to make writing latex templates not too stressfull. This is the very beginning, I'll have to figure how to compile the documents and serve them, right now I just serve the .tex as text content. Any pointer on how to do that with jelix would be appreciated)

So here we go. The new respons

require_once (JELIX_LIB_RESPONSE_PATH.'jResponseText.class.php');
 
class genericLatex extends jResponseText {
 /**
     * selector of the main template file
     * This template should contains the body content, and is used by the $body template engine
     * @var string
     */
    public $bodyTpl = '';
/**
     * The template engine used to generate the content
     * @var jTpl
     */
    public $body = null;
/**
     * Authors of the document
     * @var array
     */
    public $authors = array();
/**
     * Document title
     * @var string
     */
    public $title = '';

 /**
    * constructor;
    * setup the template engine
    */
    function __construct ($attributes=array()){
        $this->body = new jTpl();
        parent::__construct($attributes);
    }

 function output(){
 global $gJConfig;
        $this->_httpHeaders['Content-Type']='text/plain;charset='.$gJConfig->defaultCharset;
        $this->_httpHeaders['Content-length']=strlen($this->content);
        $this->sendHttpHeaders();
        echo  '
 \documentclass[11pt]{article}
 \usepackage{graphicx}    % needed for including graphics e.g. EPS, PS
 \topmargin -1.5cm        % read Lamport p.163
 \oddsidemargin -0.04cm   % read Lamport p.163
 \evensidemargin -0.04cm  % same as oddsidemargin but for left-hand pages
 \textwidth 16.59cm
 \textheight 21.94cm 
 %\pagestyle{empty}       
 \parskip 7.2pt           % sets spacing between paragraphs
 %\renewcommand{\baselinestretch}{1.5} 	% Uncomment for 1.5 spacing between lines
 \parindent 0pt		  % sets leading space for paragraphs
\begin{document}
\title{'.$this->title.'}
\author{';
foreach ($this->authors as $a) echo $a.'\\\\'."\n";
echo'}
\date{\today}
\maketitle
 ';
 $this->body->display($this->bodyTpl);
 echo  '

 \end{document}';
	return true;
 }
   // modifications communes aux actions utilisant cette reponses
   protected function _commonProcess(){}
}
?>

The jTpl block plugin to write \begin{blah} end{blah}:

/**
 * a special to insert latex content
 *
 * usage : {latex section} blah{/latex} generates the equivalent of \section{blah}. Supports nesting
 * @param jTplCompiler $compiler the template compiler
 * @param boolean true if it is the begin of block, else false
 * @param $param array  1=>latex command 
 * @return string the php code corresponding to the begin or end of the block
 */
function jtpl_block_latex($compiler, $begin, $param=array())
{
static $stack=array();
if ($begin){
	array_push($stack,$param[0]);
	return 'echo \'\\begin{'.$param[0].'}\';';
	}
else return 'echo \'\\end{'.array_pop($stack).'}\';';
}

And displaying values from the db can proove cumbersome because of all the special chars latex has, so here is a modifier which does the job for you:

/**
 * modifier plugin : simple search/replace for latex chars
 * @param string

 */
function jtpl_modifier_latex($string)
{
    return str_replace(array('#','$','%','^','&','_','{','}','~'), array('\\#','\\$','\\%','\\^','\\&','\\_','\\{','\\}','\\~'), str_replace('\\','\\textbackslash',$string));
}

There is room for many improvements, but that's a working start.

As an illustration, here is a sample template:

{latex section}Test Cases Review{/latex}

{assign $rob='# $ % ^ & _  ~ \\'}

Test of robustnes:{$rob|latex}

{latex tabular}{literal}{ l | c || r | }{/literal}

{assign $global_status=array('NV','OK','NOK','PV')}
{foreach $list as $i=>$tc}
{assign $tc_status=$global_status[$tc->reviewStatus()]}
{$i} & {$tc->id|latex} & {$tc_status} \\
{/foreach}
	
{/latex tabular}

and an associated action :

class defaultCtrl extends jController {
...
function report(){
                ...
		$rep = $this->getResponse('latex');
		$rep->title = 'GADIRS A400M test review report';
		$rep->authors = array('Aubanel MONNIER','Yvonne XXXXXX','Pierre YYYYYY', 'Antoine ZZZZZZZ');
		$rep->body->assign('list', $list);
		$rep->bodyTpl = 'tc.report'; 		
		return $rep;
	}

Attachments (7)

genericLatex.class.php (2.6 KB) - added by Aubanel MONNIER 13 years ago.
the genericLatex response
modifier.latex.php (715 bytes) - added by Aubanel MONNIER 13 years ago.
the latex modifier to escape bad chars
block.lcmd.php (921 bytes) - added by Aubanel MONNIER 13 years ago.
the lcmd jTpl block plugin for latex commands like \section{blah\footnonte{hey} blah}
block.lenv.php (978 bytes) - added by Aubanel MONNIER 13 years ago.
the lenv jTpl block plugin for latex environments like \begin{tabular} ... \end{tabular}
genericLatex.class.2.php (4.0 KB) - added by Aubanel MONNIER 13 years ago.
update with: clear cache function, correct headers, more configration options
block.lcmd.2.php (868 bytes) - added by Aubanel MONNIER 13 years ago.
fixed non-exiting array bug
genericLatex.class.3.php (4.5 KB) - added by Aubanel MONNIER 13 years ago.
Yet another update, finally understood how latex commands should work (should look less clumsy to latex users). Also added a default commands function + other minor fixes. Still the problem of the exception though, if someone can guide me here …

Download all attachments as: .zip

Change History (18)

comment:1 follow-up: Changed 13 years ago by laurentj

  • Cc laurentj added

Ok, with your work, at present, we could send latex content to the browser. But i don't know if browsers could support latex directly (with a browser plugin perhaps ?).

If you want to provide PDF to the user, i think you should improve your response. The response should not output latex, but pdf and it should be in fact a responseLatexToPdf. So in fact, in the output method, it's ok to generate a latex document, but the response shouldn't output it. At this end of this method, you should call a class which transform latex to pdf, and then you output the result (pdf content). But i don't know if a such class exists on the internet. Do search with google, or create one (based on a the FPDF class for example).

Your work is interresting anyway. I would like Jelix to support as many output format as possible :-)

For futur patch, please follow guidelines on http://developer.jelix.org/wiki/fr/sources. You could also join us on irc to discuss about your work.

comment:2 Changed 13 years ago by laurentj

  • Cc aubanel@… added; aubanel@… removed

comment:3 in reply to: ↑ 1 Changed 13 years ago by Aubanel MONNIER

OK, I just completed the missing bits to have something working out of the box. I'd be glad to play with svn to work on head, but I have some issues with the corporate firewall. I guess the best is to attach the 4 new files (one response and 3 jTpl plugins) so I'll try that. The plugins are:

block lenv : latex environment

block lcmd : latex command

modifier latex : replaces latex special chars

There is a naïve cache system in the latexResponse (its deletion is not managed, can grow large if heavily used), any better idea is welcome. The call to pdflatex is hardcoded in the response, so if you want to test, you'd better have it in your $PATH.

Just wondering, is there a way to change the special {} chars used by jTpl to something else (e.g. <>) because {} are used quite heavily in latex... This could remove the need for the lenv and lcmd plugins.

So enjoy, jelix has now latex/pdf resonses !

Changed 13 years ago by Aubanel MONNIER

the genericLatex response

Changed 13 years ago by Aubanel MONNIER

the latex modifier to escape bad chars

Changed 13 years ago by Aubanel MONNIER

the lcmd jTpl block plugin for latex commands like \section{blah\footnonte{hey} blah}

Changed 13 years ago by Aubanel MONNIER

the lenv jTpl block plugin for latex environments like \begin{tabular} ... \end{tabular}

comment:4 follow-up: Changed 13 years ago by laurentj

  • Milestone set to Jelix 1.0beta2

Wonderful ! :-) Using pdflatex is a good thing although it won't work on windows server i guess. So here some improvement i would like :

  • adding a test to see if pdflatex exists, and if not, generate an error.
  • there are some things into the header of latex document (topmargin etc), why not to create some class properties for it, so the user can change this parameters ?
  • create temp files into a subdirectory of the temp/ directory
  • having a property which content the path to the pdflatex command. So the user can set the right path (and the default value can be simply "pdflatex")

For the cache system, i haven't an idea for the moment. Perhaps adding a clean() method, so the user can delete all temporary files when he wants.

For the {}, unfortunately we cannot change them in jtpl, so for the moment, keep the plugins.

An other thing : could you please add correct comment headers, with your name, your copyright on all files, and fix comments in jtpl plugin (usage documentation, parameter etc..) ? (see http://developer.jelix.org/wiki/fr/conventions )

When you will have fixed this issues and made improvements, i will check in your files into the repository :-) Note that i will change the name genericLatex to jResponseLatexPdf.

Changed 13 years ago by Aubanel MONNIER

update with: clear cache function, correct headers, more configration options

comment:5 in reply to: ↑ 4 Changed 13 years ago by anonymous

Replying to laurentj:

Wonderful ! :-) Using pdflatex is a good thing although it won't work on windows server i guess. So here some improvement i would like :

As far as I know, pdflatex is available on windows by installing miktex

  • adding a test to see if pdflatex exists, and if not, generate an error.

Done. I did not understood everything with exceptions in php and jelix, I guess I have to give a locale selector instead of the raw string I pass to the exception. Just dunno where the localized text has to be written, so I let this tiny point up to you ;)

  • there are some things into the header of latex document (topmargin etc), why not to create some class properties for it, so the user can change this parameters ?

OK, done (might be rough or unacurate I am not the latex expert)

  • create temp files into a subdirectory of the temp/ directory

Done

  • having a property which content the path to the pdflatex command. So the user can set the right path (and the default value can be simply "pdflatex")

Done

For the cache system, i haven't an idea for the moment. Perhaps adding a clean() method, so the user can delete all temporary files when he wants.

Done

An other thing : could you please add correct comment headers, with your name, your copyright on all files, and fix comments in jtpl plugin (usage documentation, parameter etc..) ? (see http://developer.jelix.org/wiki/fr/conventions )

Done

When you will have fixed this issues and made improvements, i will check in your files into the repository :-) Note that i will change the name genericLatex to jResponseLatexPdf.

OK, it's up to you now ! (everything is in the new updated genericLatex.class.php file)

comment:6 Changed 13 years ago by Aubanel MONNIER

I let a small bug in the lcmd plugin, fix it right now.

Changed 13 years ago by Aubanel MONNIER

fixed non-exiting array bug

Changed 13 years ago by Aubanel MONNIER

Yet another update, finally understood how latex commands should work (should look less clumsy to latex users). Also added a default commands function + other minor fixes. Still the problem of the exception though, if someone can guide me here ...

comment:7 Changed 13 years ago by laurentj

  • Resolution set to fixed
  • Status changed from new to closed
  • Summary changed from Adding a latex response to Adding a latex/pdf response

patch checked in in the trunk. Fix exception problem and change minor things for a better integration into jelix.

comment:8 Changed 13 years ago by Aubanel MONNIER

Super ! et merci pour ce superbe framework qu'est déjà jelix.

comment:9 follow-up: Changed 13 years ago by netAction

In function jtpl_modifier_latex($string) is missing:

"\n" -> " ", "\r" -> " ", "<", ">", "|"

comment:10 Changed 13 years ago by laurentj

@netAction : This ticket is closed. please create a new ticket, with details of the bug. thanks.

comment:11 in reply to: ↑ 9 Changed 13 years ago by netAction

No, even this is not enought. But this should be ok.

$string=str_replace(

array( '#', '$', '%', '','&', '_', '{', '}','~','\r'),

array('
#','
$','
%','
textasciicircum','
&','
_','
{','
}','
textasciitilde{}', ' '),

str_replace('
','
textbackslash ',$string));

$string=str_replace("<","
textless{}",$string);

$string=str_replace(">","
textgreater{}",$string);

$string=str_replace("|","
docbooktolatexpipe{}",$string);

Note: See TracTickets for help on using tickets.