• Publicidad

script Perl pst2pdf y pdfTeX

¿Apenas comienzas con Perl? En este foro podrás encontrar y hacer preguntas básicas de Perl con respuestas aptas a tu nivel.

script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2010-09-12 21:13 @925

Hola, mi nombre es Pablo, soy usuario de TeX/LaTeX hace bastantes años (en entornos Linux y Win32) y tengo instalado MikTeX2.8 junto a Active Perl.

El problema se me presenta con el siguiente script Perl «pst2pdf» de H.V (a cargo de mantener y desarrollar los paquetes PsTricks y compañía)

El script funciona, pero no en forma correcta, con la línea
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
print PDF "\\IncludeGraphics[scale=$Iscale]{$imageDir/$name-tmp-$IMGno$Iext}";
 
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4

escribe en el fichero final, pero, agrega un .\ de la siguiente forma
Sintáxis: [ Descargar ] [ Ocultar ]
Using text Syntax Highlighting
\IncludeGraphics[scale=1]{images/.\test-tmp-0.pdf}
Coloreado en 0.000 segundos, usando GeSHi 1.0.8.4

el cual produce un error en Windows y Linux.

He revisado y leído el código (varias veces) pero no logro encontrar el problema, es decir, en qué parte del script se imprime el .\

Esperando su guía y ayuda para resolver este asunto TeXnico para el mundo TeX, se despide Pablo.
Última edición por pablgonz el 2011-05-28 15:00 @667, editado 3 veces en total
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Publicidad

Re: script Perl pst2pdf y pdfTeX

Notapor explorer » 2010-09-13 07:45 @365

Bienvenido a los foros de Perl en Español, pablgonz.

Esto es lo que pasa.

En la línea 47 extraemos la ruta, el nombre del fichero y su posible extensión. El nombre queda en $name, y la ruta en $path.

Si al programa le pasas, como nombre 'test', $name valdrá 'test', y la ruta valdrá '.\' (si estás en Windows).

En la línea 92, se llama a runpdfTeX("$path$name",$name);. Observa que el primer argumento es la ruta completa al fichero. Así que el primer argumento sería '.\test'. Y el segundo argumento es solo el nombre del fichero (seguramente, sin extensión) ('test').

La función runpdfTeX empieza en la 269. Lo primero que hace es

my ($name,$pdfname) = @_;

Es decir, la ruta completa pasa a la variable local $name, y el nombre de solo el fichero, pasa a la local $pdfname.

Y llegamos a las líneas 298 y 312:
print PDF "\\IncludeGraphics[scale=$Iscale]{$imageDir/$name-tmp-$IMGno$Iext}";

Estríctamente hablando, es correcto lo que pone ahí (estamos creando una ruta a un nuevo fichero), uniendo los valores de $imageDir, '/', $name, '-tmp-', $IMGno e $Iext, que sale lo que indicas: images/.\test-tmp-0.pdf.

Y el problema parece que está justamente en la presencia del '/' junto con '\'. Yo probaría a cambiar la '/' por un '\' (mejor '\\', que así queda escapado), que es el separador de ficheros en Windows/DOS.

La forma correcta, sería usando la función catfile() de File::Spec. De hecho, si quieres que un código funcione de forma portable, es indispensable el uso de este módulo, y realizar con él todas las operaciones de gestión de nombres de ficheros.

Otra opción sería cambiar $name por $pdfname, en las líneas 298 y 312, pero tendríamos problemas en caso de tener que manejar ficheros que estén en directorios o subdirectorios distintos del directorio de ejecución. Bueno, depende de lo que quiera decir la instrucción \IncludeGraphics. Si solo se trata de indicar un directorio temporal donde guardar los gráficos, sí que se podría indicar solo $pdfname. No lo sé, depende de cómo lo dejen los comandos que crean los gráficos, me parece que en la función runTeX().
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2010-09-13 23:07 @005

Muchas gracias por la pronta respuesta, el problema se ha solucionado por completo con los cambios en las líneas 298 y 312 y descomentando un par de líneas más arriba para que escribiera \graphicspath{{images/}} en el fichero.

Lo de reescribir el script usando catfile()... es un poco complicado, puesto que el \ y / significan mucho (y muchas cosas) en TeX/LaTeX. Lo ideal sería detectar el SO y modificar images/ si es Win32, images\ si es Linux y images: si es Mac, puesto que en si los ficheros LaTeX ya son portátiles y el script a excepción del detalle de images\ funciona (ahora) correctamente.

En sí la función de este script es sencilla pero potente; si se tiene un archivo con imágenes creadas usando pstricks (el paquete PostScript y amigos) éstas no pueden ser procesadas directamente por pdfTeX, LuaTeX, XeTeX y ConText, el script extrae todos los entornos donde hay imágenes creadas con pstricks y los separa en ficheros individuales en una carpeta (images) en el mismo directorio, para procesarlos y convertirlos en PDF (que sí es aceptado por pdfTeX, LuaTeX , ...), generando un nuevo fichero limpio (a excepción de un par de paquetes en el preámbulo) listo para procesar y enviar, una herramienta útil para aquellos que generamos dibujos o creamos presentaciones y guías.

En fin muchas gracias por la explicación de las líneas de código (si eso no hubiese entendido jamas lo del bendito /.\) y por la pronta respuesta al tema. Doy por cerrado el tema, a menos que alguien decida mejorar este ya grandioso script.

Gracias por todo,
Pablo
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: script Perl pst2pdf y pdfTeX

Notapor explorer » 2010-09-14 04:41 @237

Precisamente lo que hace catfile() es unir los componentes de la ruta mediante '\' o '/' según sea el sistema operativo. Se podría intentar el crear la ruta antes de meterla junto con el comando LaTeX.

Para saber en qué sistema se está ejecutando el programa, se puede consultar la variable especial $^O, o usando alguno de los módulos Devel::CheckOS o Perl::OSType.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14480
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Modificar script ...

Notapor pablgonz » 2011-05-23 21:01 @917

Creo que ya encontré la solución a mi cuestión (el flojo trabaja el doble).

Tras mucho leer (y deambular por el foro) y probar (gracias sleep(time)) me he percatado dónde está mi problema (explorer me aclaró las líneas de la versión anterior de este mismo script en un post anterior).

Adaptar otro script no era la mejor solución, pero, me dio algunas ideas. Ya entiendo qué es lo que sucede, sólo necesito ayuda para encaminar la solución.

El script lee todo el fichero de una vez ($name.tex) en la línea 298; es aquí donde se necesitan eliminar algunas líneas de la primera parte del archivo (preámbulo) que causan conflicto con el compilador (pdfTeX) y que ahora ya no son necesarias.

Se me ocurren dos ideas para solucionar el problema:

1. Leer $name.tex desde la primera línea hasta \begin{document} y en ellas modificar (eliminar) las líneas que quiero y seguir con el proceso.

2. Durante el proceso el script crea filename.preamble; leerlo, eliminar las líneas, guardarlo e insertar este antes de la línea \begin{document} de $name.tex

¿Se puede hacer esto? ¿Cuál sería la mejor opción?

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}' && eval 'exec perl -S $0 $argv:q'
  2.   if 0;
  3.  
  4. use strict;                             # to be sure, that all is safe ... :-)
  5.  
  6. # v. 0.11                               simplify the use of PSTricks with pdf
  7. # 2011-01-18    (c) Herbert Voss <[email protected]>
  8. # $Id: pst2pdf.pl 239 2010-01-01 17:23:13Z herbert $
  9. # Thanks to Pablo Gonzales Luengo
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or (at
  14. # your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful, but
  17. # WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  19. # See the GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License
  22. # along with this program; if not, write to the
  23. # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  24. # MA  02111-1307  USA
  25. #
  26. use File::Path;                         # creating/removing dirs
  27. use File::Copy;                         # copying files
  28. use File::Basename;                     # scan argument
  29. use IO::File;                           # simple IO operation
  30. use Getopt::Long;                       # read parameter
  31.  
  32. #----------------------- User part begin ------------------------
  33. my $imageDir = "images";                # where to save the images
  34. my @imageType = ("eps","pdf");          # all image types
  35. my $machine = "Linux";
  36. if ($^O eq 'MSWin32') { $machine = "Windows"; }
  37. else                  { push (@imageType, "png"); }
  38. my $Iext = ".pdf";                      # leave empty, if not a special one
  39. my $tempDir = ".";                      # temporary directory
  40. my $verbose = 1;                        # 0 or 1, logfile  
  41. my $clear = 0;                          # 0 or 1, clears all temporary files
  42. my $DPI = 75;                           # very low value for the png's
  43. my $Iscale = 1;                         # for \includegraphics
  44. my $noImages = 0;                       # 1->create no images
  45. my $runBibTeX = 0;                      # 1->runs bibtex
  46. my $runBiber = 0;                       # 1->runs biber and sets $runBibTeX=0
  47. #----------------------- User part end ---------------------------
  48.  
  49. @ARGV == 0 && die "file name expected!\n";
  50.  
  51. my @SuffixList = (".tex","",".ltx");                    # possible extensions
  52. my ($name,$path,$ext) = fileparse($ARGV[0],@SuffixList);
  53. if ( $ext eq "" ) { $ext = ".tex"; }                    # me need the extension as well
  54. my $TeXfile = "$path$name$ext";
  55. my $Logfile = "$tempDir/$name.plog";                    # our own log file
  56. open (LOGfile, ">$Logfile") or die "cannot open $Logfile!";
  57.  
  58. my $result = GetOptions ("DPI=i"      => \$DPI,         # numeric
  59.                          "Iscale=f"   => \$Iscale,      # real
  60.                          "imageDir=s" => \$imageDir,    # string
  61.                          "tempDir=s"  => \$tempDir,     # string
  62.                          "Iext=s"     => \$Iext,        # string
  63.                          "clear"      => \$clear,       # flag
  64.                          "noImages"   => \$noImages,    # flag
  65.                          "runBibTeX"  => \$runBibTeX,   # flag
  66.                          "runBiber"   => \$runBiber,    # flag
  67.                          "verbose"    => \$verbose);    # flag
  68.  
  69. LOG ("Parameters:");
  70. LOG ("==> imageDir = $imageDir");
  71. LOG ("==> Iext     = $Iext");
  72. LOG ("==> DPI      = $DPI");
  73. LOG ("==> Iscale   = $Iscale");
  74. LOG ("==> tempDir  = $tempDir");
  75. LOG ("==> verbose  = $verbose");
  76. LOG ("==> clear    = $clear");
  77. LOG ("==> noImages = $noImages");
  78. LOG ("==> runBibTeX= $runBibTeX");
  79. LOG ("==> runBiber = $runBiber");
  80.  
  81. if ($runBibTeX && $runBiber) {
  82.   LOG ("!!! you cannot run BibTeX and Biber at the same document ...");
  83.   LOG ("!!! Assuming to run Biber");
  84.   $runBibTeX = 0;
  85. }
  86.  
  87. my $imgNo = 0;                          # internal image counter
  88. my $pstExaLoaded = 0;                   # Document loads pst-exa
  89.  
  90. LOG ("Running on [$path][$name][$ext]");
  91. open (FILE, "<$TeXfile") or die "cannot open source file $TeXfile!";    # the source
  92. if ( !$noImages ) {
  93.   if (-d $imageDir) { LOG ("$imageDir exists") }
  94.   else { mkdir("$imageDir", 0744) || die "cannot mkdir $imageDir: $!";
  95.     LOG ("Imagedir created"); }
  96.  
  97.   LOG ("go to savePreamble ... ");
  98.   savePreamble($name);
  99.   LOG ("done!\n go to runFile ...");
  100.   runFile($name);
  101.   LOG ("done!");
  102.   close FILE;                                           # close source file
  103. }# !noImages
  104.  
  105.  
  106. LOG ("runpdfTeX ... ");
  107. runpdfTeX("$path$name",$name);
  108. LOG ("all finished ... :-)");
  109. close LOGfile;
  110. if ( $clear ) {
  111.   unlink "$path$name.aux";
  112.   unlink "$path$name.log";
  113.   unlink "$path$name.preamble";
  114.   unlink "$path$name-tmp.aux";
  115.   unlink "$path$name-tmp.dvi";
  116.   unlink "$path$name-tmp.log";
  117.   unlink "$path$name-tmp.pdf";
  118.   unlink "$path$name-tmp.ps";
  119.   unlink "$path$name-tmp.tex";
  120. }
  121.  
  122. sub savePreamble {                      # create a preamble file
  123. # if we have a \input command inside the preamble, it doesn't hurt, we need
  124. # it anyway for the postscript files and the pdf one.
  125.   my $filename = pop;                   # get the file name
  126.   LOG ("----- Start Preamble -----");
  127.   open (FILEp, ">$tempDir/$filename.preamble")
  128.     or die "cannot open preamble file $tempDir/$filename.preamble!";
  129.   while (<FILE>) {                      # read all until \begin{document}
  130.     $pstExaLoaded = index($_,"usepackage{pst-exa}");
  131.     my $i = index($_,"begin{document}");
  132.     if ($i > 0) {
  133.       if ($i > 1) { print FILEp substr($_,0,--$i); }    # write all until \begin{document}
  134.       print FILEp "\n\\usepackage{pst-exa}\n";
  135.       close(FILEp);                                     # close preamble
  136.       LOG ("----- Close Preamble ------");
  137.       return;
  138.     } else {
  139.       print FILEp "$_";                                 # write into preamble
  140.       LOG ("$_");
  141.     }
  142.   }
  143.   close(FILEp);
  144.   if ( $verbose ) { LOG("<-----Preamble<----"); }
  145.   return;
  146. }
  147.  
  148. sub searchPS {                                  # search the PostScript parts
  149.   my @PS = ();                                  # single PS sequence
  150.   my @PStotal = ();                             # all PS sequences as list of arrays
  151.   my $depth = -1;                               # counts nested macros
  152.   my $type = -1;                                # -1-> none; 1->PST; 2->PS;
  153.   my $EndDocument = 0;                          # ignore all after \end{document}
  154.   my $iVerb = 0;                                # test for verbatim or lstlisting environment, must be ignored
  155.   while (<FILE>) {                              # scan the input file
  156.     if (!$EndDocument) {
  157.     chomp;                                      # delete EOL character
  158.     my $line = $_;                              # save line
  159.     if ( !$iVerb ) {
  160.       $iVerb = ((index($line,"begin{verbatim}") > 0) or (index($line,"begin{lstlisting}") > 0));
  161.     }                                           # do nothing until \end{verbatim}
  162.     if ( !$iVerb ) {
  163.       my $iPS = index($line,"begin{postscript}");
  164.       my $iPST = index($line,"begin{pspicture*}");
  165.       if ($iPST < 0) { $iPST = index($line,"begin{pspicture}"); }       # alternative
  166.       if ($iPST < 0) { $iPST = index($line,"pspicture"); }      # alternative \pspicture...
  167.       if (($iPS > 0) && ( $type == 1 )){ print "postscript environment must be of outer level!\n"; exit 1; }
  168.       if ( $type < 0 ) {                        # no active environment
  169.         if ($iPS > 0) {                         # we have \begin{postscript}
  170.           $type = 2;                   
  171.           $line = substr($line,$iPS-1);         # add rest of the line
  172.           LOG("PS-Zeile: $line");
  173.         }                              
  174.         elsif ( $iPST > 0 ) {                   # we have \begin{pspicture} or \pspicture
  175.           $type = 1;
  176.           $depth++;  
  177.           $line = substr($line,$iPST-1);        # add all unitl pspicture
  178.           LOG("PST-Zeile: $line");
  179.         }
  180.       }
  181. #       we have now \begin{pspicture} or \begin{postscript}
  182.       if ($type > 0) {                          # start Scan, we have an environment
  183.         LOG ("searchPS: set \$type=$type");
  184.         $iPST = index($line,"end{pspicture*}");
  185.         if ($iPST < 0) { $iPST = index($line,"end{pspicture}"); }       # alternative
  186.         if ($iPST < 0) { $iPST = index($line,"endpspicture"); } # alternative \endpspicture...
  187.         $iPS = index($line,"end{postscript}"); 
  188.         if ($iPST > 0) {                        # test, we can have postscript and pspicture in one line
  189.           if ( $type < 2) {                     # found end of pspicture environment
  190.             LOG ("searchPS: $line");
  191.             $depth--;
  192.             if ($depth < 0) {
  193.               $type = -1;
  194.               if (index($line,"endpspicture") > 0)              # add line, depends to type
  195.                    { push @PS,substr($line,0,$iPST+12); }       # \endpspicture
  196.               elsif (index($line,"pspicture*") > 0)
  197.                       { push @PS,substr($line,0,$iPST+15); }    # \end{pspicture}
  198.               else { push @PS,substr($line,0,$iPST+14); }       # \end{pspicture}
  199.               LOG ("searchPS: set \$type=$type");
  200.               push @PStotal,[@PS];      # add PS sequence
  201.               LOG ("---->PS---->\n@PS\n<----PS<----");
  202.               @PS = ();                 # start new PS sequence
  203.             }                           # no pspicture env left
  204.           } else { push @PS,$line; }    # pspicture inside postscript
  205.         } elsif ($iPS > 0) {            # must be type=1 -> stop Scan
  206.           LOG ("searchPS: $line");
  207.           $type = -1;
  208.           push @PS,substr($line,0,$iPS+15);# add line
  209.           LOG ("searchPS: set \$type=$type");
  210.           push @PStotal,[@PS];          # add PS sequence
  211.           LOG ("---->PS---->\n@PS\n<----PS<----");
  212.           @PS = ();                     # start new PS sequence
  213.         } else { push @PS,$line; }              # add line
  214.       }
  215.       my $i = index($line,"end{document}");
  216.       if ($i > 0) { $EndDocument++; LOG("EndDocument in searchPS"); }
  217.     } # if ( $iVerb )
  218.     if (( index($line,"end{verbatim}") > 0 ) or ( index($line,"end{lstlisting}") > 0 )) { $iVerb = 0; }
  219.   }}
  220.   if ( $verbose ) {
  221.     LOG("---->PStotal---->");
  222.     for my $aref ( @PStotal ) {
  223.       my @a = @$aref;
  224.       my $i = 0;
  225.       foreach ( @a ) { LOG ($a[$i]); $i++; }
  226.     }
  227.     LOG ("<----PStotal<----");
  228.   }
  229.   close(FILE);
  230.   return @PStotal;                      # return all PS sequences
  231. }
  232.  
  233. sub runTeX {
  234.   my $filename = pop;
  235.   system("latex $filename"); # or die "Error in the LaTeX run from file $filename!";
  236.   system("dvips $filename"); # or die "Error in the dvips run from file $filename!";
  237.   system("ps2pdf $filename.ps");# or die "Error in the ps2pdf run from file $filename!";
  238.   copy("$filename.tex", "$imageDir/$filename-$imgNo.tex") or die "Cannot copy Source file!";;
  239.   for my $Itype ( @imageType ) {
  240.     if ($Itype eq "pdf") { system("pdfcrop $filename.pdf $imageDir/$filename-$imgNo.pdf");  }
  241.     if ($Itype eq "png") {
  242.       system("pdftoppm -f 1 -l 1 -r $DPI $imageDir/$filename-$imgNo.pdf $imageDir/");
  243.       system("convert $imageDir/-1.ppm  $imageDir/$filename-$imgNo.png");
  244.       system("rm $imageDir/-1.ppm");
  245.     }
  246.     if ($Itype eq "jpg") {
  247.       system("pdftoppm -f 1 -l 1 -r $DPI $imageDir/$filename-$imgNo.pdf $imageDir/");
  248.       system("convert $imageDir/-1.ppm  $imageDir/$filename-$imgNo.jpg");
  249.       system("rm $imageDir/-1.ppm");
  250.     }
  251.     if ($Itype eq "eps") { system("pdftops -f 1 -l 1 -eps $imageDir/$filename-$imgNo.pdf $imageDir/$filename-$imgNo.eps"); }
  252.   }
  253.   $imgNo++;
  254. }
  255.  
  256. sub runFile {
  257.   my $filename = pop;
  258.   my @PSarray = searchPS();
  259.   if ( $verbose ) {
  260.     LOG("---->PSarray---->");
  261.     for my $aref ( @PSarray ) {
  262.       my @a = @$aref;
  263.       my $i = 0;
  264.       foreach ( @a ) { print LOG $a[$i]."\n"; $i++; }
  265.     }
  266.     LOG("<----PSarray<----");
  267.     my $no = @PSarray;
  268.     LOG("PS: ".$no." PS sequence(s)");
  269.   }
  270.   for my $aref ( @PSarray ) {
  271.     my @PS = @$aref;
  272.     open (FILEp, "<$tempDir/$filename.preamble") or die "cannot open $tempDir/$filename.preamble!";
  273.     open (FILEsub, ">$tempDir/$filename-tmp.tex") or die "cannot open $tempDir/$filename-tmp.tex!";
  274.     #print FILEsub "\\RequirePackage{listings}\n";
  275.     while (<FILEp>) { print FILEsub $_; }
  276.     print FILEsub "\\pagestyle{empty}\n";
  277.     print FILEsub "\\newenvironment{postscript}{}{}\n";
  278.     print FILEsub "\\providecommand\\IncludeGraphics[2][]{}\n";
  279.     print FILEsub "\\begin{document}\n";
  280.     if ( $verbose ) { LOG("\@PS: $_"); }
  281.     foreach ( @PS ) { print FILEsub "$_\n"; }
  282.     print FILEsub "\\end{document}\n";
  283.     close (FILEsub);
  284.     close (FILEp);
  285.     runTeX("$tempDir/$filename-tmp");
  286.   }
  287. }
  288.  
  289. sub runpdfTeX() {
  290.   my ($name,$pdfname) = @_;
  291.   open (PDF, ">$tempDir/$pdfname-pdf.tex") or die "cannot open $tempDir/$pdfname-pdf.tex!";
  292.   open (FILE, "<$name.tex") or die "cannot open $name!";
  293.   print PDF "\\RequirePackage{graphicx}\n";
  294.   #if ($pstExaLoaded < 1) {
  295.    print PDF "\\let\\IncludeGraphics\\includegraphics\n"; #}
  296. #  print PDF "\\setkeys{Gin}{scale=0.25}\n";
  297. #  print PDF "\\providecommand\\psset[1]{}\n";
  298.   print PDF "\\graphicspath{{$imageDir/}}\n"; #uncomment
  299.   my $ignore = 0;
  300.   my $IMGno = 0;
  301.   my $depth = -1;
  302.   my $type = -1;
  303.   my $EndDocument = 0;                  # ignore all after \end{document}
  304.   my $iVerb = 0;
  305.   while (<FILE>) {                      # scan the input file
  306.     if ( !$iVerb ) {
  307.       $iVerb = ((index($_,"begin{verbatim}") > 0) or (index($_,"begin{lstlisting}") > 0));
  308.     } # do nothing until \end{verbatim}|| \end{lstlisting}
  309.     if ( !$iVerb ) {
  310.       my $i = index($_,"end{document}");
  311.       if ($i > 0) { print PDF $_; $EndDocument++; LOG("EndDocument in runpdfTeX"); }
  312.       if ( !$EndDocument ) {
  313.         my $iPS = index($_,"begin{postscript}");
  314.         if ( $iPS > 0 ) {
  315.           $type = 2;
  316.           $ignore = 1;
  317.           if ($iPS > 1) { print PDF substr($_,0,--$iPS); }      # add preceeding text
  318.          print PDF "\\IncludeGraphics[scale=$Iscale]{$pdfname-tmp-$IMGno$Iext}"; #change name x pdfname
  319.           $IMGno++;
  320.         }               # postscript env
  321.         if ( $type < 2 ) {
  322.           my $iPST = index($_,"begin{pspicture*}");
  323.           if ($iPST < 0) { $iPST = index($_,"begin{pspicture}"); }      # alternative ...
  324.           if ($iPST < 0) { $iPST = index($_,"\\pspicture"); }   # alternative \endpspicture...
  325.           if ( $iPST >= 0 ) {                           # start Scan
  326.             $ignore = 1;
  327.             $type = 1;
  328.             $depth++;                                   # pspicture env
  329.             LOG("Increase depth: $depth");
  330.             if ( $depth == 0 ) {
  331.               if ($iPST > 1) { print PDF substr($_,0,--$iPST); }# add preceeding text
  332.          #     print PDF "\\IncludeGraphics[scale=$Iscale]{$imageDir/$pdfname-tmp-$IMGno$Iext}"; #change name x pdfname
  333.               print PDF "\\IncludeGraphics[scale=$Iscale]{$pdfname-tmp-$IMGno$Iext}";   # use \graphicspath
  334.               $IMGno++;
  335.               LOG("Increase Image counter: $IMGno");
  336.             }
  337.           }
  338.         }
  339.         if ( !$ignore ) { print PDF "$_"; }                     # default line
  340.         if ( $type == 2 ) {                                     # postscript env
  341.           my $iPS = index($_,"end{postscript}");
  342.           if ($iPS > 0) {
  343.             print PDF substr($_,$iPS+15);                       # rest of line
  344.             $ignore = 0;
  345.             $type=-1;
  346.           }                                                     # end Scan
  347.         } elsif ( $type == 1 ) {                                # pspicture env
  348.           my $iPST = index($_,"end{pspicture*}");
  349.           if ($iPST < 0) { $iPST = index($_,"end{pspicture}"); }# alternative ...
  350.           if ($iPST < 0) { $iPST = index($_,"endpspicture"); }  # alternative \endpspicture...
  351.           if ($iPST > 0) {                                      # end Scan
  352.             if (index($_,"endpspicture") > 0)           # add rest of line, depends to type
  353.                { print PDF substr($_,$iPST+12); }       # \endpspicture
  354.             elsif (index($_,"pspicture*") > 0)
  355.                     { print PDF substr($_,$iPST+15); }  # \end{pspicture*}
  356.             else    { print PDF substr($_,$iPST+14); }  # \end{pspicture}
  357.             $depth--;
  358.             LOG("Decrease depth: $depth");
  359.             if ($depth < 0) { $ignore = 0; }
  360.           }
  361.         }
  362.       } # if ( !$EndDocument )
  363.     } else { print PDF $_; } # if ( $iVerb )
  364.     if (( index($_,"end{verbatim}") > 0 ) or ( index($_,"end{lstlisting}") > 0 )) { $iVerb = 0; }
  365.   } # while (<FILE>)
  366.   close (FILE);
  367.   close (PDF);
  368.   my $runAgain = 0;
  369.   system("pdflatex $tempDir/$pdfname-pdf");
  370.   if (-e "$tempDir/$pdfname-pdf.idx") { system("makeindex $tempDir/$pdfname-pdf.idx"); $runAgain++; }
  371.   if ($runBibTeX && -e "$tempDir/$pdfname-pdf.aux") { system("bibtex $tempDir/$pdfname-pdf");  $runAgain++; }
  372.   if ($runBiber && -e "$tempDir/$pdfname-pdf.bcf") { system("biber $tempDir/$pdfname-pdf");  $runAgain++; }
  373.   if ($runAgain) { system("pdflatex $tempDir/$pdfname-pdf"); }
  374.   if ( $clear ) {
  375.     unlink "$tempDir/$pdfname-pdf.log";
  376.     unlink "$tempDir/$pdfname-pdf.aux";
  377.   }
  378. }
  379.  
  380. sub LOG() {
  381.   if ( $verbose ) { print LOGfile "@_\n"; }
  382. }
  383.  
  384. __END__
  385.  
Coloreado en 0.012 segundos, usando GeSHi 1.0.8.4
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-05-27 19:59 @874

Creo que tengo una solución parcial, va así
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. #Archivo que quieres editar
  2. my $archivo = '$pdfname';
  3. #Definimos el array que vamos a usar
  4. my @dellines; #  array para eliminar lineas de paquetes
  5. tie @dellines, 'Tie::File', $archivo or die "No se elimino ninguna linea: $!";
  6. #para modificar las lineas
  7. foreach my $line(@dellines) {
  8. chomp($line); #  eliminamos nueva linea
  9. # Borra las lineas que contienen los paquetes indicados
  10. #$line =~ s/(\\usepackage)(\[opciones\]){nombre paquete}//gi;
  11. $line =~ s/(\\usepackage){pst-graphicx}//gi;
  12. $line =~ s/(\\usepackage){pstricks}//gi;
  13. $line =~ s/(\\usepackage){pstricks-add}//gi;
  14. #muchas más lineas
  15. }
  16. #Termina la rutina
  17. untie @dellines;
  18. ########## terminamos
  19.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4

El problema es que la inserto en el script y éste corre , pero no hace lo que pido (sigue creando el pdf con las líneas no deseadas), y no me genera los archivos dentro de la carpeta images/ .
Las interrogantes que me surgen ahora son
1.¿Cómo llamo al archivo pdf que se creó ? para poder modificarlos
2.¿Cómo utilizo las las líneas que he creado para que tengan efecto entre las líneas 1 y \begin{document}
3.¿ Es esta la mejor forma de lograr lo que busco?

He dado mil vueltas (y aprendí varias cosas cosas sobre cómo modificar texto, es una pregunta recurrente en ingles y español)

Saludos y gracias por la ayuda.
Última edición por pablgonz el 2011-05-31 20:54 @912, editado 1 vez en total
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: script Perl pst2pdf y pdfTeX

Notapor pvaldes » 2011-05-28 14:41 @653

El tema es denso pero interesante, no me lo he leído todo a fondo e igual digo una tontería pero...

> Leer $name.tex desde la primera línea hasta \begin{document} y en ellas modificar (eliminar) las líneas que quiero y seguir con el proceso.

O alternativamente sustituir ^ por ^% en esas líneas con una simple expresión regular, en cuyo caso tex simplemente las ignorará como comentarios. No se verán en el resultado final.

> El problema es que la inserto en el script y éste corre, pero no hace lo que pido...

Estás eliminando la carga de esos paquetes en tex... ¿para qué? lo lógico es que no corra si necesita alguno de ellos. Esos paquetes necesitan cargarse en un determinado orden para que funcionen bien. Mucho mejor comentarlos.

> 3.¿ Es esta la mejor forma de lograr lo que busco?

No :roll: Lo veo innecesariamente complicado. Simplemente pon todos los paquetes en la misma línea y comenta y descomenta la línea desde un editor de texto o Perl cuando lo necesites. Si borras los paquetes necesarios en el texto y necesitas volver a cargarlos, ¿cómo sabrás qué paquetes necesitabas?
Última edición por pvaldes el 2011-05-28 14:51 @660, editado 1 vez en total
pvaldes
Perlero nuevo
Perlero nuevo
 
Mensajes: 129
Registrado: 2011-01-22 12:56 @580

Re: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-05-28 14:50 @660

Ese es el gran problema... cómo leo pdfname.tex y elimino lo que necesito antes de que lo compile pdflatex...

El problema es que no sé cómo llamar a pdfname.tex después de creado, pero, antes de ser compilado, para efectuar los cambios, tie hace esa función, lee y guarda los cambios en el mismo fichero... pero no lo puedo hacer funcionar.

Cualquier ayuda se agradece.
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: script Perl pst2pdf y pdfTeX

Notapor pablgonz » 2011-05-28 14:57 @665

pvaldes escribiste:> Leer $name.tex desde la primera línea hasta \begin{document} y en ellas modificar (eliminar) las líneas que quiero y seguir con el proceso.

O alternativamente sustituir ^ por ^% en esas líneas con una simple expresión regular, en cuyo caso tex simplemente las ignorará como comentarios. No se verán en el resultado final

> El problema es que la inserto en el script y éste corre, pero no hace lo que pido...
estás eliminando la carga de esos paquetes en tex... ¿para qué? lo lógico es que no corra si necesita alguno de ellos. Esos paquetes necesitan cargarse en un determinado órden para que funcionen bien. Mucho mejor comentarlos


Comentarlos o eliminarlos da igual, ¿para qué? los paquetes son de pstricks para compilar latex>dvips>ps2pdf y como estamos creando un fichero para compilar con pdflatex... crea conflictos (dará un aviso en pantalla que estás tratando de compilar paquetes que no funciona en pdflatex) y el script se detendrá
> 3.¿ Es esta la mejor forma de lograr lo que busco?
lo veo innecesariamente complicado. Simplemente pon todos los paquetes en la misma línea y comenta y des comenta la línea desde un editor de texto o perl cuando lo necesites. Si borras los paquetes necesarios en el texto y necesitas volver a cargarlos, ¿como sabrás que paquetes necesitabas?

La idea es no editar a mano el archivo generado (por eso el script) y SÍ sé cuáles son los paquetes a eliminar (o comentar) siempre.
pablgonz
Perlero nuevo
Perlero nuevo
 
Mensajes: 236
Registrado: 2010-09-08 21:03 @919
Ubicación: Concepción (Chile)

Re: script Perl pst2pdf y pdfTeX

Notapor pvaldes » 2011-05-28 15:16 @678

> ¿Cómo llamo al archivo pdf que se creó ? para poder modificarlos
> como leo pdfname.tex y elimino lo que necesito antes de que lo compile pdflatex...

Vaya lío que me estás montando... empezaste con una pregunta, ahora has pasado a otra, o otras totalmente distintas...

Lo primero puedes cargarlo en una variable simplemente si sabes manipular pdf en crudo, pero el archivo pdf es el resultado final, no debes modificarlo con una llamada a tex desde Perl, eso es trabajo del archivo de texto .tex, lo segundo ídem, es un texto... slurp a una variable, mucho mejor camino.

¿Puedes explicar que significa exactamente que "no hace lo que quieres"?
pvaldes
Perlero nuevo
Perlero nuevo
 
Mensajes: 129
Registrado: 2011-01-22 12:56 @580

Siguiente

Volver a Básico

¿Quién está conectado?

Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 35 invitados

cron