### Create a Simple 'Hello World' PDF
Source: https://docs.aspose.com/pdf/net/hello-world-example
This snippet demonstrates the fundamental steps to create a PDF document and add 'Hello World' text to it using Aspose.PDF for .NET. Ensure Aspose.PDF for .NET is installed. The code requires a data directory setup.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void HelloWorld()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Create PDF document
using (var document = new Aspose.Pdf.Document())
{
// Add page
var page = document.Pages.Add();
// Add text to new page
page.Paragraphs.Add(new Aspose.Pdf.Text.TextFragment("Hello World!"));
// Save PDF document
document.Save(dataDir + "HelloWorld_out.pdf");
}
}
```
--------------------------------
### Verify .NET SDK Installation
Source: https://docs.aspose.com/pdf/net/installation
Run this command in the terminal to confirm that the .NET SDK has been installed correctly.
```bash
dotnet --version
```
--------------------------------
### Input XML File Example
Source: https://docs.aspose.com/pdf/net/create-a-hello-world-pdf-document-through-xml-and-xslt
This is an example of an XML file containing simple content that will be transformed into a PDF.
```xml
Hello World!
```
--------------------------------
### Run PDF Generation Examples on Windows
Source: https://docs.aspose.com/pdf/net/python-net
This Python script imports an example module and runs simple and complex PDF generation methods. If using a trial version of Aspose.PDF for .NET, provide an empty string for the license path.
```python
import example_get_started
def main():
example = example_get_started.HelloWorld("")
example.run_simple()
example.run_complex()
if __name__ == '__main__':
main()
```
--------------------------------
### Install Azure CLI for Linux
Source: https://docs.aspose.com/pdf/net/converting-documents-with-microsoft-azure-app-service
Install the Azure Command-Line Interface on Linux systems using a curl script.
```bash
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
```
--------------------------------
### Install NuGet Packages
Source: https://docs.aspose.com/pdf/net/converting-documents-with-microsoft-azure-app-service
Install the necessary NuGet packages for Aspose.PDF, Application Insights, and Azure App Service logging using the Package Manager Console or .NET CLI.
```powershell
Install-Package Aspose.PDF
Install-Package Microsoft.ApplicationInsights.AspNetCore
Install-Package Microsoft.Extensions.Logging.AzureAppServices
```
```bash
dotnet restore
```
--------------------------------
### Install VS Code Extensions
Source: https://docs.aspose.com/pdf/net/converting-documents-with-microsoft-azure-app-service
Install the C# and Azure App Service extensions for Visual Studio Code to enhance development capabilities.
```bash
code --install-extension ms-dotnettools.csharp
code --install-extension ms-azuretools.vscode-azureappservice
```
--------------------------------
### Generate PDF from XML with XSL Params (.NET 8)
Source: https://docs.aspose.com/pdf/net/generate-pdf-from-xml
This example demonstrates PDF generation from XML using XSL-FO and XSL parameters in .NET 8. It mirrors the .NET Core 3.1 example but utilizes newer C# syntax like 'using var'. Ensure 'employees.xml' and 'employees.xslt' are accessible.
```csharp
Copy// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExampleXslfoToPdf_Param_21_6()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
var xmlContent = File.ReadAllText(dataDir + "employees.xml");
var xsltContent = File.ReadAllText(dataDir + "employees.xslt");
var options = new Aspose.Pdf.XslFoLoadOptions();
// Open XML file
using var document = new Aspose.Pdf.Document(TransformXsl(xmlContent, xsltContent), options);
// Save PDF document
document.Save(dataDir + "XSLFO_out.pdf");
}
public static MemoryStream TransformXsl(string inputXml, string xsltString)
{
var transform = new XslCompiledTransform();
// Create own XsltArgumentList
var argsList = new XsltArgumentList();
argsList.AddParam("isBoldName", "", "no");
using var reader1 = XmlReader.Create(new StringReader(xsltString));
transform.Load(reader1);
var memoryStream = new MemoryStream();
var results = new StreamWriter(memoryStream);
using var reader2 = XmlReader.Create(new StringReader(inputXml));
transform.Transform(reader2, argsList, results);
memoryStream.Position = 0;
return memoryStream;
}
```
--------------------------------
### Add Aspose.PDF NuGet Package
Source: https://docs.aspose.com/pdf/net/installation
Install the Aspose.PDF package into your .NET project using the .NET CLI.
```bash
# Install Aspose.PDF package
dotnet add package Aspose.PDF
```
--------------------------------
### CustomSecurityHandler Implementation Example
Source: https://docs.aspose.com/pdf/net/custom-security-handler
A sample implementation of the ICustomSecurityHandler interface demonstrating basic encryption and permission handling. This serves as a template for creating custom security logic.
```csharp
///
/// The custom security handler interface.
///
class CustomSecurityHandler : ICustomSecurityHandler
{
private EncryptionParameters _parameters;
///
/// Gets the filter name.
///
public string Filter
{
get
{
return "TestFilter";
}
}
///
/// Gets the sub-filter name.
///
public string SubFilter
{
get
{
return "TestsSubFilter";
}
}
///
/// Gets the handler or encryption algorithm version.
///
public int Version
{
get { return 1; }
}
///
/// Gets the handler or encryption algorithm revision.
///
public int Revision
{
get { return 2; }
}
///
/// Gets the key length.
///
public int KeyLength
{
get { return 8; }
}
///
/// Encrypt the document's permissions field. The result will be written to the Perms encryption dictionary field.
/// When opening a document, the value can be obtained in via the Perms field.
/// Allows you to check if the document permissions have changed.
///
/// The document permissions in integer representation.
/// The encrypted array.
public byte[] EncryptPermissions(int permissions)
{
byte[] perms = new byte[16];
perms[0] = (byte) (permissions & 0xff);
perms[1] = (byte) ((permissions >> 8) & 0xff);
perms[2] = (byte) ((permissions >> 16) & 0xff);
perms[3] = (byte) ((permissions >> 24) & 0xff);
perms[4] = 0xff;
perms[5] = 0xff;
perms[6] = 0xff;
perms[7] = 0xff;
perms[8] = (byte) 'F';
perms[9] = (byte) 'a';
perms[10] = (byte) 'd';
perms[11] = (byte) 'b';
Random rnd = new Random();
perms[12] = (byte) rnd.Next(0, 0xff);// The random salt for example
perms[13] = (byte) rnd.Next(0, 0xff);// The random salt for example
perms[14] = (byte) rnd.Next(0, 0xff);// The random salt for example
perms[15] = (byte) rnd.Next(0, 0xff);// The random salt for example
for (var index = 0; index < perms.Length; index++)
{
perms[index] ^= 123;
}
return perms;
}
///
/// Called to initialize the current instance for encryption.
/// Note that when encrypting, it will be filled with the data of the transferred properties , and when opening the document from the encryption dictionary.
/// If the method is called during new encryption, then and will be null.
///
/// The encryption parameters.
public void Initialize(EncryptionParameters parameters)
{
_parameters = parameters;
}
}
```
--------------------------------
### Get Owner Key
Source: https://docs.aspose.com/pdf/net/custom-security-handler
Generates an encoded array for the owner key, which is written to the 'O' field of the encryption dictionary. This is used during PDF encryption setup.
```csharp
public byte[] GetOwnerKey(string userPassword, string ownerPassword)
{
byte[] bytes = Encoding.UTF8.GetBytes(ownerPassword);
int encKeyForUserPass = 0;
foreach (var b in bytes)
{
encKeyForUserPass += b;
}
```
--------------------------------
### Get All Attachments from PDF (.NET 8)
Source: https://docs.aspose.com/pdf/net/extract-and-save-an-attachment
This .NET 8 example demonstrates how to extract and save all attachments from a PDF. It utilizes the `Aspose.Pdf.Document` class and iterates through `EmbeddedFiles` to process each attachment.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetAllAttachments()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Attachments();
// Open PDF document
using var document = new Aspose.Pdf.Document(dataDir + "GetAlltheAttachments.pdf");
// Get embedded files collection
Aspose.Pdf.EmbeddedFileCollection embeddedFiles = document.EmbeddedFiles;
// Get count of the embedded files
Console.WriteLine("Total files : {0}", embeddedFiles.Count);
int count = 1;
// Loop through the collection to get all the attachments
foreach (Aspose.Pdf.FileSpecification fileSpecification in embeddedFiles)
{
Console.WriteLine("Name: {0}", fileSpecification.Name);
Console.WriteLine("Description: {0}",
fileSpecification.Description);
Console.WriteLine("Mime Type: {0}", fileSpecification.MIMEType);
// Check if parameter object contains the parameters
if (fileSpecification.Params != null)
{
Console.WriteLine("CheckSum: {0}",
fileSpecification.Params.CheckSum);
Console.WriteLine("Creation Date: {0}",
fileSpecification.Params.CreationDate);
Console.WriteLine("Modification Date: {0}",
fileSpecification.Params.ModDate);
Console.WriteLine("Size: {0}", fileSpecification.Params.Size);
}
// Get the attachment and write to file or stream
var fileContent = new byte[fileSpecification.Contents.Length];
fileSpecification.Contents.Read(fileContent, 0, fileContent.Length);
using var fileStream = new FileStream(dataDir + count + "_out" + ".txt", FileMode.Create);
fileStream.Write(fileContent, 0, fileContent.Length);
count += 1;
}
}
```
--------------------------------
### Build and Run .NET Project
Source: https://docs.aspose.com/pdf/net/installation
Execute these commands to restore dependencies, build your .NET project, and run the application.
```bash
dotnet restore
dotnet build
dotnet run
```
--------------------------------
### Create Simple PDF Document using C#
Source: https://docs.aspose.com/pdf/net/create-pdf-document
Use this snippet to create a basic PDF document with 'Hello World!' text. Ensure Aspose.Pdf.Document and Aspose.Pdf.Text.TextFragment are imported.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void CreateHelloWorldDocument()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_QuickStart();
// Create PDF document
using (var document = new Aspose.Pdf.Document())
{
// Add page
var page = document.Pages.Add();
// Add text to new page
page.Paragraphs.Add(new Aspose.Pdf.Text.TextFragment("Hello World!"));
// Save PDF document
document.Save(dataDir + "HelloWorld_out.pdf");
}
}
```
--------------------------------
### Measure Text Width Dynamically with Aspose.PDF for .NET
Source: https://docs.aspose.com/pdf/net/add-text-to-pdf-file
Use the MeasureString method of Font or TextState classes to get the width of a string. This example demonstrates comparing measurements from both classes.
```csharp
Copy// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetTextWidthDynamically()
{
var font = Aspose.Pdf.Text.FontRepository.FindFont("Arial");
var textState = new Aspose.Pdf.Text.TextState();
textState.Font = font;
textState.FontSize = 14;
if (Math.Abs(font.MeasureString("A", 14) - 9.337) > 0.001)
{
Console.WriteLine("Unexpected font string measure!");
}
if (Math.Abs(textState.MeasureString("z") - 7.0) > 0.001)
{
Console.WriteLine("Unexpected font string measure!");
}
for (char c = 'A'; c <= 'z'; c++)
{
double fontMeasure = font.MeasureString(c.ToString(), 14);
double textStateMeasure = textState.MeasureString(c.ToString());
if (Math.Abs(fontMeasure - textStateMeasure) > 0.001)
{
Console.WriteLine("Font and state string measuring doesn't match!");
}
}
}
```
--------------------------------
### Create New .NET Console Project
Source: https://docs.aspose.com/pdf/net/installation
Use these commands to create a new .NET console application and navigate into its directory.
```bash
# Create a new console application
dotnet new console -n AsposePDFNetDemo
# Navigate into the project directory
cd AsposePDFNetDemo
```
--------------------------------
### Set and Get Alternative Text for PDF Image (.NET 8)
Source: https://docs.aspose.com/pdf/net/get-set-alt-text
This example demonstrates setting and retrieving alternative text for an image in a PDF using Aspose.PDF for .NET. It utilizes the TrySetAlternativeText and GetAlternativeText methods.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetSetAlternativeTextForImage()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Images();
// Open PDF document
using var document = new Aspose.Pdf.Document(dataDir + "SearchAndGetImages.pdf");
// Alternative text to be given to the image
string altText = "Alternative text for image";
// Image for which alternative text will be set and get
XImage xImage = document.Pages[1].Resources.Images[1];
// Try to set alternative text for an image
bool result = xImage.TrySetAlternativeText(altText, document.Pages[1]);
// If set is successful, then get the alternative text for the image
if (result)
{
List altTexts = xImage.GetAlternativeText(document.Pages[1]);
}
// Save PDF document
document.Save(dataDir + "SearchAndGetImagesWithAltText_out.pdf");
}
```
--------------------------------
### Get Bookmark Page Number in .NET 8
Source: https://docs.aspose.com/pdf/net/get-update-and-expand-bookmark
This example shows how to extract bookmark details, including page numbers, from a PDF using PdfBookmarkEditor in .NET 8. It utilizes the 'using var' syntax for resource management.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetBookmarkPageNumber()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Bookmarks();
// Create PdfBookmarkEditor
using var bookmarkEditor = new Aspose.Pdf.Facades.PdfBookmarkEditor();
// Bind PDF document
bookmarkEditor.BindPdf(dataDir + "GetBookmarks.pdf");
// Extract bookmarks
Aspose.Pdf.Facades.Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks();
foreach (var bookmark in bookmarks)
{
string strLevelSeparator = string.Empty;
for (int i = 1; i < bookmark.Level; i++)
{
strLevelSeparator += "---- ";
}
Console.WriteLine("{0}Title: {1}", strLevelSeparator, bookmark.Title);
Console.WriteLine("{0}Page Number: {1}", strLevelSeparator, bookmark.PageNumber);
Console.WriteLine("{0}Page Action: {1}", strLevelSeparator, bookmark.Action);
}
}
```
--------------------------------
### Generate Image Descriptions with .NET Core 3.1
Source: https://docs.aspose.com/pdf/net/ai-copilot
Demonstrates creating an OpenAI client, configuring ImageDescriptionCopilot options, and using the copilot to get image descriptions for attached documents. Includes an extension method to add descriptions to documents and save them.
```csharp
Copy// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static async Task CreateImageDescriptions()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_AI();
// Create AI client
using (var openAiClient = Aspose.Pdf.AI.OpenAIClient
.CreateWithApiKey(ApiKey) // Create OpenAI client with the API key
//.WithProject("proj_123") // Configure optional parameters
//.WithOrganization("org_123")
.Build()) // Build
{
// Create copilot options
var options = Aspose.Pdf.AI.OpenAIImageDescriptionCopilotOptions
.Create() // Create options like this, or...
//.Create(options => { options.Model = OpenAIModels.Gpt4Turbo; }) // ...create using delegate
.WithModel(Aspose.Pdf.AI.OpenAIModels.Gpt4Turbo) // The model should have vision capabilities
.WithTemperature(0.5)
.WithTopP(1)
.WithDocument(new Aspose.Pdf.AI.PdfDocument // Attach documents
{
Name = "Another_Pdf_with_images",
Document = new Aspose.Pdf.Document(dataDir + "Pdf_with_images.pdf")
})
.WithDocument(dataDir + "Mona_liza.jpg"); // Attach images
//.WithDocument("Pdf_with_images.pdf"); // Attach document paths
// Create copilot
var copilot = Aspose.Pdf.AI.AICopilotFactory.CreateImageDescriptionCopilot(openAiClient, options);
// Get Image descriptions
List imageDescriptions = await copilot.GetImageDescriptionsAsync();
// Use extension method to add image descriptions to attached documents
await copilot.AddPdfImageDescriptionsAsync(dataDir);
}
}
```
--------------------------------
### Get Tagged PDF Content (.NET Core 3.1)
Source: https://docs.aspose.com/pdf/net/extract-tagged-content-from-tagged-pdfs
Use the TaggedContent property of the Document class to access and set properties for tagged PDF content. This example shows how to set the title and language for a PDF document.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetTaggedContent()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();
// Create PDF Document
using (var document = new Aspose.Pdf.Document())
{
// Get Content for work with Tagged PDF
Aspose.Pdf.Tagged.ITaggedContent taggedContent = document.TaggedContent;
// Work with Tagged PDF content
// Set Title and Language for Document
taggedContent.SetTitle("Simple Tagged Pdf Document");
taggedContent.SetLanguage("en-US");
// Save Tagged PDF Document
document.Save(dataDir + "TaggedPDFContent_out.pdf");
}
}
```
--------------------------------
### Create and Populate PDF Table from DataTable (.NET 8)
Source: https://docs.aspose.com/pdf/net/render-table-from-the-data-source
This .NET 8 example demonstrates creating a PDF, configuring a table's appearance and dimensions, retrieving data from a SQL database into a DataTable, and then importing this data into the PDF table. It requires a 'config.json' file with a 'connectionString'.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void AddTable()
{
// Create PDF document
using var document = new Aspose.Pdf.Document
{
PageInfo = new Aspose.Pdf.PageInfo { Margin = new Aspose.Pdf.MarginInfo(28, 28, 28, 42) }
};
var table = new Aspose.Pdf.Table
{
// Set column widths of the table
ColumnWidths = "25% 25% 25% 25%",
// Set cell padding
DefaultCellPadding = new Aspose.Pdf.MarginInfo(10, 5, 10, 5), // Left Bottom Right Top
// Set the table border color as Green
Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.Green),
// Set the border for table cells as Black
DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .2f, Aspose.Pdf.Color.Green),
};
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", false)
.Build();
var connectionString = configuration.GetSection("connectionString").Value;
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentException("No connection string in config.json");
}
var resultTable = new DataTable();
using var conn = new SqlConnection(connectionString);
const string sql = "SELECT * FROM Tennats";
using var cmd = new SqlCommand(sql, conn);
using var adapter = new SqlDataAdapter(cmd);
adapter.Fill(resultTable);
table.ImportDataTable(resultTable, true, 1, 1);
// Add table object to first page of input document
document.Pages[1].Paragraphs.Add(table);
using var streamOut = new MemoryStream();
// Save PDF document
document.Save(streamOut);
return new FileContentResult(streamOut.ToArray(), "application/pdf")
{
PageInfo = new Aspose.Pdf.PageInfo { Margin = new Aspose.Pdf.MarginInfo(28, 28, 28, 42) }
};
}
```
--------------------------------
### Extract Image from an Image Stamp (.NET 8)
Source: https://docs.aspose.com/pdf/net/extract-image-and-change-position-of-a-stamp
This .NET 8 example shows how to extract an image from an image stamp using PdfContentEditor. It involves binding the PDF, getting stamp details, and saving the extracted image.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ExtractImageFromStamp()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdfFacades_StampsWatermarks();
// Instantiate PdfContentEditor object
using var pdfContentEditor = new Aspose.Pdf.Facades.PdfContentEditor();
// Bind PDF document
pdfContentEditor.BindPdf(dataDir + "ExtractImage-ImageStamp.pdf");
// Get Stamp info for the first stamp
var infos = pdfContentEditor.GetStamps(1);
// Get the image from Stamp Info
var image = infos[0].Image;
// Save the extracted image
image.Save(dataDir + "image_out.jpg");
}
```
--------------------------------
### Get PDF 2.0 Metadata using XMP in .NET 8
Source: https://docs.aspose.com/pdf/net/pdf-file-metadata
Access PDF 2.0 metadata via the Metadata property using 'xmp:' prefixes. This example is compatible with .NET 8 and utilizes modern C# syntax.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetPdf20Metadata()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF 2.0 document
using var document = new Aspose.Pdf.Document(dataDir + "Pdf20Document.pdf");
var metadata = document.Metadata;
// Get standard metadata fields from XMP
var title = metadata["xmp:Title"]?.ToString();
var author = metadata["xmp:Author"]?.ToString();
var subject = metadata["xmp:Subject"]?.ToString();
var keywords = metadata["xmp:Keywords"]?.ToString();
var creator = metadata["xmp:Creator"]?.ToString();
var producer = metadata["xmp:Producer"]?.ToString();
Console.WriteLine($"Title: {title}");
Console.WriteLine($"Author: {author}");
Console.WriteLine($"Subject: {subject}");
Console.WriteLine($"Keywords: {keywords}");
Console.WriteLine($"Creator: {creator}");
Console.WriteLine($"Producer: {producer}");
// You can also access custom metadata
if (metadata.ContainsKey("xmp:CustomKey"))
{
var customValue = metadata["xmp:CustomKey"]?.ToString();
Console.WriteLine($"Custom Key: {customValue}");
}
}
```
--------------------------------
### Generate Image Descriptions with .NET 8
Source: https://docs.aspose.com/pdf/net/ai-copilot
Demonstrates creating an OpenAI client, configuring ImageDescriptionCopilot options, and using the copilot to get image descriptions for attached documents. Includes an extension method to add descriptions to documents and save them.
```csharp
Copy// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static async Task CreateImageDescriptions()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_AI();
// Create AI client
using var openAiClient = Aspose.Pdf.AI.OpenAIClient
.CreateWithApiKey(ApiKey) // Create OpenAI client with the API key
//.WithProject("proj_123") // Configure optional parameters
//.WithOrganization("org_123")
.Build(); // Build
// Create copilot options
var options = Aspose.Pdf.AI.OpenAIImageDescriptionCopilotOptions
.Create() // Create options like this, or...
//.Create(options => { options.Model = OpenAIModels.Gpt4Turbo; }) // ...create using delegate
.WithModel(Aspose.Pdf.AI.OpenAIModels.Gpt4Turbo) // The model should have vision capabilities
.WithTemperature(0.5)
.WithTopP(1)
.WithDocument(new Aspose.Pdf.AI.PdfDocument // Attach documents
{
Name = "Another_Pdf_with_images",
Document = new Aspose.Pdf.Document(dataDir + "Pdf_with_images.pdf")
})
.WithDocument(dataDir + "Mona_liza.jpg"); // Attach images
//.WithDocument(dataDir + "Pdf_with_images.pdf"); // Attach document paths
// Create copilot
var copilot = Aspose.Pdf.AI.AICopilotFactory.CreateImageDescriptionCopilot(openAiClient, options);
// Get Image descriptions
List imageDescriptions = await copilot.GetImageDescriptionsAsync();
// Use extension method to add image descriptions to attached documents
await copilot.AddPdfImageDescriptionsAsync(dataDir);
}
```
--------------------------------
### Add Grouped Checkbox Fields to PDF (.NET Core 3.1)
Source: https://docs.aspose.com/pdf/net/create-form
Use this code to add grouped checkbox fields to a PDF document. Ensure Aspose.PDF for .NET is installed. This example configures the appearance and border styles of the radio buttons.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void AddGroupedCheckBoxFieldsToPdf()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_Forms();
// Create PDF document
using (var document = new Aspose.Pdf.Document())
{
// Add page to PDF file
var page = document.Pages.Add();
var radioButtonField = new Aspose.Pdf.Forms.RadioButtonField(page);
// Add radio button options and specify its position using Rectangle
var opt1 = new Aspose.Pdf.Forms.RadioButtonOptionField(page, new Aspose.Pdf.Rectangle(50, 500, 70, 520));
var opt2 = new Aspose.Pdf.Forms.RadioButtonOptionField(page, new Aspose.Pdf.Rectangle(100, 500, 120, 520));
// Set option names for identification
opt1.OptionName = "Option1";
opt2.OptionName = "Option2";
// Set the style of the radio buttons
opt1.Style = Aspose.Pdf.Forms.BoxStyle.Square;
opt2.Style = Aspose.Pdf.Forms.BoxStyle.Cross;
// Configure the border of the first radio button
opt1.Border = new Aspose.Pdf.Annotations.Border(opt1);
opt1.Border.Style = Aspose.Pdf.Annotations.BorderStyle.Dashed;
opt1.Border.Width = 1;
opt1.Characteristics.Border = System.Drawing.Color.Blue;
// Configure the border of the second radio button
opt2.Border = new Aspose.Pdf.Annotations.Border(opt2);
opt2.Border.Style = Aspose.Pdf.Annotations.BorderStyle.Solid;
opt2.Border.Width = 1;
opt2.Characteristics.Border = System.Drawing.Color.Black;
radioButtonField.Add(opt1);
radioButtonField.Add(opt2);
// Add radio button field to the form object of the document
document.Form.Add(radioButtonField);
// Save PDF document
document.Save(dataDir + "GroupedCheckboxFields_out.pdf");
}
}
```
--------------------------------
### Get XMP Metadata from PDF using Aspose.PDF for .NET
Source: https://docs.aspose.com/pdf/net/get-xmp-metadata-of-an-existing-pdf-file
Use the PdfXmpMetadata class to bind a PDF and access its XMP metadata properties. Ensure the Aspose.Pdf.Facades namespace is imported. This example demonstrates accessing default and custom XMP properties.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetXmpMetadata()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdfFacades_WorkingDocuments();
// Create PdfXmpMetadata object
using (var xmpMetaData = new Aspose.Pdf.Facades.PdfXmpMetadata())
{
// Bind PDF document
xmpMetaData.BindPdf(dataDir + "GetXMPMetadata.pdf");
// Get XMP Meta Data properties
Console.WriteLine(": {0}", xmpMetaData[Aspose.Pdf.Facades.DefaultMetadataProperties.CreateDate].ToString());
Console.WriteLine(": {0}", xmpMetaData[Aspose.Pdf.Facades.DefaultMetadataProperties.MetadataDate].ToString());
Console.WriteLine(": {0}", xmpMetaData[Aspose.Pdf.Facades.DefaultMetadataProperties.CreatorTool].ToString());
Console.WriteLine(": {0}", xmpMetaData["customNamespace:UserPropertyName"].ToString());
Console.ReadLine();
}
}
```
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void GetXmpMetadata()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdfFacades_WorkingDocuments();
// Create PdfXmpMetadata object
using var xmpMetaData = new Aspose.Pdf.Facades.PdfXmpMetadata();
// Bind PDF document
xmpMetaData.BindPdf(dataDir + "GetXMPMetadata.pdf");
// Get XMP Meta Data properties
Console.WriteLine(": {0}", xmpMetaData[Aspose.Pdf.Facades.DefaultMetadataProperties.CreateDate].ToString());
Console.WriteLine(": {0}", xmpMetaData[Aspose.Pdf.Facades.DefaultMetadataProperties.MetadataDate].ToString());
Console.WriteLine(": {0}", xmpMetaData[Aspose.Pdf.Facades.DefaultMetadataProperties.CreatorTool].ToString());
Console.WriteLine(": {0}", xmpMetaData["customNamespace:UserPropertyName"].ToString());
Console.ReadLine();
}
```
--------------------------------
### Create Project Structure
Source: https://docs.aspose.com/pdf/net/converting-documents-with-microsoft-azure-app-service
Create the necessary directories and files for your project structure in Visual Studio Code.
```bash
mkdir Controllers
touch Controllers/PdfController.cs
```
--------------------------------
### Generate PDF Summary with OpenAI ( .NET 8)
Source: https://docs.aspose.com/pdf/net/ai-copilot
Demonstrates how to create an OpenAI client, configure summary copilot options, and generate/save PDF summaries using the Aspose.PDF AI Copilot API in .NET 8.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static async Task GetSummary()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_AI();
// Create AI client
using var openAiClient = Aspose.Pdf.AI.OpenAIClient
.CreateWithApiKey(ApiKey) // Create OpenAI client with the API key
//.WithProject("proj_123") // Configure optional parameters
.Build();
// Create copilot options
var options = Aspose.Pdf.AI.OpenAISummaryCopilotOptions
.Create() // Create options like this, or...
//.Create(options => { options.Model = OpenAIModels.Gpt35Turbo; }) // ...create using delegate
.WithTemperature(0.5) // Configure other optional parameters
.WithDocument("SampleDocument.pdf"); // .WithDocument methods allows to add text, pdf and paths to documents
//.WithDocuments(new List { new Aspose.Pdf.AI.TextDocument() }); // .WithDocuments methods allows to add text, pdf and path collections
// Create summary copilot
Aspose.Pdf.AI.ISummaryCopilot summaryCopilot = Aspose.Pdf.AI.AICopilotFactory.CreateSummaryCopilot(openAiClient, options);
// Get summary text
string summaryText = await summaryCopilot.GetSummaryAsync();
// Get summary document
Aspose.Pdf.Document summaryDocument = await summaryCopilot.GetSummaryDocumentAsync();
// Get summary document with page info
Aspose.Pdf.Document summaryDocumentWithPageInfo = await summaryCopilot.GetSummaryDocumentAsync(new Aspose.Pdf.PageInfo());
// Save PDF document
await summaryCopilot.SaveSummaryAsync(dataDir + "Summary_out.pdf");
}
```
--------------------------------
### Singleton Implementation for Metered License Management
Source: https://docs.aspose.com/pdf/net/licensing
Ensures a stable licensing setup by applying the license once at application startup using a singleton pattern. Periodically checks license status and reapplies if invalid.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
public class AsposeLicenseManager
{
private static AsposeLicenseManager _instance;
private static readonly object _lock = new object();
private Aspose.Pdf.Metered _metered;
private AsposeLicenseManager()
{
_metered = new Aspose.Pdf.Metered();
_metered.SetMeteredKey("your-public-key", "your-private-key");
}
public static AsposeLicenseManager Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new AsposeLicenseManager();
}
return _instance;
}
}
}
public void ValidateLicense()
{
if (!Aspose.Pdf.License.IsMeteredLicensed())
{
_metered.SetMeteredKey("your-public-key", "your-private-key");
}
}
}
```
--------------------------------
### Create and Use OpenAI Chat Copilot
Source: https://docs.aspose.com/pdf/net/ai-copilot
Demonstrates creating an OpenAI client, configuring ChatCopilot options, and using it to interact with user queries and manage context. Ensure you have the API key and necessary data files.
```csharp
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static async Task ChatWithDocument()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_AI();
// Create AI client
using (var openAiClient = Aspose.Pdf.AI.OpenAIClient
.CreateWithApiKey(ApiKey) // Create OpenAI client with the API key
//.WithProject("proj_123") // Configure optional parameters
//.WithOrganization("org_123")
.Build()) // Build
{
// Create copilot options
var options = Aspose.Pdf.AI.OpenAIChatCopilotOptions
.Create() // Create options like this, or...
//.Create(options => { options.Model = OpenAIModels.Gpt35Turbo; }) // ...create using delegate
.WithModel(Aspose.Pdf.AI.OpenAIModels.Gpt35Turbo) // Configure other optional parameters
.WithTemperature(0.5)
.WithTopP(1)
//.WithContextBackupJsonPath("ContextBackup.json") // Supply context backup to resume the conversation session
//.WithRestoreContextFromBackup(true) // If set to true, the context will be restored
.WithDocument(dataDir + "SampleDocument.pdf"); // Attach documents using .WithDocument(s) methods allows to add text, pdf and paths to documents
// Create summary copilot
Aspose.Pdf.AI.IChatCopilot chatCopilot = Aspose.Pdf.AI.AICopilotFactory.CreateChatCopilot(openAiClient, options);
// Get response on a user query
string copilotResponse1 = await chatCopilot.GetResponseAsync("Summarize this document.");
// Get response on a list of queries
string copilotResponse2 = await chatCopilot.GetResponseAsync(new List
{
"What is the subject of this document?",
"How many words in it?"
});
// Save PDF document
await chatCopilot.SaveResponseAsync("Summarize this document.", dataDir + "ResponseDocument1_out.pdf");
// Save PDF document
await chatCopilot.SaveResponseAsync(new List
{
"What is the subject of this document?",
"How many words in it?"
},
dataDir + "ResponseDocument2_out.pdf");
// Save context (ids of assistant, thread, documents)
await chatCopilot.SaveContextAsync(dataDir + "ContextBackup.json");
// Deletes the context
await chatCopilot.DeleteContextAsync();
}
}
```
--------------------------------
### XML Data Example
Source: https://docs.aspose.com/pdf/net/generate-pdf-from-xml
This is an example XML structure representing a catalog of CDs. It serves as the input data for XSLT transformation.
```xml
Empire Burlesque
Bob Dylan
USA
Columbia
10.90
1985
Hide your heart
Bonnie Tyler
UK
CBS Records
9.90
1988
Greatest Hits
Dolly Parton
USA
RCA
9.90
1982
Still got the blues
Gary Moore
UK
Virgin records
10.20
1990
Eros
Eros Ramazzotti
EU
BMG
9.90
1997
One night only
Bee Gees
UK
Polydor
10.90
1998
Sylvias Mother
Dr.Hook
UK
CBS
8.10
1973
Maggie May
Rod Stewart
UK
Pickwick
8.50
1990
Romanza
Andrea Bocelli
EU
Polydor
10.80
1996
When a man loves a woman
Percy Sledge
USA
Atlantic
8.70
1987
Black angel
Savage Rose
EU
Mega
10.90
1995
1999 Grammy Nominees
Many
USA
Grammy
10.20
1999
For the good times
Kenny Rogers
UK
Mucik Master
8.70
1995
Big Willie style
Will Smith
USA
Columbia
9.90
1997
Tupelo Honey
Van Morrison
UK
Polydor
8.20
1971
Soulsville
Jorn Hoel
Norway
WEA
7.90
1996
The very best of
Cat Stevens
UK
Island
8.90
1990
Stop
Sam Brown
UK
A and M
8.90
1988
Bridge of Spies
T`Pau
UK
Siren
7.90
1987
Private Dancer
Tina Turner
UK
Capitol
8.90
1983
Midt om natten
Kim Larsen
EU
Medley
7.80
1983
Pavarotti Gala Concert
Luciano Pavarotti
UK
DECCA
9.90
1991
The dock of the bay
Otis Redding
USA
Stax Records
7.90
1968
Picture book
Simply Red
EU
Elektra
7.20
1985
Red
The Communards
UK
London
7.80
1987
Unchain my heart
Joe Cocker
USA
EMI
8.20
1987
```