Knowledgebase (2330)
Children categories
Comments are a commonly used feature in situations where multiple people are collaborating on the same document simultaneously. By using comments, collaborators can offer their thoughts or ideas directly in the document without making any changes to the actual text. This allows authors to review and consider the feedback before making any revisions. Additionally, comments provide an efficient way to identify specific issues within the document, as each comment is linked directly to the corresponding text or location in the document. In this article, we will explain how to work with comments in Word, specifically, how to add, reply to and delete comments in Word documents using Spire.Doc for C++.
- Add a Comment to a Paragraph in Word in C++
- Add a Comment to a Specific Text in Word in C++
- Add a Comment with a Picture in Word in C++
- Reply to a Comment in Word in C++
- Delete a Comment from Word in C++
Install Spire.Doc for C++
There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.
Integrate Spire.Doc for C++ in a C++ Application
Add a Comment to a Paragraph in Word in C++
You can add a comment to a paragraph to provide a suggestion or additional information about the content of the paragraph. The following steps explain how to add a comment to a specific paragraph in a Word document using Spire.Doc for C++:
- Initialize an instance of the Document class.
- Load a Word document using the Document->LoadFromFile(LPCWSTR_S fileName) method.
- Get a specific section of the document using the Document->GetSections()->GetItemInSectionCollection(int index) method.
- Get a specific paragraph of the section using the Section->GetParagraphs()->GetItemInParagraphCollection(int index) method.
- Add a comment to the paragraph using the Paragraph->AppendComment(LPCWSTR_S text) method.
- Set the author and ID for the comment using the Comment->GetFormat()->SetAuthor(LPCWSTR_S value) and Comment->GetFormat()->SetCommentId(int value) methods.
- Save the result document using the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
- C++
#include "Spire.Doc.o.h"
using namespace Spire::Doc;
int main()
{
//Initialize an instance of the Document class
intrusive_ptr<Document> document = new Document();
//Load a Word document
document->LoadFromFile(L"Input.docx");
//Get the first section of the document
intrusive_ptr<Section> section = document->GetSections()->GetItemInSectionCollection(0);
//Get the second paragraph of the first section
intrusive_ptr<Paragraph> paragraph = section->GetParagraphs()->GetItemInParagraphCollection(1);
//Add a comment to the paragraph
intrusive_ptr<Spire::Doc::Comment> comment = paragraph->AppendComment(L"This comment is added using Spire.Doc for Cpp.");
//Set the author and ID for the comment
comment->GetFormat()->SetAuthor(L"E-iceblue");
comment->GetFormat()->SetCommentId(0);
comment->GetFormat()->SetInitial(L"CM");
//Save the result document
document->SaveToFile(L"AddCommentToParagraph.docx", FileFormat::Docx2019);
document->Close();
}

Add a Comment to a Specific Text in Word in C++
In addition to adding comments to paragraphs, Spire.Doc for C++ is also capable of adding comments to specific text in Word documents. The following steps explain how to add a comment to a specific text in a Word document using Spire.Doc for C++:
- Initialize an instance of the Document class.
- Load a Word document using the Document->LoadFromFile(LPCWSTR_S fileName) method.
- Find the specific text in the document using the Document->FindString(LPCWSTR_S stringValue, bool caseSensitive, bool wholeWord) method.
- Initialize an instance of the Comment class to create a new comment. Then set the content, author, and ID for the comment.
- Initialize an instance of the CommentMark class and set its type as CommentMarkType::CommentStart to create a comment start mark. Then set the ID of the comment start mark to be the same as the ID of the comment.
- Initialize an instance of the CommentMark class and set its type as CommentMarkType::CommentEnd to create a comment end mark. Then set the ID of the comment end mark to be the same as the ID of the comment.
- Get the owner paragraph of the found text. Then add the comment to the owner paragraph using the Paragraph->GetChildObjects()->Add(intrusive_ptr<IDocumentObject> entity) method.
- Get the index position of the found text in the owner paragraph using the Paragraph->GetChildObjects()->IndexOf(intrusive_ptr<IDocumentObject> entity) method.
- Insert the comment start mark before the index position of the found text using the Paragraph->GetChildObjects()->Insert(int index, intrusive_ptr<IDocumentObject> entity) method.
- Insert the comment end mark after the index position of the found text using the Paragraph->GetChildObjects()->Insert(int index, intrusive_ptr<IDocumentObject> entity) method.
- Save the result document using the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
- C++
#include "Spire.Doc.o.h"
using namespace Spire::Doc;
int main()
{
//Initialize an instance of the Document class
intrusive_ptr<Document> document = new Document();
//Load a Word document
document->LoadFromFile(L"Input.docx");
//Find a specific text
intrusive_ptr<TextSelection> find = document->FindString(L"Microsoft Office", false, true);
//Create a comment and set its content, author and ID
intrusive_ptr<Comment> comment = new Comment(document);
comment->GetBody()->AddParagraph()->SetText(L"A software developed by Microsoft in 1988.");
comment->GetFormat()->SetAuthor(L"George");
comment->GetFormat()->SetCommentId(0);
//Create a comment start mark
intrusive_ptr<CommentMark> commentmarkStart = new CommentMark(document);
commentmarkStart->SetType(CommentMarkType::CommentStart);
//Set its ID to be the same as the ID of the comment
commentmarkStart->SetCommentId(0);
//Create a comment end mark
intrusive_ptr<CommentMark> commentmarkEnd = new CommentMark(document);
commentmarkEnd->SetType(CommentMarkType::CommentEnd);
//Set its ID to be the same as the ID of the comment
commentmarkEnd->SetCommentId(0);
//Get the found text as a single text range
intrusive_ptr<TextRange> range = find->GetAsOneRange();
//Get the owner paragraph of the text range
intrusive_ptr<Paragraph> para = range->GetOwnerParagraph();
//Add the comment to the owner paragraph
para->GetChildObjects()->Add(comment);
//Get the index position of the text range in the owner paragraph
int index = para->GetChildObjects()->IndexOf(range);
//Insert the comment start mark before the index position of the text range
para->GetChildObjects()->Insert(index, commentmarkStart);
//Insert the comment end mark after the index position of the text range
para->GetChildObjects()->Insert(index + 2, commentmarkEnd);
//Save the result document
document->SaveToFile(L"AddCommentForSpecificText.docx", FileFormat::Docx2019);
document->Close();
}

Add a Comment with a Picture in Word in C++
Sometimes, you may want to include a picture in your comment to supplement the textual content. The following steps explain how to add a comment with a picture to a Word document using Spire.Doc for C++:
- Initialize an instance of the Document class.
- Load a Word document using the Document->LoadFromFile(LPCWSTR_S fileName) method.
- Get a specific section of the document using the Document->GetSections()->GetItemInSectionCollection(int index) method.
- Get a specific paragraph of the section using the Section->GetParagraphs()->GetItemInParagraphCollection(int index) method.
- Add a comment to the paragraph using the Paragraph->AppendComment(LPCWSTR_S text) method. Then set the author name and ID for the comment.
- Initialize an instance of the DocPicture class.
- Load a picture using the DocPicture->LoadImageSpire(LPCWSTR_S imgFile) method. Then set the width and height for the picture.
- Add a paragraph to the comment. Then add the picture to the paragraph using the Paragraph->GetChildObjects()->Add() method.
- Save the result document using the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
- C++
#include "Spire.Doc.o.h"
using namespace Spire::Doc;
int main()
{
//Initialize an instance of the Document class
intrusive_ptr<Document> document = new Document();
//Load a Word document
document->LoadFromFile(L"Input.docx");
//Get the first section of the document
intrusive_ptr<Section> section = document->GetSections()->GetItemInSectionCollection(0);
//Get the first paragraph of the first section
intrusive_ptr<Paragraph> paragraph = section->GetParagraphs()->GetItemInParagraphCollection(0);
//Add a comment to the paragraph
intrusive_ptr<Comment> comment = paragraph->AppendComment(L"Spire.Doc for Cpp");
comment->GetFormat()->SetAuthor(L"E-iceblue");
comment->GetFormat()->SetCommentId(0);
//Load a picture
intrusive_ptr<DocPicture> docPicture = new DocPicture(document);
docPicture->LoadImageSpire(L"Doc-CPP.png");
//Set picture width and height
docPicture->SetWidth(100);
docPicture->SetHeight(100);
//Add the picture to the comment
intrusive_ptr<Paragraph> picParagraph = comment->GetBody()->AddParagraph();
picParagraph->GetChildObjects()->Add(docPicture);
//Save the result document
document->SaveToFile(L"AddCommentWithPicture.docx", FileFormat::Docx2019);
document->Close();
}

Reply to a Comment in Word in C++
When reviewing a comment added by others, you may want to reply to it to provide your insights. The following steps explain how to reply to an existing comment in a Word document using Spire.Doc for C++:
- Initialize an instance of the Document class.
- Load a Word document using the Document->LoadFromFile(LPCWSTR_S fileName) method.
- Get a specific comment in the document using the Document-> GetComments()->GetItem(int index) method.
- Initialize an instance of the Comment class to create a new comment. Then set the content, author, and ID for the comment.
- Add the new comment as a reply to the specific comment using the Comment->ReplyToComment(intrusive_ptr<Comment> replyComment) method.
- Save the result document using the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
- C++
#include "Spire.Doc.o.h"
using namespace Spire::Doc;
int main()
{
//Initialize an instance of the Document class
intrusive_ptr<Document> document = new Document();
//Load a Word document
document->LoadFromFile(L"AddCommentToParagraph.docx");
//Get the first comment of the document
intrusive_ptr<Comment> comment = document->GetComments()->GetItem(0);
//Create a comment and set its author, ID and content
intrusive_ptr<Comment> replyComment = new Comment(document);
replyComment->GetFormat()->SetAuthor(L"Michael");
replyComment->GetFormat()->SetCommentId(1);
replyComment->GetBody()->AddParagraph()->AppendText(L"Spire.Doc is a wonderful Word library.");
//Add the new comment as a reply to the first comment
comment->ReplyToComment(replyComment);
//Save the result document
document->SaveToFile(L"ReplyToComment.docx", FileFormat::Docx2019);
document->Close();
}

Delete a Comment from Word in C++
After you have finished revising the file and want to publish a formal version, you may need to remove the comments from the file. The following steps show you how to delete a comment from a Word document using Spire.Doc for C++:
- Initialize an instance of the Document class.
- Load a Word document using the Document->LoadFromFile(LPCWSTR_S fileName) method.
- Delete a specific comment from the document using the Document->GetComments()->RemoveAt(int index) method.
- Save the result document using the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
- C++
#include "Spire.Doc.o.h"
using namespace Spire::Doc;
int main()
{
//Initialize an instance of the Document class
intrusive_ptr<Document> document = new Document();
//Load a Word document
document->LoadFromFile(L"AddCommentToParagraph.docx");
//Delete the first comment from the document
document->GetComments()->RemoveAt(0);
//Save the result document
document->SaveToFile(L"DeleteComment.docx", FileFormat::Docx2019);
document->Close();
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Creating PDFs in C# is a must-have skill for developers, especially when building apps that generate reports, invoices, or other dynamic documents. Libraries like Spire.PDF for .NET simplify the process by offering tools for adding text, tables, and even converting HTML to PDF—helping you create professional documents with minimal effort.
This guide walks you through C# PDF generation step by step, from basic text formatting to advanced features like HTML rendering and tenplate. By the end, you’ll be able to customize and creaete PDFs for any project.
- .NET Library for Creating PDF Documents
- Creating a PDF File from Scratch
- Creating PDF from HTML
- Creating PDF Based on Template
- Conclusion
- FAQs
.NET Library for Creating PDF Documents
Spire.PDF is a powerful and versatile .NET library designed for creating, editing, and manipulating PDF documents programmatically. It provides developers with a comprehensive set of features to generate high-quality PDFs from scratch, modify existing files, and convert various formats into PDF.
Key Features of Spire.PDF
- PDF Creation & Editing – Build PDFs with text, images, tables, lists, and more.
- Rich Formatting Options – Customize fonts, colors, alignment, and layouts.
- HTML to PDF Conversion – Render web pages or HTML content into PDFs with precise formatting.
- Template-Based PDF Generation – Use placeholders in existing PDFs to dynamically insert text and data.
- Interactive Elements – Support for forms, annotations, and bookmarks.
- Document Security – Apply passwords, permissions, and digital signatures.
Installing Spire.PDF
To begin using Spire.PDF to create PDF documents, install it directly through NuGet.
Install-Package Spire.PDF
Alternatively, you can download Spire.PDF from our official website and manually import the DLL in your project.
Creating a PDF File from Scratch in C#
Understanding the Coordinate System
Before delving into the code, it's important to understand the coordinate system used by Spire.PDF. It resembles those in many graphics libraries but has specific PDF considerations. The origin (0,0) is located at the top-left corner of the content area (excluding margins), with positive Y values extending downward.
Understanding this system is essential for accurate element placement when building document layouts.

Note: This coordinate system applies only to newly created pages. In existing PDF pages, the origin is at the top-left corner of the entire page.
Creating a Simple PDF File with Text
Now, let's create our first PDF document. Text content is fundamental to most PDFs, so mastering text handling is crucial.
The following code demonstrates how to create a simple PDF with text in C#:
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace CreatePdfDocument
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Add a page
PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(50f));
// Create brush and font objects
PdfSolidBrush titleBrush = new PdfSolidBrush(new PdfRGBColor(Color.Blue));
PdfSolidBrush paraBrush = new PdfSolidBrush(new PdfRGBColor(Color.Black));
PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Times New Roman", 18f, FontStyle.Bold), true);
PdfTrueTypeFont paraFont = new PdfTrueTypeFont(new Font("Times New Roman", 13f, FontStyle.Regular), true);
// Specify title text
String titleText = "What's Spire.PDF";
// Set the text alignment via PdfStringFormat class
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
// Draw title on the center of the page
page.Canvas.DrawString(titleText, titleFont, titleBrush, page.Canvas.ClientSize.Width / 2, 20, format);
// Get paragraph content from a .txt file
string paraText = "Spire.PDF is a .NET library designed for creating, reading, and manipulating PDF documents." +
" It offers a wide range of features, including the ability to generate PDF documents from scratch and " +
"convert various formats into PDF. Users can modify existing PDF files by adding text, images, or annotations, " +
"and it also supports filling and managing interactive PDF forms. Additionally, Spire.PDF allows for the " +
"extraction of text and images from PDF documents, as well as converting PDF files into other formats like " +
"Word, Excel, and images.";
// Create a PdfTextWidget object to hold the paragrah content
PdfTextWidget widget = new PdfTextWidget(paraText, paraFont, paraBrush);
// Create a rectangle where the paragraph content will be placed
RectangleF rect = new RectangleF(0, 50, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height);
// Set the PdfLayoutType to Paginate to make the content paginated automatically
PdfTextLayout layout = new PdfTextLayout();
layout.Layout = PdfLayoutType.Paginate;
// Draw the widget on the page
widget.Draw(page, rect, layout);
// Save the document to file
doc.SaveToFile("SimpleDocument.pdf");
doc.Dispose();
}
}
}
In this code:
- PdfDocument: Serves as the foundation for creating a PDF, managing its structure and content.
- PdfPageBase: Adds a page to the document, specifying the A4 size and margins, setting up the drawing canvas.
- PdfSolidBrush: Defines colors for the title and paragraph text, filling shapes and text.
- PdfTrueTypeFont: Specifies font type, size, and style for text, creating distinct fonts for the title and paragraph.
- PdfStringFormat: Used to set text alignment (centered for the title), enhancing presentation.
- Canvas.DrawString(): Draws the title on the canvas at a specified location using the defined font, brush, and format.
- PdfTextWidget: Encapsulates the paragraph text, simplifying management and rendering of larger text blocks.
- PdfTextLayout: Configured for automatic pagination, ensuring text flows correctly to the next page if it exceeds the current one.
- PdfTextWidget.Draw(): Renders the paragraph within a specified rectangle on the page.
- SaveToFile(): Saves the document to the specified file path, completing the PDF creation process.
Output:

Enhancing Your PDF with Rich Elements
While text forms the foundation of most documents, professional PDFs often require richer content types to effectively communicate information. This section explores how to elevate your documents by incorporating images, tables, and lists.
1. Inserting an Image to PDF
Spire.PDF provides the PdfImage class to load and manage various image formats. You can position the image using the coordinate system discussed earlier with the DrawImage method.
// Load an image
PdfImage image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\ai.png");
// Specify the X and Y coordinates to start drawing the image
float x = 0f;
float y = 0f;
// Draw the image at a specified location on the page
page.Canvas.DrawImage(image, x, y);
2. Creating a Table in PDF
Spire.PDF provides the PdfTable class for creating and managing tables in a PDF document. You can populate the table with a DataTable and customize its appearance using various interfaces within PdfTable. Finally, the table is rendered on the page using the Draw method.
// Create a PdfTable
PdfTable table = new PdfTable();
// Create a DataTable
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Name");
dataTable.Columns.Add("Age");
dataTable.Columns.Add("Deparment");
dataTable.Rows.Add(new object[] { "David", "35", "Development" });
dataTable.Rows.Add(new object[] { "Sophie", "32", "Support" });
dataTable.Rows.Add(new object[] { "Wayne", "28", "Marketing" });
// Show header (invisible by default)
table.Style.ShowHeader = true;
//Set font color and backgroud color of header row
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray;
table.Style.HeaderStyle.TextBrush = PdfBrushes.White;
// Assign data source
table.DataSource = dataTable;
//Set text alignment in header row
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
//Set text alignment in other cells
for (int i = 0; i < table.Columns.Count; i++)
{
table.Columns[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
}
// Draw table on the page
table.Draw(page, new RectangleF(0, 150, 300, 150));
In addition to PdfTable, Spire.PDF offers the PdfGrid class, making it easier to create and manage complex tables in PDF documents. For detailed instruction, check this guide: Generate Tables in PDF Using C#.
3. Adding a List to PDF
The PdfSortedList class in Spire.PDF enables the creation of ordered lists with various numbering styles. You can specify the list content as a string and customize its appearance by adjusting properties such as font, indent, and text indent. The list is then rendered on the page using the Draw method at a specified location.
// Create a font
PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);
// Create a maker for ordered list
PdfOrderedMarker marker = new PdfOrderedMarker(PdfNumberStyle.Numeric, listFont);
//Create a numbered list
String listContent = "Data Structure\n"
+ "Algorithm\n"
+ "Computer Networks\n"
+ "Operating System\n"
+ "Theory of Computations";
PdfSortedList list = new PdfSortedList(listContent);
//Set the font, indent, text indent, brush of the list
list.Font = listFont;
list.Indent = 2;
list.TextIndent = 4;
list.Marker = marker;
//Draw list on the page at the specified location
list.Draw(page, 310, 125);
Output:
Below is a screenshot of the PDF file created by the code snippets in this section:

In addition to the mentioned elements, Spire.PDF supports the addition of nearly all common elements to PDFs. For more documentation, refer to the Spire.PDF Programming Guide.
Creating PDF from HTML in C#
In modern applications, it's increasingly common to need conversion of HTML content to PDF format—whether for web page archiving, report generation, or creating printable versions of web content.
Spire.PDF addresses this need through its HTML conversion capabilities, which leverage Chrome's rendering engine for exceptional fidelity. This approach ensures that your PDF output closely matches how the content appears in web browsers, including support for modern CSS features.
The conversion process is highly configurable, allowing you to control aspects like page size , margins , and timeout settings to accommodate various content types and network conditions.
Here's an exmaple demonstrating how to create PDF from HTML in C#:
using Spire.Additions.Chrome;
namespace ConvertHtmlToPdf
{
internal class Program
{
static void Main(string[] args)
{
// Specify the input URL and output PDF file path
string inputUrl = @"C:\Users\Administrator\Desktop\Html.html";
string outputFile = @"HtmlToPDF.pdf";
// Specify the path to the Chrome plugin
string chromeLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe";
// Create an instance of the ChromeHtmlConverter class
ChromeHtmlConverter converter = new ChromeHtmlConverter(chromeLocation);
// Create an instance of the ConvertOptions class
ConvertOptions options = new ConvertOptions();
options.Timeout = 10 * 3000;
// Set paper size and page margins of the converted PDF
options.PageSettings = new PageSettings()
{
PaperWidth = 8.27,
PaperHeight = 11.69,
MarginTop = 0,
MarginLeft = 0,
MarginRight = 0,
MarginBottom = 0
};
//Convert the URL to PDF
converter.ConvertToPdf(inputUrl, outputFile, options);
}
}
}
Output:

Creating PDF Based on Template in C#
Template-based PDF generation enhances maintainability and consistency in enterprise applications. Spire.PDF supports this with text replacement functionality, allowing the creation of master templates with placeholders filled at runtime. This separation enables non-technical users to update templates easily.
The PdfTextReplacer class facilitates replacements, including automatic text resizing to fit designated spaces, making it ideal for documents like contracts, certificates, or forms with a constant layout.
The following code demonstrates how to create a PDF file based on a predefined template in C#:
using Spire.Pdf;
using Spire.Pdf.Texts;
namespace GeneratePdfBasedOnTemplate
{
class Program
{
static void Main(string[] args)
{
// Create a PdfDocument object
PdfDocument doc = new PdfDocument();
// Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.pdf");
// Create a PdfTextReplaceOptions object and specify the options
PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions
{
ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth | PdfTextReplaceOptions.ReplaceActionType.WholeWord
};
// Get a specific page
PdfPageBase page = doc.Pages[0];
// Create a PdfTextReplacer object based on the page
PdfTextReplacer textReplacer = new PdfTextReplacer(page)
{
Options = textReplaceOptions
};
// Dictionary for old and new strings
Dictionary<string, string> replacements = new Dictionary<string, string>
{
{ "#name#", "John Doe" },
{ "#gender#", "Male" },
{ "#birthdate#", "January 15, 1990" },
{ "#address#", "123 Main St, Springfield, IL, 62701" }
};
// Loop through the dictionary to replace text
foreach (var pair in replacements)
{
textReplacer.ReplaceText(pair.Key, pair.Value);
}
// Save the document to a different PDF file
doc.SaveToFile("Output.pdf");
doc.Dispose();
}
}
}
Output:

Conclusion
The ability to create and manipulate PDF documents in C# is an invaluable skill for developers, especially in today's data-driven environment. This guide has covered various methods for generating PDFs, including creating documents from scratch, converting HTML to PDF, and utilizing templates for dynamic content generation.
With the robust features of Spire.PDF, developers can produce professional-quality PDFs that meet diverse requirements, from simple reports to complex forms. Dive into the world of PDF generation with Spire.PDF and unlock endless possibilities for your projects.
FAQs
Q1. What is the best library for creating PDFs in C#?
Spire.PDF is highly recommended due to its extensive feature set, user-friendly interface, and support for advanced operations like HTML-to-PDF conversion. It allows developers to easily create, manipulate, and customize PDF documents to meet a variety of needs.
Q2. Can I create PDF files in C# without external libraries?
While .NET has limited built-in capabilities, libraries like Spire.PDF are essential for complex tasks like adding tables or images.
Q3. How do I generate a PDF from HTML in C#?
Spire.PDF’s integration with Chrome allows for seamless conversion of HTML to PDF. You can customize page settings, such as margins and orientation, ensuring that the output PDF maintains the desired formatting and layout of the original HTML content.
Q4. How do I protect my PDF with passwords or permissions?
Spire.PDF offers robust encryption options through the PdfSecurityPolicy class. You can set owner and user passwords to restrict access, as well as define permissions for printing, copying, and editing the PDF. For more details, refer to: Encrypt or Decrypt PDF Files in C# .NET
Q5. Can I create PDF files from Word and Excel using Spire.PDF?
No, you cannot convert Word or Excel files directly with Spire.PDF. For Word to PDF conversion, use Spire.Doc, and for Excel to PDF, use Spire.XLS.
Get a Free License
To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.
Hyperlinks are a powerful tool in Excel that allows users to connect different parts of an Excel file or link to external sources such as websites, email addresses, or other files. They provide a quick and easy way for users to navigate within a worksheet or between different worksheets. In addition to facilitating navigation, hyperlinks can also provide additional context or resources related to the data in a file. For example, you can link to a website that provides more information about a specific product listed in your worksheet to help your readers gain a deeper understanding of the product. In this article, we will explore how to add hyperlinks to Excel, specifically, how to add text hyperlinks and image hyperlinks to Excel files in C++ using Spire.XLS for C++.
Install Spire.XLS for C++
There are two ways to integrate Spire.XLS for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.
Integrate Spire.XLS for C++ in a C++ Application
Add Text Hyperlinks to Excel in C++
A text hyperlink in Excel is a word or phrase that you can click on to jump to a specific location, such as a different part of the Excel file, an email address, a webpage, or an external file. The following steps explain how to add a text hyperlink to an Excel file using Spire.XLS for C++:
- Initialize an instance of the Workbook class.
- Get a specific worksheet using the Workbook->GetWorksheets()->Get(int index) method.
- Get the cell that you want to add a hyperlink to using the Worksheet->GetRange(LPCWSTR_S name) method.
- Add a hyperlink to the cell using the Worksheet->GetHyperLinks()->Add(intrusive_ptr<IXLSRange> range) method.
- Set the type, display text, and address for the hyperlink using the XlsHyperLink->SetType(HyperLinkType value), XlsHyperLink->SetTextToDisplay(LPCWSTR_S value) and XlsHyperLink->SetAddress(LPCWSTR_S value) methods.
- Autofit column width using the XlsWorksheet->AutoFitColumn(int columnIndex) method.
- Save the result file using the Workbook->SaveToFile(LPCWSTR_S fileName, ExcelVersion version) method.
- C++
#include "Spire.Xls.o.h";
using namespace Spire::Xls;
int main()
{
//Initialize an instance of the Workbook class
intrusive_ptr<Workbook> workbook = new Workbook();
//Get the first worksheet
intrusive_ptr<Worksheet> sheet = dynamic_pointer_cast<Worksheet>(workbook->GetWorksheets()->Get(0));
//Add a text hyperlink that links to a webpage
intrusive_ptr<CellRange> cell1 = dynamic_pointer_cast<CellRange>(sheet->GetRange(L"B3"));
intrusive_ptr<HyperLink> urlLink = sheet->GetHyperLinks()->Add(cell1);
urlLink->SetType(HyperLinkType::Url);
urlLink->SetTextToDisplay(L"Link to a website");
urlLink->SetAddress(L"https://www.e-iceblue.com/");
//Add a text hyperlink that links to an email address
intrusive_ptr<CellRange> cell2 = dynamic_pointer_cast<CellRange>(sheet->GetRange(L"E3"));
intrusive_ptr<HyperLink> mailLink = sheet->GetHyperLinks()->Add(cell2);
mailLink->SetType(HyperLinkType::Url);
mailLink->SetTextToDisplay(L"Link to an email address");
mailLink->SetAddress(L"mailto:support@e-iceblue.com");
//Add a text hyperlink that links to an external file
intrusive_ptr<CellRange> cell3 = dynamic_pointer_cast<CellRange>(sheet->GetRange(L"B7"));
intrusive_ptr<HyperLink> fileLink = sheet->GetHyperLinks()->Add(cell3);
fileLink->SetType(HyperLinkType::File);
fileLink->SetTextToDisplay(L"Link to an external file");
fileLink->SetAddress(L"C:\\Users\\Administrator\\Desktop\\Report.xlsx");
//Add a text hyperlink that links to a cell in another sheet
intrusive_ptr<CellRange> cell4 = dynamic_pointer_cast<CellRange>(sheet->GetRange(L"E7"));
intrusive_ptr<HyperLink> sheetLink = sheet->GetHyperLinks()->Add(cell4);
sheetLink->SetType(HyperLinkType::Workbook);
sheetLink->SetTextToDisplay(L"Link to a cell in sheet2");
sheetLink->SetAddress(L"Sheet2!B5");
//Add a text hyperlink that links to a UNC address
intrusive_ptr<CellRange> cell5 = dynamic_pointer_cast<CellRange>(sheet->GetRange(L"B11"));
intrusive_ptr<HyperLink> uncLink = sheet->GetHyperLinks()->Add(cell5);
uncLink->SetType(HyperLinkType::Unc);
uncLink->SetTextToDisplay(L"Link to a UNC address");
uncLink->SetAddress(L"\\192.168.0.121");
//Autofit column widths
sheet->AutoFitColumn(2);
sheet->AutoFitColumn(5);
//Save the result file
workbook->SaveToFile(L"AddTextHyperlinks.xlsx", ExcelVersion::Version2013);
workbook->Dispose();
}

Add Image Hyperlinks to Excel in C++
Similar to a text hyperlink, an image hyperlink is an image that you can click on to navigate to a specific location. The following steps explain how to add an image hyperlink to an Excel file using Spire.XLS for C++:
- Initialize an instance of the Workbook class.
- Get a specific worksheet using the Workbook->GetWorksheets()->Get(int index) method.
- Add text to a specific cell using the Worksheetsheet->GetRange(LPCWSTR_S name)->SetText(LPCWSTR_S value) method.
- Add an image to a specific cell using the Worksheet->GetPictures()->Add(int topRow,int leftColumn, LPCWSTR_S fileName) method.
- Set image width and height.
- Add a hyperlink to the image using the XlsBitmapShape->SetHyperLink(LPCWSTR_S linkString, bool isExternal) method.
- Save the result file using the Workbook->SaveToFile(LPCWSTR_S fileName, ExcelVersion version) method.
- C++
#include "Spire.Xls.o.h";
using namespace Spire::Xls;
int main()
{
//Initialize an instance of the Workbook class
intrusive_ptr<Workbook> workbook = new Workbook();
//Get the first worksheet
intrusive_ptr<Worksheet> sheet = dynamic_pointer_cast<Worksheet>(workbook->GetWorksheets()->Get(0));
//Add text to a specific cell
sheet->GetRange(L"A1")->SetText(L"Image Hyperlink");
//Add an image to a specific cell
intrusive_ptr<ExcelPicture> picture = ExcelPicture::Dynamic_cast<ExcelPicture>(sheet->GetPictures()->Add(2, 1, L"Logo.png"));
//Set image width and height
picture->SetWidth(100);
picture->SetHeight(100);
//Add a hyperlink to the image
picture->SetHyperLink(L"https://www.e-iceblue.com", true);
//Set column width
sheet->GetColumns()->GetItem(0)->SetColumnWidth(13);
//Save the result file
workbook->SaveToFile(L"AddImageHyperlink.xlsx", ExcelVersion::Version2013);
workbook->Dispose();
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.