USING IRONPDF

How to Use ChatGPT with IronPDF For C# Developer

Updated March 17, 2024
Share:

1.0 What is ChatGPT?

ChatGPT is an artificial intelligence (AI) chatbot created by OpenAI. The term "ChatGPT" combines the words "Chat," which alludes to the chatbot feature of the system, and "GPT," which stands for Generative Pre-trained Transformer and is a kind of large language model (LLM). The fundamental GPT models from OpenAI, namely GPT-3.5 and GPT-4, serve as the basis for ChatGPT, which has been refined (a method of transfer learning) for conversational applications utilizing a combination of supervised and reinforcement learning techniques, which includes machine learning, natural language processing, and artificial intelligence. ChatGPT can understand and generate human-like text.

This article will demonstrate how to develop an MAUI application that makes use of the OpenAI ChatGPT API to take messages, offer results based on user queries, and then export those results as a PDF file for later usage using IronPDF.

1.1 Setup OpenAI account

To register for an OpenAI account, do the following:

  • Visit the official OpenAI website.
  • On the website's home page, locate and click the Sign-Up button. This will take you to the page where you create an account.
  • Complete the sign-up form's essential fields.
  • Click on the verification link issued to your registered email account to confirm your email address.
  • If your registration is successful, you should be able to access your OpenAI account by entering the login information you gave when registering.

1.2 Getting an OpenAI API key

  • To access OpenAI, go to the website and log in with your account information.

    How to Use ChatGPT with IronPDF For C# Developer, Figure 1: Access OpenAI website Access OpenAI website

  • Navigate to the OpenAI platform's API area. Then Account Settings > View API key where you may find this.
  • Now you can create a New secret API key.

    How to Use ChatGPT with IronPDF For C# Developer, Figure 2: Create API keys Create API keys

2.0 Getting Started with .NET MAUI Application

You need Visual Studio 2022 and .NET 7 Framework installed for creating the .NET MAUI application writing in C#. Then, follow the next steps to create and write a .NET MAUI app.

2.1 Open Visual Studio

Open Visual Studio, then select "Create a New Project" from the menu and enter ".NET MAUI" into the search field.

2.2 Choose the .NET MAUI App

In Visual Studio, choose the .NET MAUI app template from the list of search results. After choosing it, give it a decent name and choose the project's location. Click "Next" after the configuration is complete.

How to Use ChatGPT with IronPDF For C# Developer, Figure 3: Create a new .NET MAUI App in Visual Studio Create a new .NET MAUI App in Visual Studio

2.3 Select Framework

Choose the necessary framework; nevertheless, for example, it is advised to choose the most recent .NET Framework. Press the Create button in Visual Studio after choosing the framework version.

How to Use ChatGPT with IronPDF For C# Developer, Figure 4: Configure the new project Configure the new project

In Visual Studio 2022, a new .NET MAUI Project will be created. .NET MAUI by default develops a straightforward counter application.

How to Use ChatGPT with IronPDF For C# Developer, Figure 5: .NET Framework selection .NET Framework selection

By modifying the .NET MAUI application, the ChatGPT OpenAI can be integrated and export the result into PDF files using the IronPDF C# PDF library on this variant of platforms.

2.4 Install the OpenAI Package

Enter the next command into the NuGet Package Manager Console.

Install-Package OpenAI

Enter the above line of code into the Package Manager Console, which will help to install the package OpenAI.

Install-Package IronPdf

The code above helps to install the IronPDF into the MAUI code.

3.0 What is IronPDF?

Developers can swiftly create, read, and edit PDF documents thanks to IronPDF, a robust PDF SDK foundation for PDF processing. The Chrome engine is used by the IronPDF library to convert HTML to PDF. Among the several web components that the library supports are MAUI, Xamarin, Blazor, Unity, HoloLens apps, Windows Forms, HTML, ASPX, Razor HTML, .NET Core, ASP.NET, and WPF. Microsoft.NET and.NET Core programming can be used in both traditional Windows Applications and ASP.NET web apps.

Using HTML5, JavaScript, CSS, and images, IronPDF enables you to create attractive PDFs that have a title and footer. The API library includes a robust HTML-to-PDF converter that can deal with PDFs as well as a stand-alone PDF conversion tool and engine that is independent of any outside sources.

To know more about the IronPDF, refer to the tutorial pages.

4.0 Export ChatGPT API Result using IronPDF

Add the below code in the "MauiProgram.cs" file:

builder.Services.AddChatGpt(options =>
    {
        options.UseOpenAI("API key here");
        options.DefaultModel = OpenAIChatGptModels.Gpt35Turbo; 
        options.MessageLimit = 10;
        options.MessageExpiration = TimeSpan.FromMinutes(5); 
    }
);
builder.Services.AddChatGpt(options =>
    {
        options.UseOpenAI("API key here");
        options.DefaultModel = OpenAIChatGptModels.Gpt35Turbo; 
        options.MessageLimit = 10;
        options.MessageExpiration = TimeSpan.FromMinutes(5); 
    }
);
builder.Services.AddChatGpt(Sub(options)
		options.UseOpenAI("API key here")
		options.DefaultModel = OpenAIChatGptModels.Gpt35Turbo
		options.MessageLimit = 10
		options.MessageExpiration = TimeSpan.FromMinutes(5)
End Sub)
VB   C#

This helps to create a service for the ChatGPT API Then it can be retrieved and used by the other classes/pages.

Add the below on the main page of the application in the page load method. This helps to get the ChatGPT service instant and store it into a local object.

_chatGptClient = Handler.MauiContext.Services.GetService<IChatGptClient>();
_chatGptClient = Handler.MauiContext.Services.GetService<IChatGptClient>();
_chatGptClient = Handler.MauiContext.Services.GetService(Of IChatGptClient)()
VB   C#

Then create UI for the user interface like the below image.

How to Use ChatGPT with IronPDF For C# Developer, Figure 6: UI of the MAUI App UI of the MAUI App

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                x:Class="ChatGPT_MauiApp.MainPage"
            BackgroundColor="black">
    <StackLayout>
        <StackLayout Orientation="Horizontal"  Spacing="25"
            Padding="30,0">
            <ScrollView WidthRequest="700" HeightRequest="200" x:Name="scrollView">
        <TableView Intent="Data" WidthRequest="700" x:Name="Table_View"  BackgroundColor="DarkSlateGrey">
                    <TableRoot>
                        <!--<TableSection >
                            --><!--<TextCell Text="test" Detail="test">
                            </TextCell>--><!--
                        </TableSection>-->
                    </TableRoot>
            </TableView>
    </ScrollView>
    </StackLayout>
        <StackLayout Padding="30,0">
            <Editor
                x:Name="Userquest"
                Text=""
                HorizontalOptions="Start"
                FontSize="12"
                Placeholder=" Enter your Queries"
                HeightRequest="25" WidthRequest="700"

                />
        </StackLayout>
        <StackLayout Padding="30,10,10,0">
        <FlexLayout >
            <Button
                x:Name="Sendquery"
                Text="Sent Query"
                SemanticProperties.Hint="Click to send query to BOT"
                Clicked="SendqueryClicked"
                HorizontalOptions="Center" 
                BackgroundColor="Green"
                TextColor="WhiteSmoke"

                />
                <Button
                x:Name="Export"
                Text="Export"
                SemanticProperties.Hint="click to export data"
                Clicked="OnExportClicked"
                HorizontalOptions="Center" 
                BackgroundColor="DodgerBlue"
                TextColor="WhiteSmoke"
                />
            </FlexLayout>
        </StackLayout>

    </StackLayout>
</ContentPage>
XML

The above code helps to design and implement the UI page. On the design page, the text box allows the user to enter the query. Once they enter the text they need to, when they click the button, a query will be sent which interacts with the ChatGPT API and produces the result. The result will be displayed in Tableview.

As the demo ChatGPT version, the service prevents no more than 3 requests per minute. The UI also has a button called "export" which will allow exporting the User query and ChatGPT API reply into a PDF document which can be used in the future for reference.

The code samples below is used for exporting to Excel.

private void OnExportClicked(object sender, EventArgs e)
{
    celldata = null;
    db = new StringBuilder();
    foreach (var table_section in Table_View.Root.ToList().Select(s => new TableSection { s }).ToList())
    {
        if (table_section.Count > 0)
        {
            celldata = null;
            celldata = table_section.Select(s => (Microsoft.Maui.Controls.TextCell)s).FirstOrDefault();
            db.Append("<p style='color:red;text-align:left;'>" + celldata.Text + "</p>");
            db.Append("<p style='color:black;text-align:justify;'>" + celldata.Detail + "</p>");
        }
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(db.ToString());
        pdf.SaveAs("F:\\Download\\Demo.pdf");
    }
}

private async void SendqueryClicked(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Userquest.Text.ToString()))
    {
        var query = Userquest.Text;
        Userquest.Text = "";
        var tablesec = SetGetTextCell(query);
        ChatGptResponse response = await _chatGptClient.AskAsync(_sessionGuid, query);
        var resp = response.GetMessage();
        tablesec.Detail = resp.ToString();
    }
}

private Microsoft.Maui.Controls.TextCell SetGetTextCell(string Setvalue)
{
    celldata = null;
    if (!string.IsNullOrEmpty(Setvalue))
    {
        celldata = new TextCell
        {
            Text = Setvalue,
            TextColor = Colors.Red,
            DetailColor = Colors.WhiteSmoke,
            Detail = ""
        };
        Table_View.Root.Add(new TableSection()
            {
                celldata
            });
    }
    return celldata;
}
private void OnExportClicked(object sender, EventArgs e)
{
    celldata = null;
    db = new StringBuilder();
    foreach (var table_section in Table_View.Root.ToList().Select(s => new TableSection { s }).ToList())
    {
        if (table_section.Count > 0)
        {
            celldata = null;
            celldata = table_section.Select(s => (Microsoft.Maui.Controls.TextCell)s).FirstOrDefault();
            db.Append("<p style='color:red;text-align:left;'>" + celldata.Text + "</p>");
            db.Append("<p style='color:black;text-align:justify;'>" + celldata.Detail + "</p>");
        }
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf(db.ToString());
        pdf.SaveAs("F:\\Download\\Demo.pdf");
    }
}

private async void SendqueryClicked(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(Userquest.Text.ToString()))
    {
        var query = Userquest.Text;
        Userquest.Text = "";
        var tablesec = SetGetTextCell(query);
        ChatGptResponse response = await _chatGptClient.AskAsync(_sessionGuid, query);
        var resp = response.GetMessage();
        tablesec.Detail = resp.ToString();
    }
}

private Microsoft.Maui.Controls.TextCell SetGetTextCell(string Setvalue)
{
    celldata = null;
    if (!string.IsNullOrEmpty(Setvalue))
    {
        celldata = new TextCell
        {
            Text = Setvalue,
            TextColor = Colors.Red,
            DetailColor = Colors.WhiteSmoke,
            Detail = ""
        };
        Table_View.Root.Add(new TableSection()
            {
                celldata
            });
    }
    return celldata;
}
Private Sub OnExportClicked(ByVal sender As Object, ByVal e As EventArgs)
	celldata = Nothing
	db = New StringBuilder()
	For Each table_section In Table_View.Root.ToList().Select(Function(s) New TableSection From {s}).ToList()
		If table_section.Count > 0 Then
			celldata = Nothing
			celldata = table_section.Select(Function(s) CType(s, Microsoft.Maui.Controls.TextCell)).FirstOrDefault()
			db.Append("<p style='color:red;text-align:left;'>" & celldata.Text & "</p>")
			db.Append("<p style='color:black;text-align:justify;'>" & celldata.Detail & "</p>")
		End If
		Dim renderer = New ChromePdfRenderer()
		Dim pdf = renderer.RenderHtmlAsPdf(db.ToString())
		pdf.SaveAs("F:\Download\Demo.pdf")
	Next table_section
End Sub

Private Async Sub SendqueryClicked(ByVal sender As Object, ByVal e As EventArgs)
	If Not String.IsNullOrEmpty(Userquest.Text.ToString()) Then
		Dim query = Userquest.Text
		Userquest.Text = ""
		Dim tablesec = SetGetTextCell(query)
		Dim response As ChatGptResponse = Await _chatGptClient.AskAsync(_sessionGuid, query)
		Dim resp = response.GetMessage()
		tablesec.Detail = resp.ToString()
	End If
End Sub

Private Function SetGetTextCell(ByVal Setvalue As String) As Microsoft.Maui.Controls.TextCell
	celldata = Nothing
	If Not String.IsNullOrEmpty(Setvalue) Then
		celldata = New TextCell With {
			.Text = Setvalue,
			.TextColor = Colors.Red,
			.DetailColor = Colors.WhiteSmoke,
			.Detail = ""
		}
		Table_View.Root.Add(New TableSection() From {celldata})
	End If
	Return celldata
End Function
VB   C#

On retrieving the input data one by one using the for loop, then add the HTML string into the string to format the display text. Then IronPDF can be used to export the results into PDF and save them in a desired location.

After adding the above code, try the run the solution. Then enter the query and retrieve the result by clicking the button "send query". It will send the user a query to retrieve the result and display the message on the screen like the below image.

How to Use ChatGPT with IronPDF For C# Developer, Figure 7: Add text query into the application Add text query into the application

Click on the export button to export results into a PDF like the image below.

How to Use ChatGPT with IronPDF For C# Developer, Figure 8: The exported PDF file The exported PDF file

Now, we were able to create a chatbot using ChatGPT and export that chat using IronPDF on MAUI App. Using the above concept, it is possible to include images, Audio, and video from ChatGPT API for more accurate results.

5.0 Conclusion

The goal of this article is to develop an MAUI application that makes use of the OpenAI ChatGPT API to take messages, offer results based on user queries, and export those results as a PDF file. To improve the caliber of the suggestions, feel free to explore by altering the questions. To see if various models produce better results, you can also experiment with modifying the ChatGptModels enum value within the AddChatGpt method in "MauiProgram.cs".

The ChatGPT API is a powerful AI program that allows us to provide results based on the user query. The cost for ChatGPT API is calculated based on the number of requests sent. IronPDF is used to make API requests and export the result into PDF for future uses, avoiding repeatedly querying the same API request.

We can create PDFs using only a few lines of code with IronPDF. This application is suitable for beginners and only requires fundamental knowledge to use. No other package is dependent on IronPDF in any way. For instance, it is a library that comes in a single package. IronPDF Developers can choose from a variety of licenses to suit their requirements. There is also a free trial available. For complete pricing and licensing information about IronPDF, kindly refer to the licensing page.

< PREVIOUS
How to Use Fluent Validation With IronPDF in C#
NEXT >
How to Create PDF Signatures in .NET

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >