Tags

, , , ,

To this implementation I used ITextSharp.DLL and ItextSharp.xmlworker DLL. Please note that this will only shows how to do the conversion . Please use your own different font files and image files in this example

Itextsharp.DLL can be download from here: – http://sourceforge.net/projects/itextsharp/

ItextSharp.xmlworker can be download from here: – http://sourceforge.net/projects/itextsharp/files/xmlworker/

Expectations of ItextSharp framework.

  • HTML must be well formatted
  • CSS must  be well formatted
  • CSS Files which going to use by the HTML must be resides inside the working solution
  • Fonts which going to use by the CSS must be resides inside the  working solution
  • Images cannot be  applied from CSS classes , they should be inserted as inline styles

The Project Setup

This example code was done with a simple MVC 4 Application.
I Have created a folder named resources and placed the files as follows.
It’s not a must to follow this structure HTMLtoPDFApp (The MVC Application Name)

Resources
---CSS
------grace.css
---Fonts
------Mf Sipping on Sunshine.ttf
------TequilaSunset-Regular.ttf
--HTML
------grace.html

Implementation

First of all we need to read the contents inside a CSS file and an HTML file as a string representation. If you are planning to read a content from a file in a physical location
you can only do this with the absolute path. I tried with the relative path but it didn’t work.  So first of all let’s read the CSS and the HTML from physically located files

var cssText = System.IO.File.ReadAllText(@"C:\<Path to your Application>\HTMLtoPDFApplication\HTMLtoPDFApp\Resources\CSS\grace.css");
var htmlText = System.IO.File.ReadAllText(@"C:\<Path to your Application>\HTMLtoPDFApplication\HTMLtoPDFApp\Resources\HTML\grace.html");
Next we need to declare the stuff which required for basic pdf implementation using Memory Stream and ItextSharp Library components
var memoryStream = newMemoryStream();
var document = newDocument();
var writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
Now we need to using features available in XMLWorker library. First of all I would prefer to register fonts.
var xmlWorkerFontProvider = newXMLWorkerFontProvider();
xmlWorkerFontProvider.Register("http://localhost:58045/Resources/Fonts/Mf Sippin On Sunshine.ttf");

Please note that we have registered fonts in the following format. <DomainName>/Folder/Font Name.  Relative location does not work. After that we need to pass the HTML and the CSS as a string for XML Helper.

Now let’s pass the CSS and the HTML which comes as a  representation of strings to the XMLWorker

using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
{
    using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlText)))
    {
        XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
    }
}
 
var pdfContent = new PdfContent
{
    MemoryStream = memoryStream,
    FileName = "SomeName"
};
return pdfContent;

PdfContent will setup the necessary response headers to  download the Pdf

public class PdfContent : ActionResult
    {
        public MemoryStream MemoryStream { get; set; }
        public string FileName { get; set; }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            var response = context.HttpContext.Response;
            response.ContentType = "pdf/application";
            response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".pdf");
            response.OutputStream.Write(MemoryStream.GetBuffer(), 0, MemoryStream.GetBuffer().Length);
        }
    }
HTML File used for this Conversion
<html>
<head>
    <link href="../CSS/grace.css" rel="stylesheet"></link>
</head>
<body>
    <div class="main_div">
        <div class="text_one">Hello</div>
        <div class="text_two">aoha</div>
        <div class="text_three">Hoi</div>
    </div>
    <div class="table_div">
        <table class="tbl_page">
            <tr class="tbr_raw">
                <th>Name</th>
                <th>Age</th>
                <th>ODI Runs</th>
                <th>Test Runs</th>
            </tr>
            <tr>
                <td class="tbl_cell">Tillakaratne Dilshan</td>
                <td>38</td>
                <td>10007</td>
                <td>5492</td>
            </tr>
            <tr>
                <td>Kusal Perera</td>
                <td>38</td>
                <td>10007</td>
                <td>5492</td>
            </tr>
            <tr>
                <td>Shehan Jayasuriya</td>
                <td>38</td>
                <td>10007</td>
                <td>5492</td>
            </tr>
            <tr>
                <td>Dhananjaya de Silva</td>
                <td>38</td>
                <td>10007</td>
                <td>5492</td>
            </tr>
        </table>
    </div>
    <div class="div_font_class">Yeritz</div>
    <div style="width:200px; height:200px;">
    </div>
    <div>
        <p class="para_div">
            Hurricane Diane was the costliest Atlantic hurricane of its time. One of three hurricanes to hit North Carolina during the 1955 Atlantic hurricane season, it formed on August 7 from a tropical wave between the Lesser Antilles and Cape Verde. Diane initially moved west-northwestward with little change in its intensity, but began to strengthen rapidly after turning to the north-northeast. On August 12, the hurricane reached peak sustained winds of 105 mph (170 km/h), making it a Category 2 hurricane. Gradually weakening after veering back west, Diane made landfall near Wilmington, North Carolina, as a strong tropical storm on August 17, just five days after Hurricane Connie struck near the same area. Diane weakened further after moving inland, at which point the United States Weather Bureau noted a decreased threat of further destruction. The storm turned to the northeast, and warm waters from the Atlantic Ocean helped produce record rainfall across the northeastern United States. On August 19, Diane emerged into the Atlantic Ocean southeast of New York City, becoming extratropical two days later and completely dissipating by August 23.
        </p>
    </div>
    <div>
        <p class="para_div_two">
            he first area affected by Diane was North Carolina, which suffered coastal flooding but little wind and rain damage. After the storm weakened in Virginia, it maintained an area of moisture that resulted in heavy rainfall after interacting with the Blue Ridge Mountains, a process known as orographic lift. Flooding affected roads and low-lying areas along the Potomac River. The northernmost portion of Delaware also saw freshwater flooding, although to a much lesser extent than adjacent states. Diane produced heavy rainfall in eastern Pennsylvania, causing the worst floods on record there, largely in the Poconos and along the Delaware River. Rushing waters demolished about 150 road and rail bridges and breached or destroyed 30 dams. The swollen Brodhead Creek virtually submerged a summer camp, killing 37 people. Throughout Pennsylvania, the disaster killed 101 people and caused an estimated $70 million in damage (1955 USD).[nb 1] Additional flooding spread through the northwest portion of neighboring New Jersey, forcing hundreds of people to evacuate and destroying several bridges, including one built in 1831. Storm damage was evident but less significant in southeastern New York.
        </p>
        <p class="para_div_two">
            Reference :- <a class="link_deco" target="_blank" href="https://en.wikipedia.org/wiki/Hurricane_Diane">Wiki Article Link</a>
        </p>
    </div>
</body>
</html>

CSS File which was used for this Conversion 

.main_div {
    background-color: #F8F8F8;
    vertical-align: center;
    z-index: 1000000;
    border-width: 1px;
    border-style: solid;
    border-radius: 2px;
    border-color: #E0E0E0;
    width: 400px;
    height: 200px;
}
.text_one {
    color: #003300;
}
.text_two {
    color: #0000ca;
}
.text_three {
    color: #e40000;
}
.tbl_page {
    margin-top: 5px;
    color: black;
    background-color: cornsilk;
    display: block;
    border-style: solid;
    border-color: wheat;
    border-width: 1px;
    ;
    border-radius: 5px;
    font-family: "Times New Roman", Times, serif;
    font-size: 12px;
    white-space: normal;
    line-height: normal;
}
.tbl_cell {
    background-color: honeydew;
    font-family: "Tequila Sunset";
}
td, th {
    display: table-cell;
    padding: 20px;
}
.tbr_raw {
    background-color: #66CCFF;
    text-align: center;
}
.image_div_background {
    height: 400px;
    width: 400px;
    background-repeat: no-repeat;
}
.div_font_class {
    font-style: bold;
    font-family: "Tequila Sunset";
    font-size: 20px;
    color: #003300;
}
.para_div {
    margin-top: 160px;
    font-family: "Mf Sippin On Sunshine";
    text-align: justify;
    text-justify: inter-word;
    color: rgb(0,0,255);
    line-height: 20pt;
}
.para_div_two {
    margin-top: 10px;
    text-align: justify;
    text-justify: inter-word;
    color: rgb(3,44,89);
    line-height: 40pt;
}
.link_deco {
    text-decoration: none;
    color: lightslategray;
}