将HTML字符串转换为pdf itext时未应用样式

时间:2019-02-27 10:04:10

标签: c# css asp.net itext pdfhtml

下面是我尝试从中生成pdf的代码。   附加HTML字符串并转换为Pdf, Pdf正在生成,但样式未应用。

protected void Demo()
{

    StringBuilder sb = new StringBuilder();
    sb.Append("<header class='clearfix'>");
    sb.Append("<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\">");
    sb.Append("<tbody>");
    sb.Append("<tr>");
    sb.Append("<td  style=\"height:47px; width:175px;\">");
    sb.Append("<p>");
    sb.Append(" <style=\"width:205px; height:35px;\"></p>");
    sb.Append("</td>");
    sb.Append("<td colspan=\"4\" style=\"height:47px; width:553px;  background:#0d4580; color:aliceblue;\">");
    sb.Append("<p style='margin-left:76.45pt'><strong>JOB DESCRIPTION</strong ></p>");
    sb.Append("</td>");
    sb.Append("</tr>");
    sb.Append("<tr>");
    sb.Append("<td colspan='5' style='height:19px; width:729px;'>");
    sb.Append("<p> &nbsp;</p>");
    sb.Append("</td>");
    sb.Append("</tr>");
    sb.Append("<tr>");
    sb.Append("<td colspan='2' style=\"height:38px; width:182px; background: #0d4580;color: aliceblue;\" >");
    sb.Append("<p style=\"margin-left:5.35pt\" ><strong> Job Title / Role:</ strong ></p>");
    sb.Append("</td>");
    sb.Append("<td colspan='3' style='height:38px; width:547px;' >");
    sb.Append("<p style='margin-left:5.3pt' > Quality Assurance Executive</ p >");
    sb.Append("</td>");
    sb.Append("</tr>");
    sb.Append("<tr>");
    sb.Append("<td colspan='2' style='height:38px; width:182px; background: #0d4580;color: aliceblue;' >");
    sb.Append("<p style='margin-left:5.35pt' ><strong> Department:</ strong ></p>");
    sb.Append("</td>");
    sb.Append("<td style='height:38px; width:215px' >");
    sb.Append("<p style='margin-left:5.3pt' > Training & amp; Quality </ p >");
    sb.Append("</td>");
    sb.Append("<td style='height:38px; width:120px; background: #0d4580;color: aliceblue;' >");
    sb.Append("<p style='margin-left:5.3pt' >< strong > Shift Timings:</strong ></p>");
    sb.Append("</td>");
    sb.Append("<td style='height:38px; width:211px' >");
    sb.Append("<p style='margin-left:5.3pt' > Flexible(7AM & ndash; 10PM)</p>");
    sb.Append("</td>");
    sb.Append("</tr>");
    sb.Append("<tr>");
    sb.Append("<td colspan = '2' style = 'height:39px; width:182px; background: #0d4580;color: aliceblue;' >");
    sb.Append("<p style = 'margin-left:5.35pt'><strong> Reporting To:</strong></p>");
    sb.Append("</ td >");
    sb.Append("<td style = 'height:39px; width:215px' >");
    sb.Append("<p style ='margin-left:5.3pt' > AM & ndash; Quality </p>");
    sb.Append("</td >");
    sb.Append("<td style='height:39px;     width: 128px;     background:#0d4580;color:aliceblue;' >");
    sb.Append("<p style='margin-left:5.3pt'><strong> No.of position:</strong></p>");
    sb.Append("</td >");
    sb.Append("<td style='height:39px; width:211px' >");
    sb.Append("<p style='margin-left:5.3pt' > 01(One) </p>");
    sb.Append("</td >");
    sb.Append("</tr>");
    sb.Append("<tr>");
    sb.Append("<td colspan='2' style='height:38px; width:182px;  background: #0d4580;color: aliceblue;' >");
    sb.Append("<p style='margin-left:5.35pt' >< strong > Work Location:</ strong ></p >");
    sb.Append("</td>");
    sb.Append("<td style='height:38px; width:215px' >");
    sb.Append(" <p style='margin-left:5.3pt' > Bhayander, Mumbai </p>");
    sb.Append("</td>");
    sb.Append("<td style ='height:38px; width:120px;  background: #0d4580;color: aliceblue;' >");
    sb.Append("<p style ='margin-left:5.3pt' ><strong> Level / Grade:</strong></p>");
    sb.Append("</td>");
    sb.Append("<td style='height:38px; width:211px' >");
    sb.Append("<p style='margin-left:5.3pt' > 5 </ p >");
    sb.Append("</td>");
    sb.Append("</tr>");
    sb.Append("<tr>");
    sb.Append("</tr>");
    sb.Append("</tbody>");
    sb.Append("</table>");

    //string strOutput = sb.ToString();
    //StringReader reader = new StringReader(strOutput);

    StringReader sr = new StringReader(sb.ToString());

    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    using (MemoryStream memoryStream = new MemoryStream())
    {

        //HtmlConverter.ConvertToPdf(sb.ToString(), memoryStream);

        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
        pdfDoc.Open();

        htmlparser.Parse(sr);
        pdfDoc.Close();

        byte[] bytes = memoryStream.ToArray();
        HtmlConverter.ConvertToPdf(sb.ToString(), memoryStream);
        memoryStream.Close();
        Response.Clear();

        Response.ContentType = "application/pdf";

        Response.AddHeader("Content-Disposition", "attachment; filename=Invoice.pdf");

        Response.Buffer = true;

        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        Response.BinaryWrite(bytes);

        Response.End();

        Response.Close();

    }
}

使用字符串生成器将Htmlstring转换为PDF时不应用样式, 它显示没有样式,语法是否适合应用样式? 还是我需要使用其他技术来使用样式工具生成pdf?

1 个答案:

答案 0 :(得分:0)

我所做的是我创建了不同的CSS文件并使用了Itextsharp Xmlworker

protected void Demo(int Id)
            {
                CareerDetails Sql = new CareerDetails();
                string imageURL = Server.MapPath("~") + "/Images/epicenter_logo.gif";
                StringBuilder sb = new StringBuilder();
                sb.Append("<header class='clearfix'>");
                sb.Append("<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\" class='Header'>");
                sb.Append("<tbody>");
                sb.Append("<tr>");
                sb.Append("<td  class='td1'>");
                sb.Append("<img src='"+ imageURL +"' class='p3'/>");
                sb.Append("</td>");
                sb.Append("<td colspan=\"4\"class='td2'>");
                DataSet ds = new DataSet();
                SqlParameter[] sqlParam = new SqlParameter[1];
                sqlParam[0] = new SqlParameter("@Id", SqlDbType.Int);
                sqlParam[0].Value = Id;


            ds = Sql.GetDatawithPara("EPC_GeneratePdf", sqlParam);

            if (ds.Tables[0].Rows.Count > 0)
            {
                sb.Append("<p class='p1'><strong>JOB DESCRIPTION</strong ></p>");
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("<tr>");
                sb.Append("<td colspan='5'>");
                sb.Append("<p> &nbsp;</p>");
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("<tr>");
                sb.Append("<td colspan='2' class='td3' >");
                sb.Append("<p style=\"margin-left:5.35pt\" ><strong> Job Title / Role:</ strong ></p>");
                sb.Append("</td>");
                sb.Append("<td colspan='3' style='height:38px; width:547px;' >");
                sb.Append("<p class='p2' > " + ds.Tables[0].Rows[0]["RoleName"].ToString() + "</p >");
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("<tr>");
                sb.Append("<td colspan='2'class='td3' >");
                sb.Append("<p style='margin-left:5.35pt' ><strong> Department:</ strong ></p>");
                sb.Append("</td>");
                sb.Append("<td class='td1'>");
                sb.Append("<p class='p2' >" + ds.Tables[0].Rows[0]["DepartmentName"].ToString() + " </ p >");
                sb.Append("</td>");
                sb.Append("<td class='td3' >");
                sb.Append("<p class='p2'><strong> Shift Timings:</strong ></p>");
                sb.Append("</td>");
                sb.Append("<td class='auto-style1' >");
                sb.Append("<p class='p2'>" + ds.Tables[0].Rows[0]["Shift"].ToString() + "</p>");
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("<td class='td3' >");
                sb.Append("<p class='p2'><strong> No.of position:</strong></p>");
                sb.Append("</td >");
                sb.Append("<td class='auto-style1'> ");
                sb.Append("<p class='p2' >" + ds.Tables[0].Rows[0]["NoofPost"].ToString() + "</p>");
                sb.Append("</td >");
                sb.Append("</tr>");
                sb.Append("<tr>");                                            
                sb.Append("</td>");
                sb.Append("</tr>");
                sb.Append("<tr>");
                sb.Append("<td colspan='5' style='height:19px;'>");
                sb.Append("<p> &nbsp;</p>");
                sb.Append("</td>");                           
               sb.Append("</tr>");
                sb.Append("</tbody>");
                sb.Append("</table>"); 

};                                                                                                                                                                                               /

在这里,我已经将css文件附加到我的方法中

            List<string> cssFiles = new List<string>();
            cssFiles.Add(@"~/css/PdfDesign.css");
            //StringReader sr = new StringReader(sb.ToString());

            Document pdfDoc = new Document(PageSize.A4);
            //HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

            using (MemoryStream memoryStream = new MemoryStream())
            {


                //HtmlConverter.ConvertToPdf(sb.ToString(), memoryStream);

                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
                writer.CloseStream = false;
                pdfDoc.Open();
                HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
                htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
                var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                tagProcessors.RemoveProcessor(HTML.Tag.IMG); // remove the default processor
              //  tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor().End()); // use our new processor

                var hpc = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors
                //Create a cssresolver to apply css
                ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
                cssFiles.ForEach(i => cssResolver.AddCssFile(System.Web.HttpContext.Current.Server.MapPath(i), true));


                //Create and attach pipeline, without pipeline parser will not work on css
                IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer)));



                //create XMLWork and attach a praser to it



                XMLWorker worker = new XMLWorker(pipeline, true);
                XMLParser xmlParser = new XMLParser(worker);
                xmlParser.Parse(new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())));

                pdfDoc.Close();

                memoryStream.Position = 0;


                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Disposition", "inline; filename=myfile.pdf");
                Response.BinaryWrite(memoryStream.ToArray());

                Response.Flush();

                Response.End();

            }

        }

现在我的样式正在PDF中应用。...