2011-03-16 53 views
10

Estoy usando iTextSharp para convertir una página HTML a PDF. Estoy haciendo uso de la clase de ayuda dada here y también he intentado hacer uso de StyleSheet.LoadTagStyle() para aplicar CSS. Pero nada parece funcionar. ¿Alguna idea?itextsharp - CSS no se aplica - C# .NET

EDITAR

soy capaz de añadir estilos como esto -

.mystyle 
{ 
    color: red; 
    width: 400px; 
} 

Con el siguiente código -

StyleSheet css = new StyleSheet(); 
css.LoadStyle("mystyle", "color", "red"); 
css.LoadStyle("mystyle", "width", "400px"); 

¿Pero qué sucede cuando he estilos complejos como ¿esta?

div .myclass 
{ 
    /*some styles*/ 
} 

td a.hover 
{ 
    /*some styles*/ 
} 

td .myclass2 
{ 
    /*some styles*/ 
}  
.myclass .myinnerclass 
{ 
    /*some styles*/ 
} 

¿Cómo agregarlo usando iTextSharp?

+0

Hola, también estoy atascado en el mismo problema, cuando uso LoadTagStyle funciona perfectamente, también puedo hacer que funcione para "LoadStyle()" cuando uso solo el atributo "color". Sin embargo, no parece funcionar cuando estoy tratando de usar los atributos "font-color" o "font-size". Cualquier ejemplo en el que podamos convertir css classes –

+4

Utilice [https://github.com/webgio/Rotativa](https://github.com/webgio/Rotativa], puede instalarlo a través de nuget. Funciona con wkhtmltopdf que utiliza el motor de webkit para representar el html/css. ¡Es impresionante! ** Es compatible con html/css. ** –

+1

Gracias a @Preben Huybrechts si lo pones en una respuesta, lo votaré, esto en realidad es mejor que retocarlo con ITextSharp. –

Respuesta

14

Estás en el camino correcto con el uso de StyleSheet.LoadTagStyle().

Básicamente se trata de un proceso de cuatro pasos:

  1. obtener el código HTML de una cadena
  2. una instancia de un objeto StyleSheet y llamar StyleSheet.LoadTagStyle() para cada estilo que desee.
  3. llamada HTMLWorker.ParseToList()
  4. agregue el IElement (s) devuelto desde la llamada anterior al objeto de documento.

aquí es un simple HTTP handler:

<%@ WebHandler Language='C#' Class='styles' %> 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Text; 
using System.Web; 
using iTextSharp.text.html; 
using iTextSharp.text.html.simpleparser; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

public class styles : IHttpHandler { 
    public void ProcessRequest (HttpContext context) { 
    HttpResponse Response = context.Response; 
    Response.ContentType = "application/pdf"; 
    string Html = @" 
<h1>h1</h1> 
<p>A paragraph</p>  
<ul> 
<li>one</li> 
<li>two</li> 
<li>three</li> 
</ul>"; 
    StyleSheet styles = new StyleSheet(); 
    styles.LoadTagStyle(HtmlTags.H1, HtmlTags.FONTSIZE, "16"); 
    styles.LoadTagStyle(HtmlTags.P, HtmlTags.FONTSIZE, "10"); 
    styles.LoadTagStyle(HtmlTags.P, HtmlTags.COLOR, "#ff0000"); 
    styles.LoadTagStyle(HtmlTags.UL, HtmlTags.INDENT, "10"); 
    styles.LoadTagStyle(HtmlTags.LI, HtmlTags.LEADING, "16"); 
    using (Document document = new Document()) { 
     PdfWriter.GetInstance(document, Response.OutputStream); 
     document.Open(); 
     List<IElement> objects = HTMLWorker.ParseToList(
     new StringReader(Html), styles 
    ); 
     foreach (IElement element in objects) { 
     document.Add(element); 
     } 
    } 
} 
    public bool IsReusable { 
     get { return false; } 
    } 
} 

se necesita la versión 5.0.6 para ejecutar el código de seguridad. soporte para analizar HTML ha sido mejorado en gran medida.

si quiere ver qué etiquetas son compatibles con la versión actual, consulte el SVN for the HtmlTags class.

+1

He editado mi pregunta. Revisalo. – NLV

+0

Creo que también hizo esta pregunta en la [lista de correo] (http://www.mail-archive.com/[email protected]/msg55976.html)? como se señaló, tendrá que esperar un tiempo o ponerse en contacto con su equipo de consultoría. – kuujinbo

3
var reader = new StringReader(text); 
var styles = new StyleSheet(); 
styles.LoadTagStyle("body", "face", "Arial"); 
styles.LoadTagStyle("body", "size", fontSize + "px"); 
styles.LoadTagStyle("body", "font-weight", "bold"); 

ArrayList list = HTMLWorker.ParseToList(reader, styles); 
for (int k = 0; k < list.Count; k++) 
{ 

    var element = (IElement)list[k]; 

    if (element is Paragraph) 
    { 
    var paragraph = (Paragraph)element; 
    paragraph.SpacingAfter = 10f; 
    cell.AddElement(paragraph); 
    } 
else 
    cell.AddElement((IElement)list[k]); 
} 
+0

He editado mi pregunta. Revisalo. – NLV

Cuestiones relacionadas