Modify the font of all text in a specific column using iTextSharp

For my PDF project, I am taking a string of HTML and using HTMLWorker.ParseToList to add each element to a column. Despite numerous attempts, I have been unable to change the font.

I tried adding the font to each element as I add it: el.Font = times; But unfortunately, this results in an error.

Here is the current code I am working with. My goal is to have all text displayed in Times Roman font.

var specialConditionsText = "<p>Special Conditions</p><p>A. More</p><p>B. Section B</p><p>C. Section C</p><ul><li>Bullet 1</li><li>Bullet 2</li></ul><ol><li>Number list 1</li><li>Number List 2<ol><li>Number list sub</li></ol></li></ol><p><br></p>";
StyleSheet styles = new StyleSheet();
styles.LoadTagStyle(HtmlTags.UL, HtmlTags.INDENT, "14");
styles.LoadTagStyle(HtmlTags.OL, HtmlTags.INDENT, "14");
styles.LoadTagStyle(HtmlTags.LI, HtmlTags.LEADING, "18");

BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
Font times = new Font(bfTimes, 12, Font.NORMAL);

using (StringReader sr = new StringReader(specialConditionsText))
{
//Get our raw PdfContentByte object letting us draw "above" existing content
PdfContentByte cb = pdfStamper.GetOverContent(11);

//Create a new ColumnText object bound to the above PdfContentByte object
ColumnText ct = new ColumnText(cb);

//Create a single column object spanning the entire page
ct.SetSimpleColumn(60, 190, 570, 720);

//Convert our HTML to iTextSharp elements
List<IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, styles);

//Loop through each element
foreach (IElement el in elements)
{
      //Add the element to the ColumnText
      el.Font = times;
      ct.AddElement(el);
}

ct.Go();
}   

Answer №1

The solution I came across was:

FontFactory.RegisterDirectories();

styles.LoadTagStyle("body", "face", "times new roman");
styles.LoadTagStyle("body", "encoding", "Identity-H");

This is the final code that I implemented. Hopefully, it can be of assistance to others.

specialConditionsText = HttpUtility.HtmlDecode(specialConditionsText);
                        specialConditionsText = specialConditionsText.Replace("<br>", "<br />");
                        specialConditionsText = specialConditionsText.Replace("<p>&nbsp;</p>", "<br />");

                        FontFactory.RegisterDirectories();

                        StyleSheet styles = new StyleSheet();
                        styles.LoadTagStyle(HtmlTags.UL, HtmlTags.INDENT, "14");
                        styles.LoadTagStyle(HtmlTags.OL, HtmlTags.INDENT, "14");
                        styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.LEADING, "13");
                        styles.LoadTagStyle(HtmlTags.BODY, HtmlTags.FONTSIZE, "11");
                        styles.LoadTagStyle("body", "face", "times new roman");
                        styles.LoadTagStyle("body", "encoding", "Identity-H");

                        using (StringReader sr = new StringReader(specialConditionsText))
                        {
                            //Get our raw PdfContentByte object allowing us to draw "above" existing content
                            PdfContentByte cb = pdfStamper.GetOverContent(11);

                            //Create a new ColumnText object bound to the above PdfContentByte object
                            ColumnText ct = new ColumnText(cb);

                            //Create a single column object spanning the entire page
                            ct.SetSimpleColumn(85, 192, 530, 720);

                            //Convert our HTML to iTextSharp elements
                            List<IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(sr, styles);

                            //Iterate through each element
                            foreach (IElement el in elements)
                            {
                                //Add the element to the ColumnText
                                ct.AddElement(el);
                            }

                            ct.Go();
                        }

Answer №2

If you want to include text in a specific font, try using the following code snippet. Instead of using addelement, this code utilizes addtext function along with a phrase (or even chunk).

ct.AddText(new Phrase(el.ToString(), times));

To create the desired font style, you can opt for either FontFactory.GetFont or BaseFont.CreateFont methods.

To learn more about formatting using itextsharp, refer to the resource below:

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

The hover CSS effect in the dropdown menu does not apply to sibling elements, but does work on descendant elements

Below are two sets of code for creating a dropdown menu. Although similar, the codes have a slight difference. In both cases, I have assigned classes to the main list item and submenu. The main heading has been given the 'heading' class with an a ...

Expand the list in both vertical and horizontal directions

I have a unique way I want this list to function: When clicked, it should reveal a vertical list. If an item in the vertical list is clicked, it should display horizontally with more information about that item. All items should be hidden until either Te ...

Whenever I open my collapsible dropdown, it seems to leap up unexpectedly

When I interact with the collapsible card, it has a jerky animation. I would like it to open smoothly instead. The issue lies with the tooltip-cus class. If I remove position: relative;, the opening animation is smooth, but then the position of the toolti ...

"Transitioning from Bootstrap version 3.3.7 to the latest Bootstrap version 4.1.3

Everywhere I look, it says that Bootstrap 4.1 is compatible with Bootstrap 3, but when I update my project to the newer version, a lot of things stop working, such as this cookie consent feature. @{ Layout = ""; } @using Microsoft.AspNetCore.Http ...

css does not bind borders with rounded limits

Is there a way to make the bottom border rounded at the ends? I want the solid line to have rounded edges, but it's not working with my current table code. <p-table [value]="fg?.controls?.treesSummary?.controls" styleClass="sumTable& ...

Displaying jQuery content tabs with excessive whitespace visible

My project utilizes a jQuery content tab plugin featuring 6 tabs with different content sections (Company, The founders, Team, Accolades, Careers, Philosophy). I am encountering an issue in Chrome where clicking on the Company tab after any other tab res ...

The nav bar in the React CSS is being populated with elements

Currently, I am in the process of developing a React app that includes a navigation bar. The issue at hand is that the content within my h1 tags and other elements are overlapping with the navigation bar - meaning that they are not properly contained withi ...

Is it possible for Google to crawl links that are generated using JavaScript?

I have developed four websites using HTML, CSS, and JavaScript without utilizing any server-side languages like PHP. My main goal is to acquire backlinks with various anchor text. To achieve this, I have decided to use a single JavaScript file on all my w ...

issue with centering using margin auto

Below is the HTML and CSS snippet for reference: * { margin: 0; padding: 0; } html, body { height: 100%; width: 100%; } header { height: 100px; background-color: #35424a; ...

Creating uniform heights for HTML column-based tables using divs in a React environment

I am developing a unique column-oriented and div-based table using React with Typescript. The data outside the table is organized in a column-based structure, rendering column 1 followed by row 1, row 2, row 3, then column 2 with its respective rows. The ...

Attempting to align two parent divs within a container div to appear side by side, while ensuring that one of the parent divs repeats multiple rows without impacting the second parent

I am in the process of building a custom WordPress theme from scratch, and I have created a template for the posts that will dynamically appear on the front page. To achieve the desired layout, I am utilizing Bootstrap 5. The structure includes a containe ...

Identifying the state of the sidebar is key

I am looking to create a script in JavaScript that can detect whether a sidebar has the class "active" or not. The sidebar is controlled by Bootstrap's toggle button, which adds the "active" class when clicked. <button type="button" id="sidebarCol ...

The CSS filter "progid:DXImageTransform.Microsoft.Alpha(style=1,opacity=80)" is not functioning properly in Firefox

Trying to apply a filter effect using CSS but encountering issues in Firefox: progid:DXImageTransform.Microsoft.Alpha(style=1,opacity=80 ) opacity: 0.5; -moz-opacity: 0.5; Any s ...

A guide on dynamically adjusting image size in ReactJS

Here is the structure I have: img { width: auto; height: 200px; } .cards { display: flex; justify-content: center; margin-top: 2em; width: 80%; flex-wrap: wrap; } .card { margin: 1em; box-shadow: 0 0 6px #000; ...

Contrasting flexbox overflow handling in React versus React Native

As a beginner in React Native, I have a query about achieving a flex layout with two child containers. The goal is to ensure that if one child's content overflows, the other child shrinks accordingly. In standard HTML/CSS, I was able to achieve this: ...

Sass list of Bootstrap version 4 grid dimensions

I'm attempting to integrate Bootstrap v4 variables into my project, which are contained within an array (_variables.scss): $grid-breakpoints: ( xs: 0, sm: 544px, md: 768px, lg: 992px, xl: 1200px ) !default; How can I reference it in my SAS ...

Is there a way to modify a jQuery animation to be positioned in the center of an element?

I have implemented a fade animation on my web page using code from JS Fiddle. Currently, the element fades in when it is fully visible in the window. Is there a way to modify this code so that the fade animation starts when only half of the element is visi ...

Tips for seamlessly integrating full-size images into the slider?

I'm a beginner when it comes to CSS and I am having trouble fitting two images inside my first slider. My goal is to display the full images within the slider, but the width of the images exceeds that of the slider. Below is the CSS code for the slid ...

What could be causing the CSS not to load on my WordPress website?

In an effort to improve my page speed score, I decided to install several plugins. Unfortunately, after installing w3 total cache, my website stopped loading CSS properly. Check out this image of the website ...

There is a single occurrence that happens when you click on a label alongside an

How can I change the number of events triggered when clicking a label without directly selecting the input element? Is there a way to achieve this using CSS only, or is it necessary to use JavaScript like document.querySelector('label input')? ...