Set width of a <TD> when converting HTML to PDF using iTextSharp
Solution 1
You need to use a combination of colspan and LoadTagStyle, both of which are outside the bounds of what I can fit in this textbox. To simplify, iTextSharp treats the total number of columns as 100% of the table, so a colspan of 5 on a table that is 10 columns should be treated like 50% of the table.
I have found that I have to play around with the values a bit, but hopefully that will lead you down the right path.
Solution 2
Use colspan property. If you have two cells defined as 10% and 90% for instance. Set colspan = 1 and 9 respectively. It does the trick.
Solution 3
you must set td width in percentage <td width="10%">
for td in each row, not only in header or first row.
Solution 4
set the width="70%" and it should work.
<td width="70%">
Anuya
Updated on June 18, 2022Comments
-
Anuya about 2 years
On button click I need to read the HTML file and convert it to PDF. The PDF is generating without any problem. But the width of columns in table is equally distributed when converted to PDF. But I need the first column of my table to take 70% of the total size of my table (540)
How can I do this?
Template.html :
<table runat="server" id="header" border="3" width="540"> <tr> <td style="width:70%; text-align: center; font-weight: bold;"> <strong>Test Specification </strong> </td> <td style="width:10%; text-align: center; font-weight: bold;"> <strong>GST </strong> </td> <td style="width:10%; text-align: center; font-weight: bold;"> <strong>Service </strong> </td> <td style="width:10%; text-align: center; font-weight: bold;"> <strong>Amount </strong> </td> </tr> </table>
Button click to convert HTML to PDF :
protected void Button1_Click(object sender, EventArgs e) { String htmlText = System.IO.File.ReadAllText(Request.PhysicalApplicationPath + "\\Template.htm"); Document document = new Document(); PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + DateTime.Now.ToString("ddMMyyyy") + "_" + DateTime.Now.ToString("HHmmss tt") + ".pdf", FileMode.Create)); document.Open(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); hw.Parse(new StringReader(HTML)); document.Close(); StringBuilder sb = new StringBuilder(); sb.Append(HTML); }
-
James almost 11 yearsJust to add my 2 cents as I've found out the hard way - you can evidently not have any columns that have the width set be part of a
colspan
cell set. In other words, if column 1 has a width set, and somewhere along the line you have column one's attributecolspan='2'
, it breaks the width setting completely... -
Ozkan almost 6 yearsDoes not work on older versions of ITextSharp. Be sure to use the latest version!