How to set the cell width in itextsharp pdf creati

2019-08-31 18:11发布

问题:

Here im try to set a table cell width using itextsharp pdf creation but im facing trouble to make it since im using html table as string

my code:

  public ActionResult FormSixteen(EmployeeFormSixteenModel objEmployeeFormSixteenModel)
    {
        string htmlTable = string.Empty;
        htmlTable = htmlTable + "<table><tr><td>S.no</td><td>Head Name</td>Amount<td></td></tr><tr><td>1</td><td>Gross Salary</td>xxxx<td></td></tr></table>";
        Document document = new Document();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=" + objEmployeeFormSixteenModel.EmployeeName + ".pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        document.Open();

        iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
        iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
        htmlTable = htmlTable.ToString().Replace("'", "\"");
        htmlTable = htmlTable.Replace("px", "");
        StringReader sr = new StringReader(htmlTable.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();``
        htmlparser.Parse(sr);
        pdfDoc.Close();
        return View("FormSixteen", objEmployeeFormSixteenModel);
    }

What should I do?.. to set width i.e. S.no to decrease the width size , please help me.

回答1:

The basic answer to your question is that you just need to give some actual widths to your HTML.

htmlTable = @"<table>
               <tr>
                <td width=""25%"">S.no</td>
                <td width=""50%"">Head Name</td>
                <td width=""25%"">Amount</td>
               </tr>
               <tr>
                <td>1</td>
                <td>Gross Salary</td>
                <td>xxxx</td>
               </tr>
              </table>";

However your code has a bunch of other problems. First, you are using HTMLWorker which although it still exists it has been deprecated a long time ago in favor of XMLWorker. This is often done because of a dependency upon 4.1.6 which if you are using I strongly recommend you upgrade to 5.x. HTMLWorker handles almost zero CSS despite a class that looks like it might do it, however if you've got very basic HTML it works pretty good still. My code below assumes you've got the latest iTextSharp but I'm still using HTMLWorker since your HTML is very basic.

Second, you are making multiple instances of objects such as Document and HTMLWorker but aren't using all of them.

Third, your HTML has content between </td><td> in some places, however maybe that was just a transcription error.

Fourth, I strongly recommend NEVER writing directly to the Response.OutputStream. This can cause debugging problems if any exceptions are thrown, especially since iTextSharp is 100% unaware of ASP.Net so it can't handle any special cases. I also recommend not changing the HTTP headers until you are confident that you have something that represents a PDF for the same above reasons. (Its really fun when your exceptions start downloading with a PDF file name but are really HTML files!) Instead I recommend writing to a MemoryStream, grabbing the bytes and then doing something with them which my code does.

Lastly, and this isn't a problem exactly, but many of the main objects in iTextSharp 5.x support IDisposable so you are encouraged to use the using pattern on them.

Below shows the above off. I can't help you with the actual return View... part but I can get you a byte array that you should be able to do something with. In web form world we would normally do a Response.BinaryWrite(bytes); (with all of your HTTP header work, too).

//HTML Work
string htmlTable = @"<table>
                      <tr>
                       <td width=""25%"">S.no</td>
                       <td width=""50%"">Head Name</td>
                       <td width=""25%"">Amount</td>
                      </tr>
                      <tr>
                       <td>1</td>
                       <td>Gross Salary</td>
                       <td>xxxx</td>
                      </tr>
                     </table>";

//Our final PDF will be stores in this later
byte[] bytes;

//Create our PDF
using (var ms = new MemoryStream()) {
    using (var document = new Document()) {
        using (var writer = PdfWriter.GetInstance(document, ms)) {
            document.Open();

            //Bind a stream to our string
            using (var sr = new StringReader(htmlTable)) {
                //Bind a parser to our document
                using (var htmlparser = new HTMLWorker(document)) {
                    //Parse the HTML into iTextSharp objects and place them directly into the documenht
                    htmlparser.Parse(sr);
                }
            }

            document.Close();
        }
    }

    //Grab our finished PDF as a byte array
    bytes = ms.ToArray();
}

//At this point, the variable bytes holds an array of bytes that represents a valid PDF