Zum Fußzeileninhalt springen
IRONPDF NUTZEN

Wie man ChatGPT mit IronPDF für C#-Entwickler verwendet

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 a 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 account creation form.
  • 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 written 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

This command will install the OpenAI package, which provides access to the API needed for interacting with ChatGPT using C#.

2.5 Install IronPDF

Enter the following command to install the IronPDF package:

Install-Package IronPdf

The command above installs IronPDF into the MAUI project. IronPDF is used for rendering HTML content into PDF files and is a key part of exporting data from the app to a PDF document.

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 HTML-to-PDF conversion 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"); // Replace with your actual OpenAI API key
    options.DefaultModel = OpenAIChatGptModels.Gpt35Turbo; // Set the default model
    options.MessageLimit = 10; // Limit number of messages per session
    options.MessageExpiration = TimeSpan.FromMinutes(5); // Set message expiration time
});
builder.Services.AddChatGpt(options =>
{
    options.UseOpenAI("API key here"); // Replace with your actual OpenAI API key
    options.DefaultModel = OpenAIChatGptModels.Gpt35Turbo; // Set the default model
    options.MessageLimit = 10; // Limit number of messages per session
    options.MessageExpiration = TimeSpan.FromMinutes(5); // Set message expiration time
});
builder.Services.AddChatGpt(Sub(options)
	options.UseOpenAI("API key here") ' Replace with your actual OpenAI API key
	options.DefaultModel = OpenAIChatGptModels.Gpt35Turbo ' Set the default model
	options.MessageLimit = 10 ' Limit number of messages per session
	options.MessageExpiration = TimeSpan.FromMinutes(5) ' Set message expiration time
End Sub)
$vbLabelText   $csharpLabel

This code snippet registers a service for the ChatGPT API, which can then be used by other classes or pages in your application.

Add the following code on the main page of the application in the page load method. This helps to get the ChatGPT service instance 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)()
$vbLabelText   $csharpLabel

This code retrieves the ChatGPT client instance from the service provider, allowing the main page to interact with the ChatGPT API.

Next, create a user interface like the one depicted in the following XAML code:

<?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 can be populated with dynamic data -->
                    </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="Send 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 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 can be populated with dynamic data -->
                    </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="Send 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 ContentPage above defines the UI layout of the application. Users can enter queries, interact with the ChatGPT API via the "Send Query" button, and export the results as a PDF using the "Export" button. Results are displayed in TableView.

Next is the code-behind logic for handling button clicks and exporting data:

private void OnExportClicked(object sender, EventArgs e)
{
    StringBuilder db = new();

    foreach (var tableSection in Table_View.Root.ToList())
    {
        foreach (var cell in tableSection)
        {
            if (cell is TextCell textCell)
            {
                db.Append("<p style='color:red;text-align:left;'>" + textCell.Text + "</p>");
                db.Append("<p style='color:black;text-align:justify;'>" + textCell.Detail + "</p>");
            }
        }
    }

    // Create and save the PDF
    var renderer = new IronPdf.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))
    {
        var query = Userquest.Text;
        Userquest.Text = "";
        var tableSection = AddQueryToTable(query);
        ChatGptResponse response = await _chatGptClient.AskAsync(_sessionGuid, query);
        var resp = response.GetMessage();
        AddResponseToTable(tableSection, resp);
    }
}

private TableSection AddQueryToTable(string query)
{
    var textCell = new TextCell
    {
        Text = query,
        TextColor = Colors.Red,
        DetailColor = Colors.WhiteSmoke,
        Detail = ""
    };

    var tableSection = new TableSection { textCell };
    Table_View.Root.Add(tableSection);
    return tableSection;
}

private void AddResponseToTable(TableSection section, string response)
{
    if (section.FirstOrDefault() is TextCell textCell)
    {
        textCell.Detail = response;
    }
}
private void OnExportClicked(object sender, EventArgs e)
{
    StringBuilder db = new();

    foreach (var tableSection in Table_View.Root.ToList())
    {
        foreach (var cell in tableSection)
        {
            if (cell is TextCell textCell)
            {
                db.Append("<p style='color:red;text-align:left;'>" + textCell.Text + "</p>");
                db.Append("<p style='color:black;text-align:justify;'>" + textCell.Detail + "</p>");
            }
        }
    }

    // Create and save the PDF
    var renderer = new IronPdf.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))
    {
        var query = Userquest.Text;
        Userquest.Text = "";
        var tableSection = AddQueryToTable(query);
        ChatGptResponse response = await _chatGptClient.AskAsync(_sessionGuid, query);
        var resp = response.GetMessage();
        AddResponseToTable(tableSection, resp);
    }
}

private TableSection AddQueryToTable(string query)
{
    var textCell = new TextCell
    {
        Text = query,
        TextColor = Colors.Red,
        DetailColor = Colors.WhiteSmoke,
        Detail = ""
    };

    var tableSection = new TableSection { textCell };
    Table_View.Root.Add(tableSection);
    return tableSection;
}

private void AddResponseToTable(TableSection section, string response)
{
    if (section.FirstOrDefault() is TextCell textCell)
    {
        textCell.Detail = response;
    }
}
Private Sub OnExportClicked(ByVal sender As Object, ByVal e As EventArgs)
	Dim db As New StringBuilder()

	For Each tableSection In Table_View.Root.ToList()
		For Each cell In tableSection
			Dim tempVar As Boolean = TypeOf cell Is TextCell
			Dim textCell As TextCell = If(tempVar, CType(cell, TextCell), Nothing)
			If tempVar Then
				db.Append("<p style='color:red;text-align:left;'>" & textCell.Text & "</p>")
				db.Append("<p style='color:black;text-align:justify;'>" & textCell.Detail & "</p>")
			End If
		Next cell
	Next tableSection

	' Create and save the PDF
	Dim renderer = New IronPdf.ChromePdfRenderer()
	Dim pdf = renderer.RenderHtmlAsPdf(db.ToString())
	pdf.SaveAs("F:\Download\Demo.pdf")
End Sub

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

Private Function AddQueryToTable(ByVal query As String) As TableSection
	Dim textCell As New TextCell With {
		.Text = query,
		.TextColor = Colors.Red,
		.DetailColor = Colors.WhiteSmoke,
		.Detail = ""
	}

	Dim tableSection As New TableSection From {textCell}
	Table_View.Root.Add(tableSection)
	Return tableSection
End Function

Private Sub AddResponseToTable(ByVal section As TableSection, ByVal response As String)
	Dim tempVar As Boolean = TypeOf section.FirstOrDefault() Is TextCell
	Dim textCell As TextCell = If(tempVar, CType(section.FirstOrDefault(), TextCell), Nothing)
	If tempVar Then
		textCell.Detail = response
	End If
End Sub
$vbLabelText   $csharpLabel

Explanation:

  • The OnExportClicked method creates a PDF from HTML content gathered from the UI using IronPDF. The generated PDF is saved to a specified location.

  • The SendqueryClicked method takes the user's query, sends it to the OpenAI API using the _chatGptClient, and displays the response. It also adds the query and response to TableView.

  • Helper methods AddQueryToTable and AddResponseToTable assist in updating the UI components with user queries and chatbot responses.

After adding the above code, try to run your solution. Enter a query and retrieve the result by clicking the "Send Query" button. It will send the user's query to the ChatGPT API, retrieve the result, and display the message on the screen.

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.

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 a MAUI App. Using the above concept, it is possible to include images, audio, and video from the ChatGPT API for more accurate results.

5.0 Conclusion

The goal of this article is to develop a 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 IronPDF licensing page.

Häufig gestellte Fragen

Wie kann ich ChatGPT mit einer .NET MAUI-Anwendung integrieren?

Um ChatGPT mit einer .NET MAUI-Anwendung zu integrieren, richten Sie zunächst ein OpenAI-Konto ein und erhalten einen API-Schlüssel. Installieren Sie dann das OpenAI-Paket in Ihrem Projekt über NuGet und konfigurieren Sie die API in Ihrer Anwendung zur Bearbeitung von Benutzerabfragen.

Wie konvertiere ich API-Ergebnisse in einer MAUI-App in PDF?

Sie können API-Ergebnisse in einer MAUI-App mithilfe von IronPDF in PDF konvertieren. Nachdem Sie Antworten von der ChatGPT-API erhalten haben, verwenden Sie die Methoden von IronPDF, um den HTML-Inhalt als PDF zu rendern.

Welche Schritte sind beim Einrichten einer ChatGPT-basierten MAUI-App beteiligt?

Um eine ChatGPT-basierte MAUI-App einzurichten, erstellen Sie ein neues .NET MAUI-Projekt in Visual Studio, installieren Sie die OpenAI- und IronPDF-Pakete, konfigurieren Sie die API-Einstellungen in Ihrem Code und schreiben Sie die Logik zur Bearbeitung von Anfragen und Ausgabe als PDF.

Kann IronPDF HTML-, JavaScript- und CSS-Inhalte beim Erstellen von PDFs verarbeiten?

Ja, IronPDF kann HTML-, JavaScript- und CSS-Inhalte beim Erstellen von PDFs verarbeiten. Es verwendet die Chrome-Rendering-Engine, um HTML-Inhalt in ein PDF-Dokument zu konvertieren.

Ist es möglich, die ChatGPT-API-Einstellungen in meiner Anwendung anzupassen?

Ja, Sie können die ChatGPT-API-Einstellungen in Ihrer Anwendung anpassen, indem Sie Parameter wie Modelltypen, Nachrichtenlimits und Ablaufzeiten in der Datei MauiProgram.cs einstellen.

Welche Vorteile bietet die Verwendung von IronPDF in einer MAUI-Anwendung?

IronPDF bietet ein robustes SDK zum Erstellen, Lesen und Bearbeiten von PDFs. Es ermöglicht die Konvertierung von HTML-Inhalten in PDFs, unterstützt die Textextraktion und bietet verschiedene Funktionen zur Verbesserung der PDF-Behandlung in einer MAUI-Anwendung.

Gibt es eine kostenlose Testversion für IronPDF?

Ja, IronPDF bietet eine kostenlose Testversion, die Entwicklern die Möglichkeit gibt, seine Funktionen und Möglichkeiten zu erkunden, bevor sie sich für einen Lizenzplan entscheiden.

Wie installiere ich die notwendigen Pakete für ein ChatGPT-PDF-Projekt in MAUI?

Verwenden Sie die NuGet Package Manager-Konsole in Visual Studio, um die OpenAI- und IronPDF-Pakete zu installieren. Führen Sie Install-Package OpenAI und Install-Package IronPDF aus, um sie zu Ihrem Projekt hinzuzufügen.

Welche Rolle spielt IronPDF beim Umgang mit PDF-Dokumenten?

IronPDF wird zum Erstellen, Bearbeiten und Konvertieren von PDF-Dokumenten verwendet. Es ermöglicht Entwicklern, Webinhalte in PDFs zu konvertieren, Textsuchen durchzuführen und Bilder zu extrahieren, was es ideal für Anwendungen macht, die PDF-Funktionen erfordern.

Ist IronPDF vollständig mit .NET 10 kompatibel?

Ja, IronPDF ist vollständig kompatibel mit .NET 10. Es unterstützt alle wichtigen .NET-Versionen – einschließlich .NET 10, 9, 8, 7, 6, Core und .NET Framework – und ist so konzipiert, dass es in .NET 10-Projekten ohne spezielle Konfiguration sofort einsatzbereit ist.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen