Converta HTML para PDF com 06 linhas de Código

Sempre vejo pessoas procurando por ai como converter HTML para PDF, mas sempre as soluções são obscuras complicadas e não muito “limpas”, as vezes requerendo bibliotecas proprietárias.
Pois então vou lhe dar uma solução com apenas 06 linhas de código que salvará sua alma :smiley: . Lá vamos nós rápidos e rasteiros. Como o código é mediocremente pequeno vou colocar tudo aqui pra encher linguiça, até os imports

[code]import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;

/**

  • @Autor Eder Baum
    */
    public class Html2Pdf {

    public static void convert(String input, OutputStream out) throws DocumentException{
    convert(new ByteArrayInputStream(input.getBytes()), out);
    }

    public static void convert(InputStream input, OutputStream out) throws DocumentException{
    Tidy tidy = new Tidy();
    Document doc = tidy.parseDOM(input, null);
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(doc, null);
    renderer.layout();
    renderer.createPDF(out);
    }

}
[/code]

Se você contar o numero de linhas do 2º método convert, verá que há apenas 06 linhas como prometido, e para usar esta classe, o código é menor ainda:

OutputStream os = new FileOutputStream("C:\\hello.pdf");; Html2Pdf.convert("<h1 style=\"color:red\">Hello PDF</h1>", os); os.close();

Os jars que vc precisa são estes
Tidy : http://jtidy.sourceforge.net
XHTMLRenderer : https://xhtmlrenderer.dev.java.net/
Itext: http://www.lowagie.com/iText

Espero que tenham divertido-se.

Orra cara!! :lol:

Obrigado por compartilhar! esta função já entrou na minha listinha!

[]s

Valeu EderBaum!!!

Mas pelo que vi o documento deve ser xhtml para funcionar, estou certo?

Document doc = tidy.parseDOM(input, null);   

Obrigado,

Bem legal…
da pra fazer algo semelhante com xhtml e algumas tags do JBoss Seam…
mas nesse caso vc já escreve o documento utilizando tags que farão com que o documento seja renderizado como pdf…
da até pra colocar gráfico :smiley:

Exemplo.xhtml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;

&lt;p:document xmlns:p="http://jboss.com/products/seam/pdf"
            xmlns:ui="http://java.sun.com/jsf/facelets"&gt;
    
    &lt;p:image value="/img/logo.jpg" scalePercent="80" /&gt;
    
    &lt;p:font family="arial" size="12"&gt;
               
        &lt;p:list style="numbered"&gt;
            &lt;ui:repeat value="#{paisList.resultList}" var="pais"&gt;
                &lt;p:listItem&gt;#{pais.nome} - #{pais.estados.size}&lt;/p:listItem&gt;
            &lt;/ui:repeat&gt;
        &lt;/p:list&gt;
        
        &lt;p:barchart title="Gráfico de Barras" 
                    legend="true"
                    width="500" 
                    height="500"&gt;
            &lt;p:series key="estados"&gt;
                &lt;ui:repeat value="#{paisList.resultList}" var="pais"&gt;
                    &lt;p:data key="#{pais.nome}" columnKey="#{pais.nome}" value="#{pais.estados.size}" /&gt;
                &lt;/ui:repeat&gt;
            &lt;/p:series&gt; 
        &lt;/p:barchart&gt;
        
    &lt;/p:font&gt;
    
&lt;/p:document&gt;

Para apresentar o pdf basta vc chamar a página como se fosse uma página, ex: /Exemplo.seam

Exato. o Jtidy é um “HTML Beautifyer”, ai o que vc mandar pra ele, mesmo tags não fechadas, ou textos tirados de Blogs :lol: vai funfar.

Esta é a beleza do código, você não precisa se preocupar com as coisas baixas, basta mandar HTML em não conformidade que o resto o código cuida.

Muito obrigado!

Mas se percebi temos de passar o html linha a linha certo?

um abraço de Portugal

Não, de forma alguma.
Você pode inclusive entrar um InputStream que aponte para este post aqui neste fórum que possivelmente vai converter este tópico para PDF :-o

Inserção de imagens e tudo mais é tranquilo e simples, porém ele vai usar conexões ai pra “puxar” as imagens.

EderBaum, bom eu nunca fiz isso como eu passo esse topico para ele escrever no pdf

    OutputStream os = new FileOutputStream("C:\\hello.pdf");;  
    Html2Pdf.convert("Coloco aki a url ????????????", os);           
    os.close();  

Desde ja agradeço atençao.

Bom ja consegui escrever de uma url


URL u = new URL ("http://www.lucascorrea.com.br");
//System.out.println (u);
URLConnection conn = u.openConnection();
InputStream is = conn.getInputStream(); 
		
OutputStream os = new FileOutputStream("C:\\hello.pdf");
Html2Pdf.convert(is, os);           
os.close();  

Mais ele não carregar as imagens como vc disse EderBaum

Bem, eu nunca tentei fazer com uma URL, e também não consigo ver onde isto seria necessário.
Mas mandando uma string tipo:

OutputStream os = new FileOutputStream("C:\\hello.pdf"); Html2Pdf.convert("<b>Uma Imagem</b>\n\n<br /><img src=\"http://f.i.uol.com.br/folha/informatica/images/0735360.jpg\" />", os); os.close();

Isto pra mim funcionou perfeitamente, mas minha aplicação está rodando já num servidor na Web.

Já sei o que houve. Neste meu exemplo acima eu uso o caminho completo da imagem no “src”, já na sua página é sempre apontado o caminho relativo, e ai não vai mesmo.

Eu tambem testei.

No netbeans 6.0 criei a classe Html2Pdf

[code]package javaapplication1;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.lowagie.text.DocumentException;

public class Html2Pdf {

public static void convert(String input, OutputStream out) throws DocumentException{   
    convert(new ByteArrayInputStream(input.getBytes()), out);   
}   
   
public static void convert(InputStream input, OutputStream out) throws DocumentException{   
    Tidy tidy = new Tidy();           
    Document doc = tidy.parseDOM(input, null);   
    ITextRenderer renderer = new ITextRenderer();   
    renderer.setDocument(doc, null);   
    renderer.layout();         
    renderer.createPDF(out);                   
}     

} [/code]

e a main

[code]package javaapplication1;

import java.net.;
import java.io.
;
import java.io.InputStream;
import java.io.OutputStream;
import javaapplication1.Html2Pdf;

/**
*

  • @author Admin
    */
    public class Main {

    /**

    • @param args the command line arguments
      */
      public static void main(String[] args)throws Exception{

      try{
      URL u = new URL(“http://www.guj.com.br/posts/list/77682.java”);
      //System.out.println (u);
      URLConnection conn = u.openConnection();
      InputStream is = conn.getInputStream();

      OutputStream os = new FileOutputStream(“C:\TEMP\hello.pdf”);
      Html2Pdf.convert(is, os);
      os.close();
      } catch (IOException e) {
      // Print out the exception that occurred
      System.out.println(e.getMessage());
      }

    }
    }[/code]

e como resultado obtive

[code]Tidy (vers 4th August 2000) Parsing “InputStream”
line 58 column 1 - Warning:

repeated attribute
line 58 column 1 - Warning:
repeated attribute
line 58 column 1 - Warning:
repeated attribute
line 58 column 1 - Warning:
lacks “summary” attribute
line 61 column 46 - Warning: img lacks “alt” attribute
line 65 column 111 - Warning: trimming empty

InputStream: Document content looks like HTML proprietary
55 warnings/errors were found!

plumbing.render INFO:: Using CSS implementation from: org.xhtmlrenderer.context.StyleReference
plumbing.css-parse WARNING:: (null#inline_style_1) Invalid URL, no protocol: null#inline_style_1 at line 1. Skipping @import rule.
plumbing.css-parse WARNING:: (null#inline_style_2) Invalid URL, no protocol: null#inline_style_2 at line 1. Skipping @import rule.
plumbing.css-parse WARNING:: (null#inline_style_3) Invalid URL, no protocol: null#inline_style_3 at line 1. Skipping @import rule.
plumbing.css-parse WARNING:: (null#inline_style_4) Invalid URL, no protocol: null#inline_style_4 at line 1. Skipping @import rule.
plumbing.load INFO:: TIME: parse stylesheets 204ms
plumbing.match INFO:: media = print
plumbing.match INFO:: Matcher created with 118 selectors
plumbing.css-parse WARNING:: (style attribute) colspan/rowspan must be greater than zero at line 1. Skipping declaration.
plumbing.css-parse WARNING:: (style attribute) colspan/rowspan must be greater than zero at line 1. Skipping declaration.
plumbing.exception WARNING:: item at URI file:/img/logo.gif not found
plumbing.exception WARNING:: item at URI file:/img/logo.gif not found
plumbing.exception WARNING:: item at URI file:/img/tltl.gif not found
plumbing.exception WARNING:: item at URI file:/img/tlbl.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/xml_button.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/avatar/c591d12b9dbf597d4e38f56c674ecf0e.jpg not found
plumbing.exception WARNING:: item at URI file:/images/avatar/0676f43ba89ef089f43c6f36ca40fa4a.png not found
plumbing.exception WARNING:: item at URI file:/images/avatar/402cac3dacf2ef35050ca72743ae6ca7.jpg not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/avatar/1b84c4cee2b8b3d823b30e2d604b1878.png not found
plumbing.exception WARNING:: item at URI file:/images/avatar/1b84c4cee2b8b3d823b30e2d604b1878.png not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_msnm.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_email.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_msnm.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_email.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_msnm.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_email.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_msnm.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/xml_button.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/c591d12b9dbf597d4e38f56c674ecf0e.jpg not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_msnm.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/0676f43ba89ef089f43c6f36ca40fa4a.png not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/402cac3dacf2ef35050ca72743ae6ca7.jpg not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_email.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_msnm.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/1b84c4cee2b8b3d823b30e2d604b1878.png not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_email.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_msnm.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/1b84c4cee2b8b3d823b30e2d604b1878.png not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_email.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_msnm.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/icon_minipost_new.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbin
g.exception WARNING:: item at URI file:/templates/default/images/icon_up.gif not found
plumbing.exception WARNING:: item at URI file:/images/avatar/b937384a573b94c4d7cc6004c496f919.jpg not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
plumbing.exception WARNING:: item at URI file:/templates/default/images/spacer.gif not found
plumbing.exception WARNING:: item at URI file:/images/transp.gif not found
BUILD SUCCESSFUL (total time: 5 seconds)[/code]

Alguma ideia para resolver o problema?

Esqueçam tudo que eu falei sobre converter este POST para PDF.
Veja este erro:

plumbing.exception WARNING:: item at URI file:/img/logo.gif not found 

Ele nunca vai achar o arquivo /img/logo.gif pois o programa está rodando em sua máquina, e é nela que este vai ser procurado. Pra funcionar tem que trocar o /img/logo.gif por http://www.guj.com.br/img/logo.gif.
Sacou?

Se testar este exemplo abaixo com imagens, verá que vai dar certo.

OutputStream os = new FileOutputStream("C:\\hello.pdf"); Html2Pdf.convert("<b>Uma Imagem</b>\n\n<br /><img src=\"http://f.i.uol.com.br/folha/informatica/images/0735360.jpg\" />", os); os.close();

Eu usei este post titulo de exemplo… :roll:

mas axo que ja estendi…

quer dizer que se se tiver este codigo no servidor logo irá funcionar por inteiro?

e se for uma pagina jsp também funciona? desde que a pagina ja esteja carregada?

obrigado 8)

[quote=Nothunt]Eu usei este post titulo de exemplo… :roll:

mas axo que ja estendi…

quer dizer que se se tiver este codigo no servidor logo irá funcionar por inteiro?

e se for uma pagina jsp também funciona? desde que a pagina ja esteja carregada?

obrigado 8)

[/quote]

O retorno de um request HTTP que retorne HTML não tem como saber se esse HTML foi criado através de um JSP, se já era HTML puro, ou qualquer outra coisa. O stream retornado é HTML e pronto. Logo, irá funcionar para JSP também.

O problema aqui é a besteira que eu falei de converter este tópico aqui para PDF.
Não vai dar certo por causa das imagens que usam caminho relativo e não absoluto, portanto:

PELO AMOR DE DEUS NÃO CONVERTA A URL DESTE TÓPICO PARA PDF.

isso pq no final das contas a classe pega o String HTML e nem se dá conta que a imagem que aponta para /img/logo.gif está lá no servidor http://www.guj.com.br, ela “acha” que a coisa tah no seu HD.

Mas repito e repito de novo. Teste isso aqui oh que funciona:

OutputStream os = new FileOutputStream("C:\\hello.pdf"); Html2Pdf.convert("<b>Uma Imagem</b>\n\n<br /><img src=\"http://f.i.uol.com.br/folha/informatica/images/0735360.jpg\" />", os); os.close();

Galera,

perguntinha básica…

funciona com CSS??? O PDF vai ter a aparencia do bendito CSS? ou quebra?

Alguem testou?

No meu esta dando erro no exato momento em que instancio a classe ITextRenderer,o erro esta na linha 6

  public static void convert(InputStream input, OutputStream out)
            throws DocumentException {
        Tidy tidy = new Tidy();
        Document doc = tidy.parseDOM(input, null);
       
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver resolver = renderer.getFontResolver();
        try {
			resolver.addFont("C:\\Windows\\Fonts\\TIMES.TTF",
			        BaseFont.IDENTITY_H,
			        BaseFont.NOT_EMBEDDED
			        );
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        renderer.setDocument(doc, null);
        renderer.layout();
        renderer.createPDF(out);
    }
       
    
    
   public static void main(String[] args) {

       try {

            InputStream in = new FileInputStream(new File("C:\\teste.html"));

            OutputStream out = new FileOutputStream("C:\\hello.pdf");
            try {
                Html2Pdf.convert(in, out);
            } catch (DocumentException e1) {
                e1.printStackTrace();
            }
            out.close();
        } catch (IOException e) {

            System.out.println(e.getMessage());
        }
  
   
        
    }

StackTrace:

        Exception in thread "main" java.lang.NoSuchMethodError: com.lowagie.text.pdf.BaseFont.getCharBBox(C)[I
	at org.xhtmlrenderer.pdf.ITextFontResolver$FontDescription.setMetricDefaults(ITextFontResolver.java:496)
	at org.xhtmlrenderer.pdf.ITextFontResolver$FontDescription.<init>(ITextFontResolver.java:427)
	at org.xhtmlrenderer.pdf.ITextFontResolver.addCourier(ITextFontResolver.java:229)
	at org.xhtmlrenderer.pdf.ITextFontResolver.createInitialFontMap(ITextFontResolver.java:209)
	at org.xhtmlrenderer.pdf.ITextFontResolver.<init>(ITextFontResolver.java:44)
	at org.xhtmlrenderer.pdf.ITextRenderer.<init>(ITextRenderer.java:81)
	at org.xhtmlrenderer.pdf.ITextRenderer.<init>(ITextRenderer.java:68)
	at br.gov.prodemge.pcnet.pat.comuns.Html2Pdf.convert(Html2Pdf.java:40)
	at br.gov.prodemge.pcnet.pat.comuns.Html2Pdf.main(Html2Pdf.java:68)

Isso esta me parecendo algum erro com algum jar…nao sei…as que eu adicionei no projeto são:
core-renderer.jar
iText-2.0.8.jar
itext-paulo-155.jar
minium.jar
Tidy.jar
Se alguem souber…por favor me ajudem…

Solucionei o problema…retirei todos os outros jars do meu class-path e deixei apenas as responsaveis pela renderização e funcionou sem problemas…

Hey Eder me esclaece uma dúvida…

eu estou tentando converter o seguinte codigo…

OutputStream os = new FileOutputStream("C:\\hello.pdf");;  
DSHtml2Pdf.convert("<b>AAAAAAAAAAAAAAAA</b>", os);
os.close();

Com o JTidy esta tudo certo, pois quando eu testo o comando tidy.parse() ele me retorna um XHTML correto, sem problemas…
Mais na hora de gerar um PDF ele da o seguinte erro…

[code]

Tidy (vers 4th August 2000) Parsing “InputStream”
line 1 column 1 - Warning: inserting missing ‘title’ element

InputStream: Document content looks like HTML 3.2
1 warnings/errors were found!

Could not execute action
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at com.opensymphony.xwork.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:353)
at com.opensymphony.xwork.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:208)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:182)
at com.opensymphony.xwork.interceptor.DefaultWorkflowInterceptor.intercept(DefaultWorkflowInterceptor.java:125)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.webwork.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:136)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:146)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.AroundInterceptor.intercept(AroundInterceptor.java:32)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:94)
at com.opensymphony.xwork.DefaultActionInvocation.invoke(DefaultActionInvocation.java:180)
at com.opensymphony.xwork.DefaultActionProxy.execute(DefaultActionProxy.java:113)
at com.opensymphony.webwork.dispatcher.DispatcherUtils.serviceAction(DispatcherUtils.java:202)
at com.opensymphony.webwork.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:184)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)
Caused by: java.lang.NoSuchMethodError: com.lowagie.text.Rectangle.height()F
at org.xhtmlrenderer.pdf.ITextRenderer.writePDF(ITextRenderer.java:262)
at org.xhtmlrenderer.pdf.ITextRenderer.createPDF(ITextRenderer.java:250)
at org.xhtmlrenderer.pdf.ITextRenderer.createPDF(ITextRenderer.java:191)
at br.com.dsystems.util.converter.DSHtml2Pdf.convert(DSHtml2Pdf.java:25)
at br.com.dsystems.util.converter.DSHtml2Pdf.convert(DSHtml2Pdf.java:16)
at br.com.dsystems.ds001.beans.TesteBean.testeVoucher(TesteBean.java:42)
… 50 more[/code]

Não estou entendendo oq está acontecendo…

Outra pergunta…
No seu exemplo vc faz o HTML gerar um arquivo PDF.

O que eu preciso fazer com este conversor é o seguinte.

Pegar uma string com tags HTML, e passar este HTML para PDF e salvar no banco de dados.
Depois disto este codigo em PDF vai ser usado para integrar um relatório q vai ser gerado com o iReport.
Isto é possível com este código q vc deu ?
Se for vai me ajuda muito hehehe =]

Obrigado
Aguardo Respostas
Rodrigo Kerkhoff