* XMLWorker [#b004f80a]
** 概要 [#oa7bf0e6]
- HTMLのParseHtml()は上手く動かない事がある?
Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.Paragraph'.
- HTMLWorkerはすでにdeprecatedなので、XMLWorkerを使う。
** コード [#sdcae9d3]
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using System.IO;
public class HtmlToPdf
{
private const string JapaneseFontName = "c:\\windows\\fonts\\msmincho.ttc,0";
public static byte[] ConvertHtmlToPdf(string html)
{
MemoryStream output = new MemoryStream();
using (var document = new Document(PageSize.A4, 30, 30, 30, 30))
using (var writer = PdfWriter.GetInstance(document, output))
{
document.Open();
var fontname = JapaneseFontName;
var fontProvider = new XMLWorkerFontProvider();
fontProvider.Register(fontname, "Serif");
var cssText = @"body {font-family: Serif;}";
using (var cssMS = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
using (var htmlMS = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
{
var xmlWorker = XMLWorkerHelper.GetInstance();
xmlWorker.ParseXHtml(writer, document, htmlMS, cssMS, System.Text.Encoding.UTF8, fontProvider);
}
document.Close();
}
return output.ToArray();
}
}
** 参考 [#f2e53114]
- http://sourceforge.net/projects/itextsharp/files/xmlworker/
- http://stackoverflow.com/questions/21106710/applying-style-to-div-having-a-class-name-itextsharp/21165654#21165654
- http://stackoverflow.com/questions/16101481/use-external-css-to-parse-xml/16105368#16105368
- http://stackoverflow.com/questions/15354005/html-to-list-using-xmlworker/15362705#15362705
- http://stackoverflow.com/questions/12113425/itextsharp-error-on-trying-to-parse-html-for-pdf-conversion