CSS样式未使用iTextSharp应用于PDF

时间:2013-08-08 17:11:31

标签: c# pdf-generation itextsharp

我正在尝试使用iTextSharp将我的网页的一部分转换为pdf,虽然pdf生成工作正常,但没有应用任何css样式。我尝试过一次一个地应用这些样式,但这似乎不起作用。这是我到目前为止所提出的:

//Get the portion of the page to convert.
StringBuilder sb = new StringBuilder();
print_div.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
string html = sb.ToString();

//Generate a random filename to use for the pdf
Guid random_guid;
random_guid = Guid.NewGuid();
string fileName = random_guid.ToString() + ".pdf";
string filename_with_folder = @"pdf\sl_" + fileName;
string fullFilePath = System.IO.Path.Combine(Request.PhysicalApplicationPath, filename_with_folder);

using (Document doc = new Document())
{
    // Create the pdf
    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
    doc.Open();
    try
    {
        //Set the font size for all elements
        StyleSheet styles = new StyleSheet();
        styles.LoadStyle("body", "fontsize", "8px");

        //Write the content to the pdf document
        StringReader sr = new StringReader(html);
        XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
    }
    catch (Exception ex)
    {
    }
    doc.Close();
}

我错过了什么吗?我开始使用HTMLWorker并已切换到XMLWorker,但我想我现在只是困惑自己。帮助将不胜感激。

ATTEMP#2

感谢您的回复!这就是我想出来的,但它没有用。我的内容现在根本没有出现在pdf中,我不知道为什么。有什么想法吗?

using (Document doc = new Document())
{
    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
    doc.Open();

    // CSS
    var cssResolver = new StyleAttrCSSResolver();
    var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("~/css/print.css"), FileMode.Open));
    cssResolver.AddCss(cssFile);

    // HTML
    CssAppliers ca = new CssAppliersImpl();
    HtmlPipelineContext hpc = new HtmlPipelineContext(ca);
    hpc.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

    // PIPELINES
    PdfWriterPipeline pdf = new PdfWriterPipeline(doc, writer);
    HtmlPipeline htmlPipe = new HtmlPipeline(hpc, pdf);
    CssResolverPipeline css = new CssResolverPipeline(cssResolver, htmlPipe);

    XMLWorker worker = new XMLWorker(css, true);
    XMLParser p = new XMLParser(worker);
    StringReader sr = new StringReader(html);
    p.Parse(sr);
    doc.Close();
}

我是否接近,或者我完全错过了这一点?

3 个答案:

答案 0 :(得分:2)

为了使用样式表使用XmlWorker创建PDF文件,您可以尝试使用返回字节数组的示例代码。



        byte[] bytesArray = null;
        using (var ms = new MemoryStream())
        {
            using (var document = new Document())
            {
                using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
                {
                    document.Open();
                    using (var strReader = new StringReader(html))
                    {
                        //Set factories
                        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                        //Set css
                        ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                        cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath("~/Content/bootstrap.min.css"), true);
                        //Export
                        IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
                        var worker = new XMLWorker(pipeline, true);
                        var xmlParse = new XMLParser(true, worker);
                        xmlParse.Parse(strReader);
                        xmlParse.Flush();
                    }
                    document.Close();
                }
            }
            bytesArray = ms.ToArray();
        }
        return bytesArray;

答案 1 :(得分:0)

您可以使用CSSResolver

创建XmlWorker
var cssResolver = new StyleAttrCSSResolver();
//Change the path to your CSS file
var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("~/pdf.css"), FileMode.Open));
cssResolver.AddCss(cssFile);

然后创建HtmlPipeline并将其传递给CssResolverPipeline构造函数:

CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker); 
using (TextReader sr = new StringReader(html))
        {
            p.Parse(sr);
            document.Close();
        }
        //close your writer
        pdfwriter.Close();

答案 2 :(得分:0)

不确定您是否设法解决了这个问题,但我在问题“Cannot get CSS to work in iTextSharp (5.4.3) when making pdf”中没有应用相同的CSS样式问题。

基本上我发现样式表的某些部分正在应用(例如,表格单元格周围的边框),但其他部分没有(字体的颜色,任何不在PX中的大小)