Error while converting HTML to PDF

Asked

Viewed 1,102 times

2

I need to make a PDF from a page HTML, but while converting I get the following error:

Cannot convert an object of type 'iTextSharp.text.html.simpleparser.Tablewrapper' to type 'iTextSharp.text.Meta'.

Follows the code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PaginaQueSeraConvertida.aspx.cs" Inherits="converterHTMLparaPDF.PaginaQueSeraConvertida" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

  Exportação de ASPX para PDF

        <span id="export" runat="server"></span>


 </div>
    </form>
</body>
</html>
using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Text;



namespace converterHTMLparaPDF
{
    public partial class PaginaQueSeraConvertida : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            criatabela();
            ConverteAspx2Pdf();
        }

        private void criatabela()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<table width='95%' border='0'><tr><td width='8%' class='tblNormal' align='Right'>Protocolo:</td>");
            sb.Append("<td width='8%' class='tblNormal' align='Right'>Devedor:</td>");
            sb.Append("<td width='16%' class='tblNormal' align='Right'>CNPJ/CPF:</td>");
            sb.Append("</tr><tr>");
            sb.Append("<td class='tblNormal' align='Right'>Título:</td>");
            sb.Append("<td class='tblNormal' align='Right'>Apresentante:</td>");
            sb.Append("<td class='tblNormal' align='Right'>Data Vencimento:</td>");
            sb.Append("</tr><tr>");
            sb.Append("<td class='tblNormal' align='Right'>Valor:</td>");
            sb.Append("<td class='tblNormal' align='Right'>Saldo:</td>");
            sb.Append("<td class='tblNormal' align='Right'>Data apontamento:</td>");
            sb.Append("</tr><tr>");
            sb.Append("<td class='tblNormal' align='Right'>Livro:</td>");
            sb.Append("<td class='tblNormal' align='Right'>Folha:</td>");
            sb.Append("<td class='tblNormal' align='Right'>Data protesto:</td>");
            sb.Append("</tr><tr>");
            export.InnerHtml = sb.ToString();
        }


        private void ConverteAspx2Pdf()
        {

            string attachment = "inline; filename=ExportacaoAspx2Pdf.pdf";

            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/pdf";

            StringWriter stw = new StringWriter();
            HtmlTextWriter htextw = new HtmlTextWriter(stw);

            this.RenderControl(htextw);

            Document document = new Document();
            PdfWriter.GetInstance(document, Response.OutputStream);

            document.Open();

            StringReader str = new StringReader(stw.ToString());
            HTMLWorker htmlworker = new HTMLWorker(document);

            htmlworker.Parse(str);
            document.Close();
            Response.Write(document);
            Response.End();

        }
    }
}
  • Your application get to enter the Converteaspx2pdf method()

  • Yes! I put exactly what is in the application.

2 answers

2

`Htmlworker is deprecated the suggestion now is to use Xmlworker

Here is a simple example of how to use it:

StringReader html = new StringReader(@"
<div style='font-size: 18pt; font-weight: bold;'>
Mouser Electronics <br />Authorized Distributor</div><br /> <br />
<div style='font-size: 14pt;'>Click to View Pricing, Inventory, Delivery & Lifecycle Information:
</div>
<br />
<div>
<table>
<tr><td></td><td>
<a href='http://www.mouser.com/access/?pn=78211-009' 
style='color: Blue; font-size: 10pt; text-decoration: underline;'>78211-009</a></td></tr>
</table></div>    
");      
using (Document document = new Document()) {
  PdfWriter writer = PdfWriter.GetInstance(document, STREAM);
  document.Open();
  XMLWorkerHelper.GetInstance().ParseXHtml(
    writer, document, html
  );
}

One observation is that to use XMLWorker you need your HTML well formatted, all tags closed properly.

I hope I’ve helped.

  • This component is not from Java?

  • There is also it for c#, is this DLL that you reference in your code. Here is a good text on how to use. http://stackoverflow.com/questions/25164257/how-to-convert-html-to-pdf-using-itextsharp

  • Look at his code: iTextSharp.tool.xml.XMLWorkerHelper

  • He doesn’t recognize this namespace!

  • Do you have the latest version? https://www.nuget.org/packages/iTextSharp/

  • Yes I am. But in doubt I uninstalled and installed again and the error persists.

Show 2 more comments

1


Your HTML this missing the closing tag .

See below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

namespace WebApplication1tiraduvidas
{
    public partial class PaginaQueSeraConvertida : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            criatabela();
            ConverteAspx2Pdf();
        }

        private void criatabela()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<table width='95%' border='0'><tr><td width='8%' >Protocolo:</td>");
            sb.Append("<td width='8%' >Devedor:</td>");
            sb.Append("<td width='16%' >CNPJ/CPF:</td>");
            sb.Append("</tr><tr>");
            sb.Append("<td>Título:</td>");
            sb.Append("<td >Apresentante:</td>");
            sb.Append("<td >Data Vencimento:</td>");
            sb.Append("</tr><tr>");
            sb.Append("<td >Valor:</td>");
            sb.Append("<td >Saldo:</td>");
            sb.Append("<td >Data apontamento:</td>");
            sb.Append("</tr><tr>");
            sb.Append("<td >Livro:</td>");
            sb.Append("<td >Folha:</td>");
            sb.Append("<td >Data protesto:</td>");
            sb.Append("</tr></table>");
            Principal.InnerHtml = sb.ToString();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
        }

        private void ConverteAspx2Pdf()
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            this.Page.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
    }
}

Also use the method:

public override void VerifyRenderingInServerForm(Control control)
            {
            }

and in aspx

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="PaginaQueSeraConvertida.aspx.cs"
  Inherits="WebApplication1tiraduvidas.PaginaQueSeraConvertida" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div id="Principal" runat="server">
    Exportação de ASPX para PDF
  </div>
  </form>
</body>
</html>
  • Excellent example. Now I just need to center the content in the middle of the page. Because when creating the PDF it does not reduce to fit the page

  • Good ai vc will have to use a little css , in case you need to change the pdf even vc can change the line Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); decreasing the document margins .

  • Is there any way to save this generated file inside the server? Without the need to open it for the client and without opening the download window?

  • Yes... See link [http://stackoverflow.com/questions/31078442/how-to-save-pdf-on-server-map-path-using-itextsharp]

Browser other questions tagged

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