INTRODUCTION
Let’s discuss how to add CSS in iTextSharp in C# ASP. Table is one of the most used elements in PDF file generation using ASP.NET application. Here we have “PdfTable” to make the structure in PDF file and “PdfCell” is used to make Rows and Columns inside table.
MERGE ROWS
You can merge the rows using iTextSharp. Find the below URL for more reference.
MERGE COLUMNS
Here you have an option to merge the Rows and Column using iTextSharp.
- PdfPTable table = newPdfPTable(4);
- table.TotalWidth = 400 f;
- table.LockedWidth = true;
- PdfPCell header = newPdfPCell(newPhrase("Header"));
- header.Colspan = 4;
- table.AddCell(header);
- table.AddCell("CellValue 1");
- table.AddCell("CellValue 2");
- table.AddCell("CellValue 3");
- table.AddCell("CellValue 4");
- PdfPTable nested = newPdfPTable(1);
- nested.AddCell("Row 1");
- nested.AddCell("Row 2");
- nested.AddCell("Row 3");
- PdfPCell nesthousing = newPdfPCell(nested);
- nesthousing.Padding = 0 f;
- table.AddCell(nesthousing);
- PdfPCell bottom = newPdfPCell(newPhrase("bottom"));
- bottom.Colspan = 3;
- table.AddCell(bottom);
- doc.Add(table);
OUTPUT
SOURCE CODE
This is the source code to apply CSS style with pdf file and download the file.
- publicstaticstring CSS_STYLE = "th { background-color: #C0C0C0; font-size: 16pt; }"
- + "td { font-size: 10pt; }";
- publicstaticstring HTML = "<html><body><table class='table-bordered'>"
- + "<thead><tr><th>Customer Name</th><th>Customer's Address</th> </tr></thead>"
- + "<tbody><tr><td> Shankar </td><td> Chennai </td></tr>"
- + "<tr><td> Krishnaa </td><td> Trichy </td></tr></tbody>"
- + "</table></body></html>";
In the above code, you can see that style is applied on the code.
This is the method to generate the PDF file.
- publicvoid GeneratePdf(String file) {
- Document document = new Document();
- PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
- document.open();
- CSSResolver cssResolver = new StyleAttrCSSResolver();
- CssFile cssFile = XMLWorkerHelper.getCSS(new ByteArrayInputStream(CSS_STYLE.getBytes()));
- cssResolver.addCss(cssFile);
-
- HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
- htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
-
- PdfWriterPipeline pdfFile = new PdfWriterPipeline(document, writer);
- HtmlPipeline html = new HtmlPipeline(htmlContext, pdfFile);
- CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
-
- XMLWorker worker = new XMLWorker(css, true);
- XMLParser p = new XMLParser(worker);
- p.parse(new ByteArrayInputStream(HTML.getBytes()));
- document.close();
- }
OUTPUT
You can see the output will be displayed like this,
Thank you.