Utilize itextsharp to transform HTML into PDF files

When I try to convert HTML to PDF using iTextSharp, the CSS styling I apply to the webpage does not get carried over to the converted PDF file.

Here is the CSS code I am using:

<style type="text/css">
       .cssformat
            {
                width:300px;
                height:200px;
                border:2px solid black;
                background-color:white; 
                border-top-left-radius:60px 90px; 
                border-bottom-right-radius:60px 90px;
        }                
        </style>

And here is my HTML code:

<div id="divpdf" runat="server">
        <table id="tid" runat="server">
        <tr>
        <td>
       <asp:Label ID="Label1" runat="server" Text="this is new way of pdf" CssClass="cssformat"></asp:Label>
        </td>
        </tr>
        </table>
        </div>

I have attempted the following in C#:

 Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        Document pdfDoc = new Document(PageSize.A4, 60f, 80f, -2f, 35f);
        divpdf.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());   
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        hw1.Parse(new StringReader(sttt));
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
        sw.Close();
        sr.Close();
        hw.Close();

Answer №1

Struggling with converting HTML to PDF using iTextSharp led me to explore alternative solutions. Given the limitations of free tools, I had to think creatively to meet my client's needs without resorting to paid software.

After dabbling with different options, I opted for a workaround that involved using wkhtmltopdf and imagemagick to ensure a smooth conversion process. While this method required extra steps and automation using C#, it ultimately delivered the desired outcome.

While this approach may not be the most elegant or efficient, it served its purpose well in converting complex HTML5 and CSS3 pages with Google graphs and charts into PDF format.

Although commercial software may offer a quicker and more seamless solution, sometimes thinking outside the box can lead to unexpected success.

It's worth mentioning that despite its challenges, the conversion process handled the intricacies of HTML5, CSS3, Bootstrap 3, and various interactive elements seamlessly.

Answer №2

Here is a sample of how to convert HTML content with inline CSS code.

public static class PdfConverter {

    public static string ConvertHtmlToPdf(string htmlContent, string fileNameWithoutExtension, string filePath, string cssContent = "") {
        if (!Directory.Exists(filePath)) {
            Directory.CreateDirectory(filePath);
        }

    var fileNameWithPath = Path.Combine(filePath, fileNameWithoutExtension + ".pdf");

    using(var stream = new FileStream(fileNameWithPath, FileMode.Create)) {
        using(var document = new Document()) {
            var writer = PdfWriter.GetInstance(document, stream);
            document.Open();

            // custom tag processor instantiated and added to `HtmlPipelineContext`.
            var tagProcessorFactory = Tags.GetHtmlTagProcessorFactory();
            tagProcessorFactory.AddProcessor(new TableData(), new string[] {
                HTML.Tag.TD
            });
            var htmlPipelineContext = new HtmlPipelineContext(null);
            htmlPipelineContext.SetTagFactory(tagProcessorFactory);

            var pdfWriterPipeline = new PdfWriterPipeline(document, writer);
            var htmlPipeline = new HtmlPipeline(htmlPipelineContext, pdfWriterPipeline);

            // obtain ICssResolver and append custom CSS
            var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(true);
            cssResolver.AddCss(cssContent, "utf-8", true);
            var cssResolverPipeline = new CssResolverPipeline(
            cssResolver, htmlPipeline);

            var worker = new XMLWorker(cssResolverPipeline, true);
            var parser = new XMLParser(worker);
            using(var stringReader = new StringReader(htmlContent)) {
                parser.Parse(stringReader);
            }
        }
    }
    return fileNameWithPath;
    }
}

Answer №3

When using the <asp:Lable> element, the output format is set to "span", resulting in an inline display type. To change this to a block display, simply adjust the settings. Have fun experimenting!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to showcase data from input fields within a bootstrap modal dialog?

After the user has entered their details and clicks submit, I would like to present the information in a Bootstrap modal with a confirmation button below. This serves as a preview of the data before it is saved to the database. Here's what I have so ...

Attempting to utilize Bootstrap for containing text inside of a background

<div class="container"> <div class="row"> <div class="col-lg-9"> <h2 style="font-family:times-new-roman">BIOGRAPHY</h2> <div id="demo" class="collapse"> <p> Isaac Newton (4 January 1643 – 31 March 1727) w ...

How can jQuery be used to target a specific class based on its inner value?

For instance, within a div of the same class, there are 6 "p" tags - some containing 'member' text and others not. I aim to use jQuery to select all "p" tags with 'member' as their inner text and apply an additional class to them. Here ...

"Troubleshooting the absence of exception messages between Angular and .NET Core integration

Is there a way to retrieve a JSON array with a message in the console that says "Your direct manager has no account for your area"? Currently, I am only receiving the message "Http failure response for https://localhost:44385/api/Option/Post: 500 Internal ...

What is the best way to automatically convert the 'echo' function of PHP from HTML code?

I am looking for an easy way to convert PHP 'echo' code from HTML. For instance, similar to this tool: This particular tool converts JS printing code from HTML. In summary, I wish to see the following conversion: from <div id="foo"> ...

Customize one header to display different banners on each page using PHP conditionals

I created my website for entertainment purposes and I decided to use different banners on each page. Currently, in my header section, random banners appear using the following code: <div style=' height:145px; background-image:url(images/banners/ba ...

Is there a way to display the background when the popover is visible and hide it when the popover is hidden?

How do I make the backdrop appear when the popover is displayed, and disappear when the popover is closed? $(function(){ var content = '<button class="btn btn-sm btn-default" onclick="location.href=\'/billing/\'">Pay Now ...

Using jQuery to manipulate the image within a specific div element

I'm facing an issue with locating the img src within a div. I've written a function to find all the divs with specific ids: function identifyDiv(){ divArray = $("div[id^='your']"); divArray = _.shuffle(divArray); } This is the ...

Using the power of jQuery to load Ajax content, unfortunately, the content remains

Hey there, I'm currently working with an HTML file that utilizes AJAX to load content from other HTML files on the same server. However, for some reason, it's not functioning properly. I'm new to AJAX and I'm not sure what could be caus ...

Making <div> elements responsive by rearranging their display order using CSS in media queries, troubleshooting issues with floats, and adjusting font sizes

I'm currently working on a webpage located at: On this page, there is a containing division with 5 elements inside. They are floated left in order to align vertically, but I am facing some challenges when it comes to adjusting my CSS for media querie ...

Design a dynamic rectangular division using CSS and Bootstrap 4 that adapts to different screen sizes

I am encountering difficulties attempting to replicate a full-width rectangle div on a website, particularly with issues related to responsiveness and mobility. Here is an example of the design I am trying to recreate. And here's what I've acco ...

Determining height of an element in AngularJS directive prior to rendering the view

As I dive into the world of Angular, any assistance is greatly welcomed. My goal is to vertically align a div based on screen size (excluding the header and footer) when the page loads, the window resizes, and during a custom event triggered by the user ex ...

CSS: The grid-column and grid-row properties are malfunctioning

I'd like to create a grid with one column containing multiple rows of text, and the second column having an equal number of input rows. My initial plan was to create a grid where the number of rows equals the number of lines of text, and then define t ...

The functionality of the "enter" key is disabled in the textarea of Internet Explorer 8

Pressing enter in a textarea with the nowrap whitespace attribute set through CSS does not create a new line in IE8. Instead, just a simple whitespace appears. Other browsers like Opera, Chrome, and Firefox do not have this issue. Any solutions for this pr ...

Alert: The lack of boundary in the multipart/form-data POST data has been detected in an unknown source on line

I am currently developing a file uploader that uploads an image when the input changes. Here is the code for my HTML form: <form method="post" enctype="multipart/form-data"> <input name="uploaded[]" type="file" id="file_upload"/> </for ...

Using Ajax to trigger JSON-formatted HTML output

Issue with Populating Modal Window I am encountering difficulties while trying to populate a modal window dynamically with extended information retrieved from a mySQL database. Despite attempting various methods such as nested arrays, while loops, and for ...

JavaScript DateTimePicker onChange event malfunctioning

Issue with JS datetimepicker onChange event not functioning. Attempts have been made using OnSelect, OnClose, OnChange, OnHide, OnChangeMonth to trigger the datetimepicker event, but none of them seem to be effective. <input type="text" class="form-co ...

What is the best approach for adding text to an image using TCPDF?

I am trying to create dynvouchers PDF using TCPDF. However, I am facing an issue where the PDF generated does not include the username and password. Here is my code: $html = ''; $html .= '<table><tr>'; for ($a = 1; $a <= ...

Provide a secondary element within a JSON object

I am struggling to extract a second integer variable from a JSON array. Currently, I can only retrieve the SP_NAME (which is a string) variable from the controller, but now I also need to pass the SP_ID so that jQuery knows where to place the information. ...

Guide to adding a theme switcher feature to your current React website

Currently, I am faced with a challenge involving two theme files, theme.js and theme-dark.js, within the context of a complex React-based website. Despite having already set up the site, I am struggling to find a way to allow users to seamlessly switch bet ...