• Publicidad

Generar HTML desde archivo Word (docx)

Así que programas sin strict y las expresiones regulares son otro modo de hablar. Aquí encontrarás respuestas de nivel avanzado, no recomendable para los débiles de corazón.

Generar HTML desde archivo Word (docx)

Notapor dolisguilarte » 2012-12-05 16:11 @716

Necesito generar un pdf y colocarle unas marcas de agua a un documento que ha subido el usuario en formato Word. Yo sé que generar el pdf desde un html es posible. De hecho, lo puedo hacer. Lo que no sé es cómo convertir el Word en html para luego pasar a pdf.

Así puedo generar el pdf desde un html:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1.     my $pdf = "prueba_externo.pdf";
  2.     print $root_htmldoc . "<br>";
  3.     print $root_path;
  4.     my $commandline
  5.         = $root_htmldoc
  6.         . "htmldoc.exe --quiet --left 1cm --charset iso-8859-1 --bottom 0.2cm --header ... --footer ../ --size A4 --right 1cm --toctitle INDICE --tocfooter ... --tocheader ... --bodyfont Helvetica --fontsize 12 --fontspacing 1.5 --bodyimage "
  7.         . $root_path
  8.         . "sbmp\\images\\fondo_doctos.gif --titlefile "
  9.         . $root_path
  10.         . "sbmp\\tmpDocs\\tpl\\portada.html --top 5.5cm --format pdf  --firstpage p1--portrait --book -f "
  11.         . $root_path
  12.         . "sbmp\\originales\\$pdf "
  13.         . $root_path
  14.         . "sbmp\\originales\\123.html";
  15.     select(STDOUT);
  16.     $| = 1;
  17.     system($commandline);
  18.  
Coloreado en 0.005 segundos, usando GeSHi 1.0.8.4
dolisguilarte
Perlero nuevo
Perlero nuevo
 
Mensajes: 21
Registrado: 2012-03-07 16:33 @731

Publicidad

Re: Generar HTML desde archivo Word (docx)

Notapor explorer » 2012-12-05 17:13 @759

En CPAN hay un módulo para ello: MSWord::ToHTML, pero requiere la presencia de los binarios de Abiword y tidy.

El truco que hace es que usa Abiword para hacer la conversión:

system( 'abiword', '-t', 'html', '-o', $new_file, $self->file );

Y luego realiza un proceso de limpieza y formateo del código HTML (para que no salga demasiado verboso).

Puedes probarlo, a ver sí así sale, pero también puedes buscar algún conversor binario directo (que no sé si existe).

Y luego, para pasar de HTML a PDF, también hay varias soluciones en CPAN. Y luego para poner la marca de agua...
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Generar HTML desde archivo Word (docx)

Notapor reLlene » 2012-12-06 20:05 @878

¿Quieres llegar a un .pdf desde un .doc y para ello pasas el .doc a un template y luego del template a un .pdf y finalmente le agregas la marca de agua? ¿Por qué te lías? :?

Para ello limítate al uso de unoconv desde la terminal y luego te ocupas de la marca de agua... Para más información AQUI y claro, dentro de los formatos podrás ver luego que el exportar por defecto es en formato PDF. Todo esto desde Linux, claro.

Sino, desde Windows tienes la solución aquí: éste.

Vamos, excepto que necesites lo que pides para alguna webapp, la generación del mismo ligado a la previsualización final del pdf y su marca de agua, ¡¡ya nos dirás!!

Saludos.
Sexo : unzip ; strip ; touch ; grep ; finger ;mount ; fsck ; more ; yes ; umount ; sleep.
Avatar de Usuario
reLlene
Perlero nuevo
Perlero nuevo
 
Mensajes: 97
Registrado: 2012-06-04 07:16 @344

Re: Generar HTML desde archivo Word (docx)

Notapor dolisguilarte » 2012-12-10 09:48 @450

A ver, el usuario sube dos archivos, uno en .doc y uno en .pdf; a este último necesito ponerle una marca de agua. El sistema ya tiene un script que convierte de HTML a PDF y entre medio le pone la marca de agua.

Ahora, como NO tengo el html tengo que, o convertir el doc a html -que intenté hacerlo y me empezó a pedir un montón de librerías que no tengo en el servidor-, o bien ponerle la marca de agua directo al archivo pdf que sube el usuario...

El tema es que intenté esta última opción con el código de abajo y no le pone nada :(

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. use CGI qw/:standard *Tr *table *td *script/;
  2. use HTML::Myasp;
  3. use SBMP::XSesion;
  4. print "Content-Type: text/html\n\n";
  5.  
  6.  
  7. use TeX::AutoTeX::StampPDF qw(stamp_pdf);
  8. my $pdfnew=$root_path."sbmp\\tmpDocs\\marca_agua.pdf";
  9. @referencia = ("HOLA ESTA ES LA MARCA DE AGUA");
  10. my $array_ref = \@referencia;
  11. stamp_pdf($pdffile, $array_ref);
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4


Sorry... Tenía un error en el nombre del archivo en el código anterior, AHORA SÍ LO HACE... PEROOOO... solo en la primera página... ¿Saben cómo puedo colocarle la marca de agua a todas las páginas del pdf?

Mil Gracias

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. use CGI qw/:standard *Tr *table *td *script/;
  2. use HTML::Myasp;
  3. use SBMP::XSesion;
  4. print "Content-Type: text/html\n\n";
  5.  
  6.  
  7. use TeX::AutoTeX::StampPDF qw(stamp_pdf);
  8. my $pdffile=$root_path."sbmp\\tmpDocs\\marca_agua.pdf";
  9. @referencia = ("HOLA ESTA ES LA MARCA DE AGUA");
  10. my $array_ref = \@referencia;
  11. stamp_pdf($pdffile, $array_ref);
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
dolisguilarte
Perlero nuevo
Perlero nuevo
 
Mensajes: 21
Registrado: 2012-03-07 16:33 @731

Re: Generar HTML desde archivo Word (docx)

Notapor explorer » 2012-12-10 11:51 @536

El TeX::AutoTeX::StampPDF usa internamente el módulo CAM::PDF para colocar la marca de agua en la primera página. Si miras su código fuente, verás que usa una línea

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
    $doc->appendPageContent(1, $pdfstamp);
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Ese '1' hace referencia a la primera página.

Quizás lo puedas resolver haciendo un bucle por todas las páginas, llamando a este método.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Generar HTML desde archivo Word (docx)

Notapor dolisguilarte » 2012-12-26 10:40 @486

Gracias, te pasaste... Ahora sí... Hice los ajustes con un for y funcionó el método que devuelve el número de páginas en el pdf, que es numPages().

Esto fue lo que modifiqué en el archivo StampPDF.pm:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. for ( $y = 0; $y < $doc->numPages(); $y++ ) {
  2.     $doc->appendPageContent( $y + 1, $pdfstamp );
  3.     $doc->addFont( $y + 1, 'Times-Roman', 'arXivStAmP' ) || cluck "$CAM::PDF::errstr\n";
  4. }
  5.  
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4



Gracias :P
dolisguilarte
Perlero nuevo
Perlero nuevo
 
Mensajes: 21
Registrado: 2012-03-07 16:33 @731

Re: Generar HTML desde archivo Word (docx)

Notapor dolisguilarte » 2012-12-26 10:44 @488

Hola, estoy reactivando este tema porque ahora necesito colocar un mensaje en el pie de un pdf. La biblioteca a continuación me permite colocarlo de forma vertical al lado izquierdo de la hoja... De verdad no sé cómo poner el mensaje al final de cada hoja tal como un pie. Este es el código:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. package TeX::AutoTeX::StampPDF;
  2. #
  3. # $Id: StampPDF.pm,v 1.9.2.7 2011/01/27 18:42:29 thorstens Exp $
  4. # $Revision: 1.9.2.7 $
  5. # $Source: /cvsroot/arxivlib/arXivLib/lib/TeX/AutoTeX/StampPDF.pm,v $
  6. #
  7. # $Date: 2011/01/27 18:42:29 $
  8. # $Author: thorstens $
  9. #
  10.  
  11. use strict;
  12. ### use warnings;
  13. use Carp qw(cluck carp);
  14.  
  15. our ($VERSION) = '$Revision: 1.9.2.7 $' =~ m{ \$Revision: \s+ (\S+) }x;
  16.  
  17. use parent qw(Exporter);
  18. our @EXPORT_OK = qw(stamp_pdf);
  19. use CAM::PDF;
  20.  
  21. sub stamp_pdf {
  22.   my ($file, $stampref) = @_;
  23.  
  24.   if (!(-r $file && ref $stampref eq 'ARRAY')) {
  25.     #FIXME: pod2usage;
  26.     throw TeX::AutoTeX::FatalException "must provide pdf file and stamp contents\n";
  27.   }
  28.  
  29.   # 6 * 72 - 1/2 * stringlength * 10
  30.   # (10 = approx average char width in 20pt Times-Roman)
  31.  my $yoffset = 432 - 5 * length $stampref->[0];
  32. # minimal arXiv stamp used as a page overlay in grayscale
  33.   my $pdfstamp = <<"EOSTAMP";
  34. q
  35. 0.5 G 0.5 g
  36. BT
  37. /arXivStAmP 20 Tf 0 1 -1 0 32 $yoffset Tm
  38. ($stampref->[0])Tj
  39. ET
  40. Q
  41. EOSTAMP
  42.  
  43.   rename($file, "$file.bk") || throw TeX::AutoTeX::FatalException q{couldn't backup PDF file};
  44.  
  45.  eval {
  46.    my $doc = CAM::PDF->new("$file.bk") || cluck "$CAM::PDF::errstr\n";
  47.    if (!$doc->canModify()) {
  48.      throw TeX::AutoTeX::FatalException "This PDF forbids modification\n";
  49.    }
  50.         #***********AJUSTES PARA IMPRIMIR LA MARCA EN CADA HOJA DEL PDF 10/12/2012
  51.                 my $y;
  52.                 for ($y=0; $y< $doc->numPages(); $y++) {
  53.                   $doc->appendPageContent($y + 1, $pdfstamp);
  54.                   $doc->addFont($y + 1, 'Times-Roman', 'arXivStAmP') || cluck "$CAM::PDF::errstr\n";
  55.                 }
  56.    #**************************************************************************************
  57.         $doc->preserveOrder();
  58.    $doc->cleanoutput($file) || cluck "$CAM::PDF::errstr\n";
  59.    1;
  60.  } or do {
  61.    rename("$file.bk", $file) || carp 'woe is me, now that failed';
  62.    throw TeX::AutoTeX::FatalException "stamp operation did not complete\n";
  63.  };
  64.  if ($@) {
  65.    rename("$file.bk", $file) || carp 'woe is me, now that failed';
  66.    throw TeX::AutoTeX::FatalException "an error occurred during stamp operation, reverted to original file\n";
  67.  }
  68.  unlink "$file.bk";
  69.  return 0;
  70. }
  71.  
  72. 1;
  73.  
  74. __END__
  75.  
  76. =for stopwords PDF PDF-only arXiv arxiv.org pdflatex FontSize writeable euid www-admin Schwander arxiv perlartistic
  77.  
  78. =head1 NAME
  79.  
  80. TeX::AutoTeX::StampPDF - watermark PDF files
  81.  
  82. =head1 VERSION
  83.  
  84. This documentation refers to TeX::AutoTeX::StampPDF version 1.9.2.5
  85.  
  86. =head1 SYNOPSIS
  87.  
  88. use TeX::AutoTeX::StampPDF qw(stamp_pdf);
  89.  
  90. stamp_pdf($pdffile, $array_ref);
  91.  
  92. =head1 DESCRIPTION
  93.  
  94. This module modifies a given PDF file. It prints an arbitrary text string
  95. (within certain length limits) onto the left edge of the 1st page of a well
  96. formed PDF file.
  97.  
  98. This is intended to be used to put the arXiv stamp onto PDF-only and pdflatex
  99. submissions, but any type of "watermark" text string is possible.
  100.  
  101. Non adjustable settings are:
  102.  
  103. Font: Times-Roman
  104.  
  105. FontSize: 20
  106.  
  107. X-Y offsets
  108.  
  109. =head1 SUBROUTINES/METHODS
  110.  
  111. The single subroutine exported by this package is C<stamp_pdf>.
  112.  
  113. =head2 stamp_pdf
  114.  
  115. C<stamp_pdf> takes 2 arguments, the name of a PDF file, which must be apt to be opened C<r/w>, and a reference to an array, which contains a text string in its C<[0]th> element. A backup file of the original PDF is created temporarily, thus the current working directory has to be writeable by euid.
  116.  
  117. The reason for the second argument to be a reference to an array is that we intend to add an associated hyperlink to the stamp, which will be paired with the C<[0]> element. Current limitations of CAM::PDF make this difficult.
  118.  
  119. =head1 DIAGNOSTICS
  120.  
  121. throw a TeX::AutoTeX::FatalException
  122.  
  123. =head1 CONFIGURATION AND ENVIRONMENT
  124.  
  125. none
  126.  
  127. =head1 DEPENDENCIES
  128.  
  129. CAM::PDF
  130.  
  131. =head1 INCOMPATIBILITIES
  132.  
  133. none
  134.  
  135. =head1 BUGS AND LIMITATIONS
  136.  
  137. The placement of the stamp is tuned to US letter size paper and dimensions
  138. are hard-coded. This is easily adaptable to other paper sizes if necessary.
  139.  
  140. Please report bugs to L<www-admin|http://arxiv.org/help/contact>
  141.  
  142. =head1 AUTHOR
  143.  
  144. Thorsten Schwander <[email protected]>
  145.  
  146. =head1 LICENSE AND COPYRIGHT
  147.  
  148. Copyright (c) 2007 - 2011 arxiv.org L<http://arxiv.org/help/contact>
  149.  
  150. This module is free software; you can redistribute it and/or modify it under
  151. the same terms as Perl itself. See
  152. L<perlartistic|http://www.opensource.org/licenses/artistic-license-2.0.php>.
  153.  
  154. =cut
  155.  
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4
dolisguilarte
Perlero nuevo
Perlero nuevo
 
Mensajes: 21
Registrado: 2012-03-07 16:33 @731

Re: Generar HTML desde archivo Word (docx)

Notapor explorer » 2012-12-27 11:33 @523

¡¡¡Madre mía!!! ¡¡¡Has modificado una biblioteca para poder escribir en todas las hojas!!!

¿No sería más cómodo usar un programa aparte?

En cuanto al problema, si se solucionó con código PDF el colocar el sello en la parte izquierda, de la misma se solucionará para ponerlo en el pie. Todo consiste en saber qué código PDF debes usar.
JF^D Perl programming & Raku programming. Grupo en Telegram: https://t.me/Perl_ES
Avatar de Usuario
explorer
Administrador
Administrador
 
Mensajes: 14476
Registrado: 2005-07-24 18:12 @800
Ubicación: Valladolid, España

Re: Generar HTML desde archivo Word (docx)

Notapor dolisguilarte » 2012-12-27 11:45 @531

Hola. Ya resolví con este código bastante simple... Yo me compliqué con el tema...

Ahora sí, resuelto... Gracias.

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
  1. use PDF::API2 qw();
  2. {
  3.     my $pdf = PDF::API2->open('sbmp\\cgi-binD1\\marca_agua.pdf');
  4.     for my $index (1 .. $pdf->pages) {
  5.         my $page = $pdf->openpage($index);
  6.         my $txt  = $page->text;
  7.         $txt->textlabel(55,30, $pdf->corefont('Arial'), 6, "Documento Restringido. Propiedad de   xxxxxxxxxxxxxxxxxxxx");
  8.     }
  9.     $pdf->saveas('sbmp\\cgi-binD1\\marca_agua.pdf');
  10.     $pdf->end;
  11. }
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4
dolisguilarte
Perlero nuevo
Perlero nuevo
 
Mensajes: 21
Registrado: 2012-03-07 16:33 @731


Volver a Avanzado

¿Quién está conectado?

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

cron