Boleto PDF

Jul 15, 2011 at 12:11 PM
Edited Jul 15, 2011 at 1:52 PM

Ola, Devido as muitas solicitacoes, segue abaixo o codigo em VB para gerar o boleto em PDF.  Sao duas aplicacoes  uma em VB e uma classe em C# para gerar a imagem.

Use o  Visual Studio 2010

1) BOLETO PDF:

Crie um projeto WebForm: copie e cole o codigo abaixo:

' =========================================================================================

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Text
Imports System.IO
Imports System.Threading
Imports BoletoNet
Imports System.Net.Mail
Imports System.Net.Mime
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Imports imagePDF

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub
    Protected Sub BtnGerarBoleto_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnGerarBoleto.Click
        Dim bb As BoletoBancario = New BoletoBancario
        bb.CodigoBanco = 237
        ' Enviar comprovante de entrega para testar o maior tamanho de boleto no Papel A4
        bb.MostrarComprovanteEntrega = True
        Dim vencimento As Date = New DateTime(2011, 3, 27)
        Dim c As Cedente = New Cedente("11.111.111/1111-11", "Nome do Cedente Ltda.", "1234", "11111")
        c.ContaBancaria.Agencia = "0123"
        c.ContaBancaria.DigitoAgencia = "P"
        c.ContaBancaria.Conta = "11111"
        c.ContaBancaria.DigitoConta = "1"
        c.CPFCNPJ = "11.111.111/0001-11"
        c.Nome = "Nome Cedente Ltda."
        Dim b As Boleto = New Boleto(vencimento, 70.0, "06", "13104800205", c, New EspecieDocumento(237, 2))
        b.NumeroDocumento = Convert.ToString(2072)
        b.Sacado = New Sacado("22.222.222/0001-22", "Nome do Sacado")
        b.Sacado.Endereco.End = "Rua da Quitanda, 999"
        b.Sacado.Endereco.Bairro = "Botafogo"
        b.Sacado.Endereco.Cidade = "Rio de Janeiro"
        b.Sacado.Endereco.CEP = "22061000"
        b.Sacado.Endereco.UF = "RJ"
        '  São 7 instruções para testar o maior tamanho possível do formulário
        Dim item1 As Instrucao_Bradesco = New Instrucao_Bradesco()
        item1.Descricao += ("1,00 por dia de antecipação.")
        b.Instrucoes.Add(item1)
        Dim item2 As Instrucao_Bradesco = New Instrucao_Bradesco()
        b.Instrucoes.Add(item2)
        item2.Descricao += ("2,00 por dia de antecipação.")
        Dim item3 As Instrucao_Bradesco = New Instrucao_Bradesco()
        item3.Descricao += ("3,00 por dia de antecipação.")
        b.Instrucoes.Add(item3)
        Dim item4 As Instrucao_Bradesco = New Instrucao_Bradesco()
        item4.Descricao += ("4,00 por dia de antecipação.")
        b.Instrucoes.Add(item4)
        Dim item5 As Instrucao_Bradesco = New Instrucao_Bradesco()
        item5.Descricao += ("5,00 por dia de antecipação.")
        b.Instrucoes.Add(item5)
        Dim item6 As Instrucao_Bradesco = New Instrucao_Bradesco()
        item6.Descricao += ("6,00 por dia de antecipação.")
        b.Instrucoes.Add(item6)
        Dim item7 As Instrucao_Bradesco = New Instrucao_Bradesco()
        item7.Descricao += ("7,00 por dia de antecipação.")
        b.Instrucoes.Add(item7)
        b.Aceite = "Sem"
        b.Especie = "DM"
        bb.Boleto = b
        bb.Boleto.Valida()
        Dim html As StringBuilder = New StringBuilder()
        html.Append(bb.MontaHtml())
        '  html.Append("</br></br></br></br>")
        Dim html_st As String = html.ToString
        Dim boletoPathHTML As String = System.IO.Path.Combine(System.IO.Path.GetTempPath, "Boleto.html")
        Dim f As FileStream = New FileStream(boletoPathHTML, FileMode.Create)
        Using (f)
            Dim w As StreamWriter = New StreamWriter(f, System.Text.Encoding.Default)
            w.Write(html.ToString())
            w.Close()
            f.Close()
            '  System.Diagnostics.Process.Start(boletoPathHTML) ' Exibe o boleto na página
        End Using

        Dim boletoPathPDF As String = System.IO.Path.Combine(System.IO.Path.GetTempPath, "Boleto.pdf")
        Dim imagePath As String = GerarImagem(boletoPathHTML)
        Dim doc As Document = New Document(PageSize.A4, 46, 0, 40, 0)
        PdfWriter.GetInstance(doc, New FileStream(boletoPathPDF, FileMode.Create))
        doc.Open()
        Dim gif As Image = Image.GetInstance(imagePath)
        gif.ScaleAbsolute(494.0F, 785.0F)
        doc.Add(gif)
        doc.CloseDocument()
        Dim mail As MailMessage = PrepararEmail("luiz@eportais.net") ' E-mail PARA
        mail.Subject += " - Off-Line"
        ' mail.AlternateViews.Add(bb.HtmlBoletoParaEnvioEmail()) ' Não funcionou
        Dim body As String = "<img src=""cid:logoImage""/><br><br>"
        Dim view As AlternateView = AlternateView.CreateAlternateViewFromString(body, System.Text.Encoding.UTF8, MediaTypeNames.Text.Html)
        '======
        '==== Adicionar o logo no topo do e-mail
        '======
        Dim resource As LinkedResource = New LinkedResource("C:\temp\Logos\LogoePortaisEmail.gif")
        resource.ContentId = "LogoImage"
        view.LinkedResources.Add(resource)
        mail.AlternateViews.Add(view)
        '  mail.IsBodyHtml = True
        Dim ArquiAttach As Attachment = New Attachment(boletoPathPDF, MediaTypeNames.Application.Octet)
        mail.Attachments.Add(ArquiAttach)
        EnviarEmail(mail)
    End Sub
    Function PrepararEmail(Optional ByVal emailStr As String = "") As MailMessage
        Dim mail As MailMessage = New MailMessage()
        Dim enderecoDE As MailAddress = New MailAddress("email DE", "Nome DE")
        mail.To.Add(New MailAddress(emailStr)) ' E-mail PARA
        mail.From = enderecoDE
        mail.Subject = "Teste de envio de Boleto Bancário"
        mail.IsBodyHtml = True
        mail.Priority = MailPriority.High
        Return (mail)
    End Function
    Private Sub EnviarEmail(ByVal mail As MailMessage)
        Dim objSmtpClient As SmtpClient = New SmtpClient()
        objSmtpClient.Host = "smtp.gmail.com"
        objSmtpClient.Port = 25
        objSmtpClient.EnableSsl = True
        objSmtpClient.Credentials = New System.Net.NetworkCredential("e-mail de acesso smtp", "senha")
        objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network
        objSmtpClient.Timeout = 60000
        objSmtpClient.Send(mail)
    End Sub
    Private Sub CriarPDF(ByVal _boletoPathHTML As String)
        Dim Documento As Document = New Document()
        Dim ms As MemoryStream = New MemoryStream()
        Dim writer As PdfWriter = PdfWriter.GetInstance(Documento, ms)
        Dim se As StringReader = New StringReader(LerHtml(_boletoPathHTML))
        Dim obj As HTMLWorker = New HTMLWorker(Documento)
        Documento.Open()
        obj.Parse(se)
        Documento.Close()
        Response.Clear()
        Response.AddHeader("content-disposition", "attachment; filename=boleto.pdf")
        Response.ContentType = "application/pdf"
        Response.Buffer = True
        Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length)
        Response.OutputStream.Flush()
        Response.End()
    End Sub
    Function LerHtml(ByVal _boletoPathHTML As String) As String
        Dim fileExists As Boolean
        fileExists = My.Computer.FileSystem.FileExists(_boletoPathHTML)
        Dim fileContents As String = " "
        If fileExists Then
            fileContents = My.Computer.FileSystem.ReadAllText(_boletoPathHTML)
        End If
        Return fileContents
    End Function
    Private Function GerarImagem(ByVal _boletoPathHTML As String) As String
        Dim width As Integer = 680
        Dim height As Integer = 1096
        Dim webBrowserWidth As Integer = 680
        Dim webBrowserHeight As Integer = 1096
        Dim bmp As System.Drawing.Bitmap = WebsiteThumbnailImageGenerator.GetWebSiteThumbnail(_boletoPathHTML, webBrowserWidth, webBrowserHeight, width, height)
        Dim boletoPathBMP As String = System.IO.Path.Combine(System.IO.Path.GetTempPath, "Boleto.bmp")
        bmp.Save(boletoPathBMP)
        Return boletoPathBMP
    End Function
End Class



2) IMAGE PDF:

Crie um projeto Class Library em C# com o nome ImagePDF: Copie e cole o código abaixo:

 

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace ImagePDF
{
    public class WebsiteThumbnailImageGenerator
    {
        public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
        {
            WebsiteThumbnailImage thumbnailGenerator = new WebsiteThumbnailImage(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight);
            return thumbnailGenerator.GenerateWebSiteThumbnailImage();
        }

        private class WebsiteThumbnailImage
        {
            public WebsiteThumbnailImage(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
            {
                this.m_Url = Url;
                this.m_BrowserWidth = BrowserWidth;
                this.m_BrowserHeight = BrowserHeight;
                this.m_ThumbnailHeight = ThumbnailHeight;
                this.m_ThumbnailWidth = ThumbnailWidth;
            }

            private string m_Url = null;
            public string Url
            {
                get
                {
                    return m_Url;
                }
                set
                {
                    m_Url = value;
                }
            }

            private Bitmap m_Bitmap = null;
            public Bitmap ThumbnailImage
            {
                get
                {
                    return m_Bitmap;
                }
            }

            private int m_ThumbnailWidth;
            public int ThumbnailWidth
            {
                get
                {
                    return m_ThumbnailWidth;
                }
                set
                {
                    m_ThumbnailWidth = value;
                }
            }

            private int m_ThumbnailHeight;
            public int ThumbnailHeight
            {
                get
                {
                    return m_ThumbnailHeight;
                }
                set
                {
                    m_ThumbnailHeight = value;
                }
            }

            private int m_BrowserWidth;
            public int BrowserWidth
            {
                get
                {
                    return m_BrowserWidth;
                }
                set
                {
                    m_BrowserWidth = value;
                }
            }

            private int m_BrowserHeight;
            public int BrowserHeight
            {
                get
                {
                    return m_BrowserHeight;
                }
                set
                {
                    m_BrowserHeight = value;
                }
            }

            public Bitmap GenerateWebSiteThumbnailImage()
            {
                Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
                m_thread.SetApartmentState(ApartmentState.STA);
                m_thread.Start();
                m_thread.Join();
                return m_Bitmap;
            }

            private void _GenerateWebSiteThumbnailImage()
            {
                WebBrowser m_WebBrowser = new WebBrowser();
                m_WebBrowser.ScrollBarsEnabled = false;
                m_WebBrowser.Navigate(m_Url);
                m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
                while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
                    Application.DoEvents();
                m_WebBrowser.Dispose();
            }

            private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                WebBrowser m_WebBrowser = (WebBrowser)sender;
                m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight);
                m_WebBrowser.ScrollBarsEnabled = false;
                m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
                m_WebBrowser.BringToFront();
                m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
                m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero);
            }
        }
    }
}

Dec 5, 2012 at 8:32 AM

Alguém teria esse exemplo em C#, estou precisando muito.

Dec 5, 2012 at 10:42 AM

Estou precisando enviar boleto para email vias asp.net e c#, por favor.

Coordinator
Dec 5, 2012 at 11:54 AM

Oi Paulo,

tente traduzir o código online http://www.carlosag.net/tools/codetranslator/. O resultado é muito bom. Se tiver alguma alteração vai ser coisa simples.

Abraço,

Stiven

Apr 1, 2014 at 2:44 PM
Copie e colei seu fonte mais dá erro no
Dim b As Boleto = New Boleto(vencimento, 70.0, "06", "13104800205", c, New EspecieDocumento(237, 2))

Erro : muitos argumentos.

E outra dúvida é onde eu baixo a biblioteca ImagePDF procurei e não achei.
Sep 25, 2014 at 2:46 PM
Pessoal, usei a biblioteca TuesPechkin e funcionou muito bem!

Vale a pena dar uma conferida: https://github.com/tuespetre/TuesPechkin.
Dec 9, 2014 at 6:05 PM
Perai, seu código é completamente dependente de um Windows Forms, correto?

Isso funcionaria em ASP.net ?