Does the library PDFSharp can - like iTextSharp - generate PDF files *take into account HTML formatting *? (bold (strong), spacing
Have you guys heard of this. I might be answering very late but I thought it helps. It is very simple and works well.
var htmlContent = String.Format("<body>Hello world: {0}</body>",
DateTime.Now);
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
Edit: I came here with the question of converting HTML code to PDF using 'PDFSharp' and found out that 'PDFSharp' cannot do it then I found out about NReco and it worked for me so I felt it might help someone just like me.
HTML Renderer for PDF using PdfSharp can generate a PDF from an HTML
before inserting to the PDF.
To render as an image, please refer to the code from Diego answer.
To render as text, please refer code below:
static void Main(string[] args)
{
string html = File.ReadAllText(@"C:\Temp\Test.html");
PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.A4, 20, null, OnStylesheetLoad, OnImageLoadPdfSharp);
pdf.Save(@"C:\Temp\Test.pdf");
}
public static void OnImageLoadPdfSharp(object sender, HtmlImageLoadEventArgs e)
{
var imgObj = Image.FromFile(@"C:\Temp\Test.png");
e.Callback(XImage.FromGdiPlusImage(imgObj));
}
public static void OnStylesheetLoad(object sender, HtmlStylesheetLoadEventArgs e)
{
e.SetStyleSheet = @"h1, h2, h3 { color: navy; font-weight:normal; }";
}
HTML code
<html>
<head>
<title></title>
<link rel="Stylesheet" href="StyleSheet" />
</head>
<body>
<h1>Images
<img src="ImageIcon" />
</h1>
</body>
</html>
No, PDFsharp does not currently include code to parse HTML files.
I'll recommend you NReco.PdfGenerator because have free and paid license and its easy to install from nuget.
Main page: https://www.nrecosite.com/pdf_generator_net.aspx
Documentation: https://www.nrecosite.com/doc/NReco.PdfGenerator/
If you want create PDF from html file try:
String html = File.ReadAllText("main.html");
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
htmlToPdf.GeneratePdf(html, null, "C:/Users/Tmp/Desktop/mapa.pdf");