Стиль не применяется при преобразовании строки HTML в pdf itextSharp - PullRequest
0 голосов
/ 27 февраля 2019

Ниже приведен код, из которого я пытаюсь сгенерировать 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();

    }
}

Стиль не применяется при преобразовании строки HTML в PDF с использованием построителя строк. Он показывает без стиля. Является ли синтаксис правильнымдля применения стиля?Или мне нужно подходить к другой технике для создания PDF со стилем реализации?

1 Ответ

0 голосов
/ 05 марта 2019

Что я сделал, так это то, что я создал другой файл 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 ....

...