Advertisement
Delta

html -> pdf

Feb 12th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. /*
  2. Baixar livrarias iText e XMLWorker:
  3. - http://sourceforge.net/projects/itext/files/iText/iText5.5.5/
  4. - http://sourceforge.net/projects/xmlworker/files/xmlworker-5.5.5.zip/download
  5.  
  6. Inclui no projeto só os arquivos: "xmlworker-5.5.5.jar" e "itextpdf-5.5.5.jar"
  7.  
  8. No form de relatórios importa essas classes:
  9. */
  10. import com.itextpdf.tool.xml.*;
  11. import com.itextpdf.text.*;
  12. import com.itextpdf.text.pdf.*;
  13. import java.io.*;
  14. import java.nio.charset.StandardCharsets;
  15. import javax.swing.JOptionPane;
  16.  
  17. /*
  18.  O código abaixo cria um PDF a partir do conteúdo da variavel "html", que é uma String e é só formatar em HTML normalmente.
  19. O que falta fazer é só puxar os dados do BD e colocar nessa string do jeito que vc achar melhor.
  20. */
  21.  
  22.  
  23.            Document doc = new Document();
  24.            String html = "<html><body><table><tr><td>Teste</td><td>123</td></tr></table></body></html>";
  25.            InputStream stream = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));
  26.            try
  27.            {
  28.                 File pdf = new File("relatorio.pdf");
  29.                 JOptionPane.showMessageDialog(null, pdf.getAbsoluteFile());
  30.                 pdf.createNewFile();
  31.                 FileOutputStream sPdf = new FileOutputStream(pdf);
  32.                 PdfWriter writer = PdfWriter.getInstance(doc, sPdf);
  33.                 doc.open();
  34.                 XMLWorkerHelper.getInstance().parseXHtml(writer, doc, stream);
  35.                 doc.close();
  36.                 sPdf.close();
  37.            }
  38.            catch(DocumentException|FileNotFoundException e)
  39.            {
  40.                JOptionPane.showMessageDialog(null, e.getClass().toString());
  41.            }
  42.            catch(IOException e)
  43.            {
  44.                JOptionPane.showMessageDialog(null, e.toString());
  45.            }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement