2012-04-26 34 views
8

Estoy usando itextsharp dll para convertir HTML a PDF.Mostrar caracteres Unicode al convertir Html a Pdf

El HTML tiene algunos caracteres Unicode como α, β ... cuando trato de convertir HTML a PDF, los caracteres Unicode no se muestran en PDF.

Mi función:

Document doc = new Document(PageSize.LETTER); 

using (FileStream fs = new FileStream(Path.Combine("Test.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read)) 
{ 
    PdfWriter.GetInstance(doc, fs); 

    doc.Open(); 
    doc.NewPage(); 

    string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), 
             "ARIALUNI.TTF"); 

    BaseFont bf = BaseFont.CreateFont(arialuniTff, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); 

    Font fontNormal = new Font(bf, 12, Font.NORMAL); 

    List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), 
               new StyleSheet()); 
    Paragraph p = new Paragraph {Font = fontNormal}; 

    foreach (var element in list) 
    { 
     p.Add(element); 
     doc.Add(p); 
    } 

    doc.Close(); 
} 

Respuesta

10

Cuando se trata de caracteres Unicode y iTextSharp hay un par de cosas que hay que cuidar. El primero que ya hiciste y eso es obtener una fuente que admita tus personajes. Lo segundo es que realmente desea registrar la fuente con iTextSharp para que esté al tanto de esto.

//Path to our font 
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); 
//Register the font with iTextSharp 
iTextSharp.text.FontFactory.Register(arialuniTff); 

Ahora que tenemos una fuente que necesitamos para crear un objeto que le dice StyleSheet iTextSharp cuándo y cómo usarlo.

//Create a new stylesheet 
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet(); 
//Set the default body font to our registered font's internal name 
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS"); 

por una parte que no sea HTML que también hay que hacer es establecer un parámetro especial encoding. Esta codificación es específica de iTextSharp y en su caso desea que sea Identity-H. Si no configura esto, se configurará por defecto en Cp1252 (WINANSI).

//Set the default encoding to support Unicode characters 
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H); 

Por último, tenemos que pasar nuestra hoja de estilo a la ParseToList método:

//Parse our HTML using the stylesheet created above 
List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), ST); 

poner que todos juntos, de abierto a cerrar tendrías:

doc.Open(); 

//Sample HTML 
StringBuilder stringBuilder = new StringBuilder(); 
stringBuilder.Append(@"<p>This is a test: <strong>α,β</strong></p>"); 

//Path to our font 
string arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); 
//Register the font with iTextSharp 
iTextSharp.text.FontFactory.Register(arialuniTff); 

//Create a new stylesheet 
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet(); 
//Set the default body font to our registered font's internal name 
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.FACE, "Arial Unicode MS"); 
//Set the default encoding to support Unicode characters 
ST.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H); 

//Parse our HTML using the stylesheet created above 
List<IElement> list = HTMLWorker.ParseToList(new StringReader(stringBuilder.ToString()), ST); 

//Loop through each element, don't bother wrapping in P tags 
foreach (var element in list) { 
    doc.Add(element); 
} 

doc.Close(); 

EDITAR

En tu comentario demuestras HTML que especifica una fuente de anulación. iTextSharp no araña el sistema de fuentes y su analizador HTML no utiliza técnicas de recuperación de fuentes. Cualquier fuente especificada en HTML/CSS debe registrarse manualmente.

string lucidaTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "l_10646.ttf"); 
iTextSharp.text.FontFactory.Register(lucidaTff); 
+0

Si el contenido HTML son como

α,β
la función anterior no funciona. –

16

También puede utilizar el nuevo XMLWorkerHelper (de la biblioteca itextsharp.xmlworker), es necesario sustituir la implementación predeterminada FontFactory sin embargo.

void GeneratePdfFromHtml() 
{ 
    const string outputFilename = @".\Files\report.pdf"; 
    const string inputFilename = @".\Files\report.html"; 

    using (var input = new FileStream(inputFilename, FileMode.Open)) 
    using (var output = new FileStream(outputFilename, FileMode.Create)) 
    { 
    CreatePdf(input, output); 
    } 
} 

void CreatePdf(Stream htmlInput, Stream pdfOutput) 
{ 
    using (var document = new Document(PageSize.A4, 30, 30, 30, 30)) 
    { 
    var writer = PdfWriter.GetInstance(document, pdfOutput); 
    var worker = XMLWorkerHelper.GetInstance(); 

    document.Open(); 
    worker.ParseXHtml(writer, document, htmlInput, null, Encoding.UTF8, new UnicodeFontFactory()); 

    document.Close(); 
    }  
} 

public class UnicodeFontFactory : FontFactoryImp 
{ 
    private static readonly string FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), 
     "arialuni.ttf"); 

    private readonly BaseFont _baseFont; 

    public UnicodeFontFactory() 
    { 
     _baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); 

    } 

    public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, 
     bool cached) 
    { 
     return new Font(_baseFont, size, style, color); 
    } 
} 
+0

Gracias, hombre, pero el resultado que obtengo, las letras están separadas entre sí. muestra ت ت ت como ت ت –

+0

Lo intenté pero todavía no hice la palabra en chino. –

+0

después de actualizar a 5.5.5 y usar el frente de Microsoft Yasei, funciona correctamente ahora. –

-1

Aquí es los pocos pasos para mostrar los caracteres Unicode en la conversión de HTML a PDF

  1. Crear una HTMLWorker
  2. Register una fuente Unicode y asignarle
  3. crear una hoja de estilo y establecer la codificación en Identity-H
  4. Asignar la hoja de estilos al analizador html

Consulte el enlace a continuación para obtener más información ....

hindi, turco y caracteres especiales también son exhibición durante la conversión de HTML a PDF utilizando este método. Verifique debajo de la imagen de demostración.

enter image description here

+0

[Se recomiendan enlaces a recursos externos, pero agregue contexto alrededor del enlace para que los demás usuarios tengan una idea de qué es y por qué está allí. Siempre cite la parte más relevante de un enlace importante, en caso de que el sitio objetivo no esté disponible o permanezca desconectado permanentemente.] (Http://stackoverflow.com/help/how-to-answer) –