With export HTML string to PDF Compressed (zip)

Asked

Viewed 375 times

2

I have this string: <HTML><HEAD></HEAD><body><FORM method="post"><table><tr><td>Nome:</td><td>JOÃO DA SILVA</td></tr><tr><td>NOME:</td><td>MARCOS ALVES</td></tr></table></BODY></HTML> saved in a table and need through the click of the button export to pdf now compressed (.zip.), using some api free. It is possible ?

I implemented the great response from George Wurthmann below, but as commented on the project available in Github as example generates PDF displaying HTML tags, I believe it is some detail in the code: inserir a descrição da imagem aqui

And here I adapted the code according to my needs, changing the string containing HTML table fixed in the code to a return of a database table:

[HttpPost]
        public ActionResult GetPdfFileZiped(ProcessamentoRegistros pProcessamentoRegistros)
        {
            pProcessamentoRegistros.IdProcessamentoDiario = 1;
            pProcessamentoRegistros.IdRegistro = 1;
            pProcessamentoRegistros.IdServico = 2;
            ProcessamentoRegistros _processamento = _IRepositorio.ObterProcessamentoRegistros(pProcessamentoRegistros);

            var doc = new Document(PageSize.A4.Rotate());
            var stream = new MemoryStream();
            var pw = PdfWriter.GetInstance(doc, stream);
            var minhaStringHTML = _processamento.DocumentoHtml;    // @"<HTML><HEAD></HEAD><body><FORM method='post'><table><tr><td></td></tr></table></BODY></HTML>";

            doc.Open();
            Paragraph paragrafo = new Paragraph(minhaStringHTML, new Font(Font.NORMAL, 12));
            paragrafo.Alignment = Element.ALIGN_LEFT;
            doc.Add(paragrafo);
            doc.Close();

            using (var compressedFileStream = new MemoryStream())
            {
                //Cria um arquivo ZIP
                using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
                {
                    //Criar a entrada do PDF para o arquivo ZIP
                    var zipEntry = zipArchive.CreateEntry("MeuPDFZipado.pdf");

                    //Pegando o stream do PDF em memória
                    using (var originalFileStream = new MemoryStream(stream.ToArray()))
                    {
                        using (var zipEntryStream = zipEntry.Open())
                        {
                            //Copia o stream do PDF para o ZIP
                            originalFileStream.CopyTo(zipEntryStream);
                        }
                    }
                }
                return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
            }
        }

This is table HTML:

<HTML>

<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<script language=javascript>
//function MudarPagina() {
//  window.history.back();
//}
</script>
</HEAD>
<!--body bgcolor=white onBlur=MudarPagina();-->
<body bgcolor=white>
    <FORM method="post" style="BACKGROUND-COLOR: white">
    <!--FORM name="Imprimir" method="post" style="BACKGROUND-COLOR: white"-->
<br>    
<table>
<tr>
<td align=center><a href="javascript:window.print();"><IMG src="https://www.sifge.caixa.gov.br/Empresa/Crf/images/botimprimir.gif" border=0></a>
<a href="javascript:window.history.back();"><IMG src="https://www.sifge.caixa.gov.br/Empresa/Crf/images/botvoltar.gif" border=0></a></td>
</tr>

<tr><td>

<table width="75%" CELLSPACING=0 CELLPADDING=10 border=1 align=center bordercolorlight="#FFFFFF" bordercolordark="#CCCCCC">


<tr>
<td>    

    <TABLE WIDTH=100% BORDER=0 CELLSPACING=0 CELLPADDING=0 style="color: black" class=txtcentral>
        <tr>
            <td align=left><IMG border="0" src="https://www.sifge.caixa.gov.br/Empresa/Crf/images/caixa.gif" width=180 height=44></td>
        </tr>

        <tr><td colspan=2>&nbsp</td></tr>

        <tr>
            <td align=rigth><span style="font-size: 13pt" align=center><strong>Certificado de Regularidade do FGTS - CRF</strong></span></td>
        </tr>
    </table>

    <TABLE WIDTH=100% BORDER=0 CELLSPACING=0 CELLPADDING=0 style="color: black" class=txtcentral>

        <tr><td colspan=2>&nbsp</td></tr>
        <tr><td colspan=2>&nbsp</td></tr>

        <tr>
            <TD width=22%><font style=" font-family: Verdana;font-size:10pt"><strong>Inscrição:</strong></font></TD>
            <TD ><font style=" font-family: Verdana;font-size:8pt">08439659/0001-50</font></TD>
        </tr>
        <tr>
            <td width=22% valign=top nowrap><font style=" font-family: Verdana;font-size:10pt"><strong>Razão Social:</strong></font></TD>
            <td><font style=" font-family: Verdana;font-size:8pt">CPFL ENERGIAS RENOVAVEIS S A</font></TD>
        </tr>

        <tr>
            <td width=22% nowrap><font style=" font-family: Verdana;font-size:10pt"><strong>Nome Fantasia:</strong></font></TD>
            <td ><font style=" font-family: Verdana;font-size:8pt">CPFL RENOVAVEIS</font></TD>
        </tr>

        <tr>
            <td width=22% valign=top><font style=" font-family: Verdana;font-size:10pt"><strong>Endereço:</strong></font></TD>
            <td ><font style=" font-family: Verdana;font-size:8pt">AV DOUTOR CARDOSO DE MELO   1184   ANDAR 7 / VILA OLIMPIA / SAO PAULO / SP / 4548-004</font></TD>
        </tr>

        <tr><td colspan=2>&nbsp</td></tr>
        <tr><td colspan=2>&nbsp</td></tr>

        <tr>
            <TD colspan=2 style="text-align: justify"><font style=" font-family: Verdana;font-size:10pt">A Caixa Econômica Federal, no uso da atribuição que lhe confere o Art. 7, da
            Lei 8.036, de 11 de maio de 1990, certifica que, nesta data, a empresa acima identificada
            encontra-se em situação regular perante o Fundo de Garantia do Tempo de Serviço - FGTS.
            </font>
            </TD>
        </tr>

        <tr><td colspan=2>&nbsp</td></tr>
        <tr><td colspan=2>&nbsp</td></tr>

        <tr>
            <td style="text-align: justify" colspan=2><font style=" font-family: Verdana;font-size:10pt">O presente Certificado não servirá de prova contra cobrança de quaisquer débitos referentes
            a contribuições e/ou encargos devidos, decorrentes das obrigações com o FGTS.</font>
            </td>
        </tr>

        <tr><td colspan=2>&nbsp</td></tr>
        <tr><td colspan=2>&nbsp</td></tr>


        <tr>
            <td colspan=2><font style=" font-family: Verdana;font-size:10pt"><strong>Validade: </strong>28/02/2017 a 29/03/2017</font></TD>
        </tr>
        <tr><td colspan=2>&nbsp</td></tr>

        <tr>
            <td colspan=2><font style=" font-family: Verdana;font-size:10pt"><strong>Certificação Número: </strong>2017022805233090232330</font></TD></TR>

        <tr><td colspan=2>&nbsp</td></tr>
        <tr><td colspan=2>&nbsp</td></tr>

        <tr>
            <TD colspan=2><font style=" font-family: Verdana;font-size:10pt">Informação obtida em 15/03/2017, às 17:14:51.</font></TD>
        </tr>

        <tr><td colspan=2>&nbsp</td></tr>
        <tr><td colspan=2>&nbsp</td></tr>

        <tr>
            <TD style="text-align: justify" colspan=2><font style=" font-family: Verdana;font-size:10pt">A utilização deste Certificado
                para os fins previstos em Lei está condicionada à verificação de
                autenticidade no site da Caixa: <strong>www.caixa.gov.br</strong></font></TD>
            </tr>
    </TABLE>
</form>

</td></tr></table>

</td>
</tr>

</table> 

<script language=javascript>
//window.print();
</script>   
</BODY>
</HTML>
  • I edited the question. I put the link to this working on Github.

  • @George Wurthmann downloaded the project from Github and the generated pdf shows the html tags for the user and this makes no sense I will edit the question and add the pdf print.

  • I just saw your issue. In _processamento.DocumentoHtml has all its string HTML?

  • 1

    I edited the answer and updated the project in Git with what you need. I edited the query because your HTML string was missing <FORM> and this caused error when trying to convert.

1 answer

2


The PDF you can generate with the iTextSharp, is quite simple.

The Zip can be generated natively by C# with the System.IO.Compression.

So you’re gonna need referral:

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.IO.Compression;

See in this example how to use:

namespace Exemplo_PDF_e_ZIP.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }


        [HttpPost]
        public ActionResult GetPdfFile()
        {
            var doc = new Document(PageSize.A4.Rotate());
            var stream = new MemoryStream();
            var pw = PdfWriter.GetInstance(doc, stream);
            var minhaStringHTML = @"<HTML><HEAD></HEAD><body><FORM method='post'><table><tr><td>Nome:</td><td>JOÃO DA SILVA</td></tr><tr><td>NOME:</td><td>MARCOS ALVES</td></tr></table></FORM></BODY></HTML>";

            doc.Open();
            using (var srHtml = new StringReader(minhaStringHTML))
            {
                //Convertendo o HTML
                XMLWorkerHelper.GetInstance().ParseXHtml(pw, doc, srHtml);
            }
            doc.Close();

            return File(stream.ToArray(), "application/pdf", "result.pdf");
        }

        [HttpPost]
        public ActionResult GetPdfFileZiped()
        {
            var doc = new Document(PageSize.A4.Rotate());
            var stream = new MemoryStream();
            var pw = PdfWriter.GetInstance(doc, stream);
            var minhaStringHTML = @"<HTML><HEAD></HEAD><body><FORM method='post'><table><tr><td>Nome:</td><td>JOÃO DA SILVA</td></tr><tr><td>NOME:</td><td>MARCOS ALVES</td></tr></table></FORM></BODY></HTML>";

            doc.Open();
            using (var srHtml = new StringReader(minhaStringHTML))
            {
                //Convertendo o HTML
                XMLWorkerHelper.GetInstance().ParseXHtml(pw, doc, srHtml);
            }
            doc.Close();

            using (var compressedFileStream = new MemoryStream())
            {
                //Cria um arquivo ZIP
                using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
                {
                    //Criar a entrada do PDF para o arquivo ZIP
                    var zipEntry = zipArchive.CreateEntry("MeuPDFZipado.pdf");

                    //Pegando o stream do PDF em memória
                    using (var originalFileStream = new MemoryStream(stream.ToArray()))
                    {
                        using (var zipEntryStream = zipEntry.Open())
                        {
                            //Copia o stream do PDF para o ZIP
                            originalFileStream.CopyTo(zipEntryStream);
                        }
                    }
                }
                return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
            }
        }
    }
}

After the edits in the question, you informed that you do not want to print the tags but the content of HTML. For that I used the XMLWorker of iTextSharp.

You will need to install it too:

PM> Install-Package itextsharp.xmlworker

Besides the namespaces I informed above use also:

using iTextSharp.tool.xml;

I put the project on Github. So you can download to use example and see working.

  • Hello @George Wurthmann very good your reply, well didactic, but the PDF displays exactly one String, what I want is to display the data that will come in this HTML, I will edit the question to explain mellhor.

  • @Adrianosuv, you want to export the table, is that it? The way it is on HTML stay in the PDF? If this is necessary more details, because I do not know how is being generated your HTML, I imagine through a View already that you are using MVC, then you need to post details of it too.

  • I don’t want to display HTML tags, content only, example: Name: MARCOS SILVA i edited the question and adicinei a generated pdf print.

  • @Adrianosuv, I understand what you mean, but as I explained before, I need to know how your table is being generated. In my code I put the string in a variable manually, because it gives to understand in your question that you already have the string you want to print.

  • is solved as the previous comments posted in the question Post, but after all the work I’ve had I see that iTextSharp does not generate Styles in pdf ? Correct ?

  • @Adrianosuv, CSS? It’s not included since it didn’t have anything in the example tag, but it’s possible with Xmlworker. Search about iTextSharp Cssresolverpipeline.

  • Correct @George Wurthmann, had not commented on the CSS.

  • I do not know if it is the case to open another post, I tried to generate several files zip within a foreach unsuccessful due to the return new FileContentResult, has as generate more than one file zip within a foreach ?

  • @Adrianosuv, in Actionresult’s Return only one can be returned. If you want to return multiple PDF’s, why not generate the Pdfs in foreach and then Zip them into a single file? It makes no sense to generate multiple zips, generates only 1 and inside it put all the files you need.

  • I’m doing this and I’m catching a lot kkkk, I implemented the generation inside a foreach but always returns the last pdf, I mean I can’t make the increment of the files rs

  • @Adrianosuv, if you can’t open a question with your doubt that I or someone else is trying to help you.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.