Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
Working with PDFs in C# involves not just rendering and formatting content, but also manipulating text to meet your needs. Whether you’re extracting, searching, or editing text within a PDF, knowing how to leverage C# string methods can significantly enhance your workflow. In this article, we'll explore common C# string operations, how they apply to IronPDF, and how you can use them to streamline your PDF processing tasks.
C# provides a variety of string methods that allow you to handle text in versatile ways. From basic operations like concatenation and replacement to advanced techniques like regular expressions, these methods are essential when manipulating content within PDFs.
IronPDF, a powerful library for working with PDFs in C#, integrates seamlessly with these string functions, giving developers a flexible toolset for handling PDF content. Whether you need to extract text, search for patterns, or manipulate content, understanding how to use C# string methods with IronPDF will help you achieve your goals.
Add from PixabayUpload
or drag and drop an image here
Add image alt text
IronPDF is a robust PDF library for .NET, designed to simplify PDF creation, manipulation, and automation. Whether you need to generate dynamic documents or extract and edit content, IronPDF offers a seamless solution with a rich set of features.
IronPDF provides a comprehensive suite of tools to handle all your PDF needs with ease and efficiency. Start exploring its powerful features today with a free trial and see how IronPDF can streamline your PDF workflows!
Concatenation is one of the simplest operations when working with strings. In C#, there are multiple ways to join two or more strings together, with the most common methods being the + operator and String.Concat().
string text1 = "Hello";
string text2 = "World";
string result = text1 + " " + text2; // Output: "Hello World"
string text1 = "Hello";
string text2 = "World";
string result = text1 + " " + text2; // Output: "Hello World"
Dim text1 As String = "Hello"
Dim text2 As String = "World"
Dim result As String = text1 & " " & text2 ' Output: "Hello World"
Add from PixabayUpload
or drag and drop an image here
Add image alt text
When working with IronPDF, you might need to concatenate strings to create a full document or manipulate text in extracted content. For example, you can merge the header and body of a PDF document as strings before applying formatting:
var pdfText = "Header: " + extractedHeader + "\n" + "Body: " + extractedBody;
var pdfText = "Header: " + extractedHeader + "\n" + "Body: " + extractedBody;
Imports Microsoft.VisualBasic
Dim pdfText = "Header: " & extractedHeader & vbLf & "Body: " & extractedBody
This demonstrates how simple string concatenation can merge specified substrings into one cohesive block. As we’ll see later, such concatenated strings can be used to build dynamic content for PDFs.
PDF Output:
Add from PixabayUpload
or drag and drop an image here
Add image alt text
When creating a new document using IronPDF, the specified index position of text strings will be critical for determining where elements like the header or body appear on the page. In this way, the current string object can directly impact layout decisions.
Once you’ve extracted and manipulated the text, you might need to format it before adding it to a new PDF. IronPDF allows you to set font styles, sizes, and even positioning using the RenderHtmlAsPdf conversion feature, where C# string methods can help you generate formatted content dynamically.
For example, you could create dynamic headers and body content by concatenating strings with HTML tags:
string htmlContent = "<h1>" + headerText + "</h1>" + "<p>" + bodyText + "</p>";
string htmlContent = "<h1>" + headerText + "</h1>" + "<p>" + bodyText + "</p>";
Dim htmlContent As String = "<h1>" & headerText & "</h1>" & "<p>" & bodyText & "</p>"
This HTML content can then be converted into a well-formatted PDF using IronPDF:
PdfDocument pdf = HtmlToPdf.ConvertHtmlString(htmlContent);
pdf.SaveAs("formattedDocument.pdf");
PdfDocument pdf = HtmlToPdf.ConvertHtmlString(htmlContent);
pdf.SaveAs("formattedDocument.pdf");
Dim pdf As PdfDocument = HtmlToPdf.ConvertHtmlString(htmlContent)
pdf.SaveAs("formattedDocument.pdf")
PDF Output:
Add from PixabayUpload
or drag and drop an image here
Add image alt text
This approach allows you to easily generate PDFs with dynamically generated content while ensuring the right text formatting. By generating a new string from dynamic content, you can pass formatted string arrays of HTML content to IronPDF, ensuring that the PDF output matches your requirements.
In many cases, you’ll need to check if a string contains a specified substring. The Contains() method is useful for this, as it returns true or false based on whether the specified string exists within the target string.
string documentText = "Invoice Number: 12345";
bool containsInvoiceNumber = documentText.Contains("Invoice Number");
string documentText = "Invoice Number: 12345";
bool containsInvoiceNumber = documentText.Contains("Invoice Number");
Dim documentText As String = "Invoice Number: 12345"
Dim containsInvoiceNumber As Boolean = documentText.Contains("Invoice Number")
To find a specified character within a string, the IndexOf() method is particularly useful. It returns the specified position where the character or substring first appears in the string.
string str = "Invoice Number: 12345"; int position = str.IndexOf('5'); // Returns the position of the first '5'
string str = "Invoice Number: 12345"; int position = str.IndexOf('5'); // Returns the position of the first '5'
Dim str As String = "Invoice Number: 12345"
Dim position As Integer = str.IndexOf("5"c) ' Returns the position of the first '5'
This can be handy when extracting dynamic data such as numbers or dates from text within a PDF using IronPDF.
For more complex text extraction, regular expressions (Regex) offer a powerful tool for pattern matching. With Regex, you can extract structured data, such as dates, invoice numbers, or even email addresses, from unstructured text within a PDF.
using System.Text.RegularExpressions;
string text = "Date: 02/11/2025";
Match match = Regex.Match(text, @"\d{2}/\d{2}/\d{4}");
if (match.Success)
{
string date = match.Value; // Output: "02/11/2025"
}
using System.Text.RegularExpressions;
string text = "Date: 02/11/2025";
Match match = Regex.Match(text, @"\d{2}/\d{2}/\d{4}");
if (match.Success)
{
string date = match.Value; // Output: "02/11/2025"
}
Imports System.Text.RegularExpressions
Private text As String = "Date: 02/11/2025"
Private match As Match = Regex.Match(text, "\d{2}/\d{2}/\d{4}")
If match.Success Then
Dim [date] As String = match.Value ' Output: "02/11/2025"
End If
Regular expressions can be particularly useful for documents with variable content or specific formats you need to capture. Using IronPDF to extract raw text combined with regular expressions helps automate tasks like form processing, data validation, and reporting.
When working with large blocks of text, such as multiple pages of content or data-driven reports, it’s more efficient to use a StringBuilder instead of regular string concatenation. StringBuilder is optimized for scenarios where you need to append or modify large amounts of text without creating multiple intermediate string instances.
StringBuilder sb = new StringBuilder();
sb.AppendLine("Header: " + headerText);
sb.AppendLine("Content: " + bodyText);
string finalText = sb.ToString();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Header: " + headerText);
sb.AppendLine("Content: " + bodyText);
string finalText = sb.ToString();
Dim sb As New StringBuilder()
sb.AppendLine("Header: " & headerText)
sb.AppendLine("Content: " & bodyText)
Dim finalText As String = sb.ToString()
IronPDF can handle large PDF documents, and integrating StringBuilder in your workflow ensures better performance when generating or manipulating large texts within PDFs.
The Equals() method checks whether two string instances match, meaning they have the same value. This is particularly useful for validation or comparisons within PDF content.
string str1 = "Invoice";
string str2 = "Invoice";
bool isMatch = str1.Equals(str2); // Returns true as both have the same value
string str1 = "Invoice";
string str2 = "Invoice";
bool isMatch = str1.Equals(str2); // Returns true as both have the same value
Dim str1 As String = "Invoice"
Dim str2 As String = "Invoice"
Dim isMatch As Boolean = str1.Equals(str2) ' Returns true as both have the same value
In IronPDF, this could be applied when comparing extracted text to ensure it matches a desired format or value.
When working with text in PDFs, you may need to manipulate or check for specified Unicode characters. The IndexOf() method can also be used to find the position of a specific unicode character within a string.
string unicodeStr = "Hello * World";
int unicodePosition = unicodeStr.IndexOf('*'); // Finds the position of the unicode character
string unicodeStr = "Hello * World";
int unicodePosition = unicodeStr.IndexOf('*'); // Finds the position of the unicode character
Dim unicodeStr As String = "Hello * World"
Dim unicodePosition As Integer = unicodeStr.IndexOf("*"c) ' Finds the position of the unicode character
PDF Output
Add from PixabayUpload
or drag and drop an image here
Add image alt text
Additionally, converting strings to a unicode character array can be useful when working with text in different languages or symbols:
char[] unicodeArray = "Hello * World".ToCharArray();
char[] unicodeArray = "Hello * World".ToCharArray();
Dim unicodeArray() As Char = "Hello * World".ToCharArray()
This allows for more precise manipulation of characters, especially when dealing with PDFs in various languages or formats.
Another powerful feature when working with strings is the ability to extract a specified substring. The Substring() method lets you select portions of a string starting from a specified index position. This is essential for extracting meaningful data from PDF content.
string sentence = "Total: $45.00";
string totalAmount = sentence.Substring(7); // Extracts "$45.00"
string sentence = "Total: $45.00";
string totalAmount = sentence.Substring(7); // Extracts "$45.00"
Dim sentence As String = "Total: $45.00"
Dim totalAmount As String = sentence.Substring(7) ' Extracts "$45.00"
This technique is useful when processing invoices or any form of structured text within a PDF.
Let’s put everything together and look at a more comprehensive example of how C# string methods can be used to generate a PDF using IronPDF. This example will demonstrate how to extract text, manipulate it with string methods, and then generate a formatted PDF.
Imagine we need to generate an invoice PDF dynamically, pulling information like the customer’s name, address, and items purchased. We'll use various string methods to format and manipulate the data before generating the final PDF.
using IronPdf;
using System;
using System.Text;
class Program
{
static void Main()
{
// Sample customer data
string customerName = "John Doe";
string customerAddress = "123 Main Street, Springfield, IL 62701";
string[] purchasedItems = { "Item 1 - $10.00", "Item 2 - $20.00", "Item 3 - $30.00" };
// Start building the HTML content for the invoice
StringBuilder invoiceContent = new StringBuilder();
// Adding the header
invoiceContent.AppendLine("<h1>Invoice</h1>");
invoiceContent.AppendLine("<h2>Customer Details</h2>");
invoiceContent.AppendLine("<p><strong>Name:</strong> " + customerName + "</p>");
invoiceContent.AppendLine("<p><strong>Address:</strong> " + customerAddress + "</p>");
// Adding the list of purchased items
invoiceContent.AppendLine("<h3>Items Purchased</h3>");
invoiceContent.AppendLine("<ul>");
foreach (var item in purchasedItems)
{
invoiceContent.AppendLine("<li>" + item + "</li>");
}
invoiceContent.AppendLine("</ul>");
// Calculate total cost (basic manipulation with string methods)
double totalCost = 0;
foreach (var item in purchasedItems)
{
string priceString = item.Substring(item.LastIndexOf('$') + 1);
double price = Convert.ToDouble(priceString);
totalCost += price;
}
// Adding total cost
invoiceContent.AppendLine("<p><strong>Total Cost:</strong> $" + totalCost.ToString("F2") + "</p>");
// Convert the HTML to PDF using IronPDF
var pdf = HtmlToPdf.ConvertHtmlString(invoiceContent.ToString());
// Save the generated PDF
pdf.SaveAs("Invoice_Johndoe.pdf");
Console.WriteLine("Invoice PDF generated successfully.");
}
}
using IronPdf;
using System;
using System.Text;
class Program
{
static void Main()
{
// Sample customer data
string customerName = "John Doe";
string customerAddress = "123 Main Street, Springfield, IL 62701";
string[] purchasedItems = { "Item 1 - $10.00", "Item 2 - $20.00", "Item 3 - $30.00" };
// Start building the HTML content for the invoice
StringBuilder invoiceContent = new StringBuilder();
// Adding the header
invoiceContent.AppendLine("<h1>Invoice</h1>");
invoiceContent.AppendLine("<h2>Customer Details</h2>");
invoiceContent.AppendLine("<p><strong>Name:</strong> " + customerName + "</p>");
invoiceContent.AppendLine("<p><strong>Address:</strong> " + customerAddress + "</p>");
// Adding the list of purchased items
invoiceContent.AppendLine("<h3>Items Purchased</h3>");
invoiceContent.AppendLine("<ul>");
foreach (var item in purchasedItems)
{
invoiceContent.AppendLine("<li>" + item + "</li>");
}
invoiceContent.AppendLine("</ul>");
// Calculate total cost (basic manipulation with string methods)
double totalCost = 0;
foreach (var item in purchasedItems)
{
string priceString = item.Substring(item.LastIndexOf('$') + 1);
double price = Convert.ToDouble(priceString);
totalCost += price;
}
// Adding total cost
invoiceContent.AppendLine("<p><strong>Total Cost:</strong> $" + totalCost.ToString("F2") + "</p>");
// Convert the HTML to PDF using IronPDF
var pdf = HtmlToPdf.ConvertHtmlString(invoiceContent.ToString());
// Save the generated PDF
pdf.SaveAs("Invoice_Johndoe.pdf");
Console.WriteLine("Invoice PDF generated successfully.");
}
}
Imports IronPdf
Imports System
Imports System.Text
Friend Class Program
Shared Sub Main()
' Sample customer data
Dim customerName As String = "John Doe"
Dim customerAddress As String = "123 Main Street, Springfield, IL 62701"
Dim purchasedItems() As String = { "Item 1 - $10.00", "Item 2 - $20.00", "Item 3 - $30.00" }
' Start building the HTML content for the invoice
Dim invoiceContent As New StringBuilder()
' Adding the header
invoiceContent.AppendLine("<h1>Invoice</h1>")
invoiceContent.AppendLine("<h2>Customer Details</h2>")
invoiceContent.AppendLine("<p><strong>Name:</strong> " & customerName & "</p>")
invoiceContent.AppendLine("<p><strong>Address:</strong> " & customerAddress & "</p>")
' Adding the list of purchased items
invoiceContent.AppendLine("<h3>Items Purchased</h3>")
invoiceContent.AppendLine("<ul>")
For Each item In purchasedItems
invoiceContent.AppendLine("<li>" & item & "</li>")
Next item
invoiceContent.AppendLine("</ul>")
' Calculate total cost (basic manipulation with string methods)
Dim totalCost As Double = 0
For Each item In purchasedItems
Dim priceString As String = item.Substring(item.LastIndexOf("$"c) + 1)
Dim price As Double = Convert.ToDouble(priceString)
totalCost += price
Next item
' Adding total cost
invoiceContent.AppendLine("<p><strong>Total Cost:</strong> $" & totalCost.ToString("F2") & "</p>")
' Convert the HTML to PDF using IronPDF
Dim pdf = HtmlToPdf.ConvertHtmlString(invoiceContent.ToString())
' Save the generated PDF
pdf.SaveAs("Invoice_Johndoe.pdf")
Console.WriteLine("Invoice PDF generated successfully.")
End Sub
End Class
StringBuilder: We use a StringBuilder to build the HTML content for the invoice. This allows us to efficiently append each part of the content (header, customer details, purchased items list, and total cost) without creating multiple intermediate string instances.
String Manipulation:
By using IronPDF's powerful HTML-to-PDF conversion and combining it with C# string manipulation techniques, you can automate the creation of dynamic documents, whether they’re invoices, reports, or contracts.
Add from PixabayUpload
or drag and drop an image here
Add image alt text
Mastering C# string methods when working with IronPDF can streamline your PDF processing tasks, whether you’re extracting, editing, or formatting content. By leveraging techniques like string concatenation, substring extraction, and regular expressions, you gain full control over the text in your PDFs, enabling more dynamic and efficient workflows.
IronPDF provides powerful PDF manipulation capabilities that work seamlessly with C# string methods. Whether you’re handling text extraction, searching for patterns, or automating content generation, combining IronPDF with C# string operations will save you time and effort.
Want to see how IronPDF can help with your PDF automation? Try out the free trial today and explore its full potential!