itextsharp - CSS not getting applied - C# .NET
you're on the right track with using StyleSheet.LoadTagStyle().
basically it's a four step process:
- get the HTML in a string
- instantiate a StyleSheet object and call StyleSheet.LoadTagStyle() for each style you want.
- call HTMLWorker.ParseToList()
- add the IElement(s) returned from above call to the Document object.
here's a simple HTTP handler:
<%@ WebHandler Language='C#' Class='styles' %>
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class styles : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpResponse Response = context.Response;
Response.ContentType = "application/pdf";
string Html = @"
<h1>h1</h1>
<p>A paragraph</p>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>";
StyleSheet styles = new StyleSheet();
styles.LoadTagStyle(HtmlTags.H1, HtmlTags.FONTSIZE, "16");
styles.LoadTagStyle(HtmlTags.P, HtmlTags.FONTSIZE, "10");
styles.LoadTagStyle(HtmlTags.P, HtmlTags.COLOR, "#ff0000");
styles.LoadTagStyle(HtmlTags.UL, HtmlTags.INDENT, "10");
styles.LoadTagStyle(HtmlTags.LI, HtmlTags.LEADING, "16");
using (Document document = new Document()) {
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
List<IElement> objects = HTMLWorker.ParseToList(
new StringReader(Html), styles
);
foreach (IElement element in objects) {
document.Add(element);
}
}
}
public bool IsReusable {
get { return false; }
}
}
you need version 5.0.6 to run the code above. support for parsing HTML has been greatly improved.
if you want to see what tags are supported by the current version, see the SVN for the HtmlTags class.
Not applying the CSS while generating PDF using iTextsharp.dll
There's a couple of things going on here. First and foremost, the HTML/CSS parser in iText and iTextSharp are far from complete. They're definitely very powerful but still have a ways to go. Each version gets better so always make sure that you're using the latest version.
Second, I've seen more HTML/CSS activity in an add-on for iText/iTextSharp called XMLWorker that you might want to look at. You don't "load styles" anymore, you just pass raw HTML/CSS in and it figures out a lot of things. You can see some examples here, see a list of supported CSS attributes here, download it here (and get the two missing files here and here).
Third, LoadTagStyle
is for loading style attributes for HTML tags, not CSS IDs or Classes. You want to use LoadStyle
to load by class:
styles.LoadStyle("<classname>", "<attribute>", "<value>");
Unfortunately this method still doesn't do what you want it to do always. For instance, to change the font size you'd think you'd say:
styles.LoadStyle("headerdiv", "font-size", "60ptx);
But to get it to work you can only use relative HTML font sizes (1,2,-1, etc) or PT sizes and you must use the size
property:
styles.LoadStyle("headerdiv", "size", "60pt");
//or
styles.LoadStyle("headerdiv", "size", "2");
The LoadStyle
honestly feels like an afterthought that was only partially completed and I recommend not using it actually. Instead I recommend writing the style attributes directly inline if you can:
string html = "<div id=\"personal\" class=\"headerdiv\" style=\"padding-left:50px;font-size:60pt;font-family:Cambria;font-weight:700;\">Personal Data</div>";
Obviously this defeats the points of CSS and once again, that's why they're working on the new XMLWorker above.
Lastly, to use fonts by name you have to register them with iTextSharp first, it won't go looking for them:
iTextSharp.text.FontFactory.Register(@"c:\windows\fonts\cambria.ttc", "Cambria");
Styles are not getting Implemented in PDF using ITextSharp
This is a known problem with old versions of iText for .NET.
Over two years ago, we abandoned the name iTextSharp in favor of the name iText for .NET.
I've taken your HTML:
<html>
<head>
<style type='text/css'>
body{font-family: Segoe, 'Segoe UI', 'DejaVu Sans', 'Trebuchet MS', Verdana, 'sans-serif'; background: #f2f2f2; margin: 0; padding: 0; font-size: 20px; color: #565656;}
.outerpdfboxCont{width: 100%; background: #fff; margin: 0 auto; padding: 15px 30px; max-width: 80%; display: table;box-shadow: 1px 1px 2px #ddd;}
.blueBorderLine{background: #0A82B4; height: 10px; width: 100%; margin: 10px auto;}
.workingWrapperboxPdf{margin: 10px 0; padding: 10px 0px; display: table;width: 100%; }
.workingWrapperboxPdf h2{font-size: 36px; font-weight: 500; margin: 40px 0 0; line-height: 40px; color: #000;}
.workingWrapperboxPdf h3{font-size: 18px; font-weight: 300;line-height: 20px;}
.darkB{color: #000!important; font-weight: 500!important;}
.DataboxH{margin: 20px 0; display: table;width: 100%;}
.border-heading{border-bottom: 1px solid #ddd; font-size: 30px!important; line-height: 35px!important; color: #000!important;width: 100%; padding-bottom: 10px;}
</style>
</head>
<body>
<div class='outerpdfboxCont'>
<div class='blueBorderLine'></div>
<div class='workingWrapperboxPdf'>
<h3>Dalvir Singh</h3>
<h3 class='darkB'>India</h3>
<div class='DataboxH'>
<h2>Summery Of the PDF</h2>
<h3 class='darkB'>Summery of pdf will go here</h3>
<h3>PDF created on 2018-6-12</h3>
</div>
</div>
</div>
</body>
</html>
An I've opened it in a browser:
Then I've taken iText 7 and the pdfHTML add-on.
I executed the following line of code
HtmlConverter.ConvertToPdf(src, dest);
In this line src
refers to the HTML file, and dest
refers to the PDF that will be created based on the HTML.
This is what the resulting PDF looks like:
As you can see, the styles are respected. Regarding the font family: you can get one of the fonts with a higher preference by creating a ConverterProperties
object that gives the converter access to a font repository. For more info about that feature, please read chapter 6 of the PDF to HTML tutorial.
Summarized: your problem will go away once you upgrade to iText 7 + the pdfHTML add-on. You are using the old XMLWorkerHelper
that, as explained in the introduction of the HTML to PDF tutorial, is no longer supported.
itextsharp does not care my html styles
Here is fixed new code.
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create));
document.Open();
HTMLWorker hw = new HTMLWorker(document);
StringReader sr = new StringReader(HTML);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);
//hw.Parse(new StringReader(HTML));
document.Close();
ShowPdf(filename, filepath);
PdfAction action = new PdfAction(PdfAction.PRINTDIALOG);
Some HTML and CSS styles not applied when creating PDF document by iText
I fixed this issue by reading the article from iText
https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-6-using-fonts-pdfhtml
Simply change
FontProvider fontProvider = new DefaultFontProvider(false, false, false);
to
FontProvider fontProvider = new DefaultFontProvider(true, true, true);
Related Topics
Is Floating-Point Math Consistent in C#? Can It Be
Using C#, How Does One Figure Out What Process Locked a File
C# 3.0 Auto-Properties - Useful or Not
Await on a Completed Task Same as Task.Result
Json.Net Serialize/Deserialize Derived Types
Finding Holes in 2D Point Sets
Suspending Event Not Raising Using Winrt
Saml Assertion in a Xml Using C#
How to Ensure That a Division of Integers Is Always Rounded Up
How to Read Appsettings Values from a .Json File in ASP.NET Core
How to Use Optional Parameters in C#
High Quality Image Scaling Library
Use Linq to Get Items in One List≪≫, That Are Not in Another List≪≫
Setting a Property by Reflection With a String Value