Reputation: 857
I have a html document with css defined within the head tags. I want this html string to converted into a pdf.
I have used ABC pdf and SelectPDF dlls and generated the pdf.
When I used ABC pdf it does not applied any CSS styles when converting to pdf. SelectPDF has applied the CSS styles to the pdf but its bit messy.
Does any one know how to properly convert HTML to pdf?
Upvotes: 0
Views: 7199
Reputation: 857
I have found a solution to convert a HTML string with inline style to PDF. I have done using ABCpdf version 11. This solution is given by the technical team at ABCpdf. I have tried many numerous libraries and online solutions (where I can pass my HTML string to service and get the pdf) but none has given me a good output including the above commented solutions. So here is the solution for the HTML to pdf conversion.
<html>
<meta charset="utf-8" />
<head><head>
<body style="height: 100%;background-color: #D7CCC8;font-size: 12px;position: relative;height: 100%;margin: 0;">
<div style='position: relative;min-height: 100%;padding: 1em 1em 2em;margin-bottom: -11em;'>
put the content that you want to be in the pdf(with inline styling the html elements). This is an example of the html string that needs to be converted into a pdf.
</div>
</body>
</html>
Following is the C# code to convert the above HTML string to a pdf.
//generate pdf
using (Doc pdfDocument = new Doc())
{
// Set HTML options
pdfDocument.HtmlOptions.Engine = EngineType.Gecko;
pdfDocument.HtmlOptions.Media = MediaType.Screen;
// Convert first HTML page, result: html string
int pageID = pdfDocument.AddImageHtml(result);
// Convert other HTML pages
while (true)
{
if (!pdfDocument.Chainable(pageID))
{
break;
}
pdfDocument.Page = pdfDocument.AddPage();
pageID = pdfDocument.AddImageToChain(pageID);
}
//save
for (int i = 0; i < pdfDocument.PageCount; i++)
{
pdfDocument.PageNumber = i;
pdfDocument.Flatten();
}
//save the pdf, pdfFullPath: path to save the pdf
pdfDocument.Save(pdfFullPath);
}
The above code will convert the html string to pdf. NOTE: in my html I did not have any images and all the styles were mentioned inline, like in the example.
Hope the above solution will help someone as it did for me. Anyone is welcomed to suggest any improvements for this code (e.g: insert images, complex html to pdf conversion etc.).
Upvotes: 2