C# Czytaj plik PDF: Łatwy przewodnik
Jeśli jesteś programistą, prawdopodobnie napotkałeś problemy podczas próby odczytania tekstu z pliku PDF. Być może dotyczy Cię jedna lub więcej z poniższych sytuacji:
- Tworzysz aplikację, która pobiera dwa dokumenty PDF jako dane wejściowe i wyszukuje podobieństwa między nimi.
- Tworzysz aplikację, która musi odczytywać dokumenty PDF za pomocą IronPDF i zwracać liczbę słów.
- Tworzysz aplikację, która pobiera dane z pliku PDF przy użyciu IronPDF i umieszcza je w ustrukturyzowanej bazie danych.
- Tworzysz aplikację, która musi wyodrębnić treść tekstową z pliku PDF i przekształcić ją w ciąg znaków.
- Pobieranie danych z plików PDF przy użyciu języka C# było trudnym i złożonym zadaniem aż do momentu opracowania biblioteki IronPDF.
Przegląd biblioteki IronPDF to biblioteka, która znacznie ułatwia programistom odczytywanie plików PDF.
Możesz dowiedzieć się więcej o IronPDF i ofercie pakietu Iron Software Suite.
Możesz odczytywać pliki PDF i wyświetlać dane w polu tekstowym C# za pomocą zaledwie dwóch linii kodu. Tak, wystarczą tylko dwie linijki kodu. Można również wyodrębnić wszystkie obrazy z plików PDF. Ponadto możesz utworzyć inny dokument z tymi obrazami lub wyświetlić je w swojej aplikacji zgodnie z własnymi wymaganiami.
Pokażemy Ci, jak to się robi.
Możemy postępować krok po kroku, korzystając z aplikacji, aby wybrać dowolne pliki PDF, a następnie wyświetlić ich zawartość.
Poniższe kroki pokazują, jak odczytywać pliki PDF w języku C#:
Poniższe kroki pokazują, jak odczytywać pliki PDF w języku C#
- Pobierz bibliotekę Print to PDF C#
- Wybierz plik PDF z komputera
- Wybierz konkretną drukarkę do druku i ustaw rozdzielczość
- Sprawdź wydruk PDF z drukarki
- Track your printing processes using C#
Prerequisite Knowledge:
- Basic Knowledge of C# Programming
- Basic Knowledge of C# GUI Controls
I have designed this tutorial in such a way that even a person with no programming background will be able to progress.
Who should read this
Any newcomer learning C# should know how to read PDF files using IronPDF because this is something you are definitely going to use in your career.
Professional developers should also read this to be able to understand the IronPDF Library, which helps us to read, generate, and manipulate PDF documents.
Now, how can we use this Library in our Project to read a PDF file?
I am using a Windows Forms App for demonstration. You can use a Console Application, a WPF Application, or an ASP.NET web application according to your preference.
Another major advantage of the IronPDF library is that it can be used with both C# and VB.NET.
Let's begin the demonstration without further delay.
Step #1: Create a Visual Studio Project
Otwórz program Visual Studio. I am using Visual Studio 2019.
Click on "Create New Project":
Create New Project
Now, select the Windows Forms App from the template, press "Next", and the following window will appear. Enter a project name. I have written 'Read Pdf using IronPDF'.
Configure project via Visual Studio
Now, click "Next", and the following window will appear. Select '.NET Core 3.1' from the drop-down menu.
.NET Core 3.1 version
Click on the "Create" button, and the Project will be created as shown below.
Initial stage of a new Windows Forms application
Step #2: Install the IronPDF NuGet Package
Click on the Project Menu from the Menu Bar, and a drop-down list will appear. Select Manage NuGet Packages, and click on it. Pojawi się następujące okno:
Menedżer pakietów NuGet
Now, click on "Browse". Pojawi się następujące okno:
Interfejs użytkownika menedżera pakietów NuGet
Type IronPdf in the search box and press "Enter". Pojawi się następujące okno:
NuGet Solution
Select and click on IronPdf. Pojawi się następujące okno:
Install Free IronPdf
Press the "Install" button and wait for the installation to complete. The following window will appear after a successful installation:
IronPdf for .NET
Press the "Ok" button, and you are good to go.
Note: There are other ways to download the NuGet Package. You can also install IronPdf by using the Package Manager Console; to do this, open the Package Manager Console and write the following code:
Install-Package IronPdf
You can also download it on the NuGet package page for IronPDF.
The following Readme.txt file will open:
IronPdf's readme file with code samples
I suggest you go through all the links and explore more IronPDF code samples about this Library.
Step #3: Design a Windows Forms App
Once a Project is created and the NuGet Package is installed, the next step is to design a Windows Forms App that will ask the user to browse for a file and display its content.
Open Form1 Design:
Form1 Design UI
Click on the toolbar that is on the left-hand side of the window:
Toolbox UI for Label and TextBox
Search for "Label", and drag and drop it into the Form Design
Name the label. Here, I have named it "C# Read Pdf using IronPDF".
Form1 UI with Label added
Next, drag and drop one text box (to show the file path), three buttons (one for browsing the files, one for reading PDF files using IronPDF, and the third button for "Clear the Text" fields), and one RichTextBox (for reading and displaying the file contents).
Set the "Read Only Property" for the TextBox and RichTextBox to "False". This is so that users can only read the contents and file path.
Form1 fully designed
Step #4: Add the Back-end Code for Browsing PDF Files
Double-click on the "Browse" button, and the following window will appear:
private void Browse_Click(object sender, EventArgs e)
{
}
private void Browse_Click(object sender, EventArgs e)
{
}
Private Sub Browse_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Next, write the following code inside the Browse_Click function:
private void Browse_Click(object sender, EventArgs e)
{
// Initialize and configure OpenFileDialog
OpenFileDialog browseFile = new OpenFileDialog
{
InitialDirectory = @"D:\",
Title = "Browse Pdf Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "pdf",
Filter = "pdf files (*.pdf)|*.pdf",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
// Show the dialog and get result
if (browseFile.ShowDialog() == DialogResult.OK)
{
// Set the text box with the selected file path
FilePath.Text = browseFile.FileName;
}
}
private void Browse_Click(object sender, EventArgs e)
{
// Initialize and configure OpenFileDialog
OpenFileDialog browseFile = new OpenFileDialog
{
InitialDirectory = @"D:\",
Title = "Browse Pdf Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "pdf",
Filter = "pdf files (*.pdf)|*.pdf",
FilterIndex = 2,
RestoreDirectory = true,
ReadOnlyChecked = true,
ShowReadOnly = true
};
// Show the dialog and get result
if (browseFile.ShowDialog() == DialogResult.OK)
{
// Set the text box with the selected file path
FilePath.Text = browseFile.FileName;
}
}
Private Sub Browse_Click(ByVal sender As Object, ByVal e As EventArgs)
' Initialize and configure OpenFileDialog
Dim browseFile As New OpenFileDialog With {
.InitialDirectory = "D:\",
.Title = "Browse Pdf Files",
.CheckFileExists = True,
.CheckPathExists = True,
.DefaultExt = "pdf",
.Filter = "pdf files (*.pdf)|*.pdf",
.FilterIndex = 2,
.RestoreDirectory = True,
.ReadOnlyChecked = True,
.ShowReadOnly = True
}
' Show the dialog and get result
If browseFile.ShowDialog() = DialogResult.OK Then
' Set the text box with the selected file path
FilePath.Text = browseFile.FileName
End If
End Sub
OpenFileDialog creates an instance of the File Dialog control of the Windows Forms App.
I have set the Initial Path to D Drive; you can set it to any.
I have set DefaultExt = "pdf" as we only have to read the PDF file.
I have used a filter so that the browse file dialog will only show you the PDF file to select.
When the user clicks "Ok", it will show the file path in the File Path field.
Let us run the solution and test the "Browse" button.
Form1 UI
Press the "Browse" button and the following window will appear:
Browse File dialog to select a PDF file
Select the file (I am selecting IronPDFTest.pdf) and press "Open". Pojawi się następujące okno.
PDF in C#
Now let's write the code behind the "Read" button to read the file.
Step #5: Add the Back-end Code for Reading PDF Documents using IronPDF
You might be thinking that code for reading a PDF file would be complex and difficult to write and understand.
Don't worry. IronPDF has simplified things and made it all so much easier. We can easily read the PDF file using just two lines of code.
Go to Form1 Design and "double-click" on the "Read" button. Pojawi się następujące okno:
private void Read_Click(object sender, EventArgs e)
{
}
private void Read_Click(object sender, EventArgs e)
{
}
Private Sub Read_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Add a namespace using IronPdf to import the IronPDF library:
using System;
using IronPdf;
using System;
using IronPdf;
Imports System
Imports IronPdf
Write the following code inside the Read_Click function:
private void Read_Click(object sender, EventArgs e)
{
// Read the PDF file using IronPdf
using PdfDocument pdf = PdfDocument.FromFile(FilePath.Text);
// Extract and display the text from the PDF
FileContent.Text = pdf.ExtractAllText();
}
private void Read_Click(object sender, EventArgs e)
{
// Read the PDF file using IronPdf
using PdfDocument pdf = PdfDocument.FromFile(FilePath.Text);
// Extract and display the text from the PDF
FileContent.Text = pdf.ExtractAllText();
}
Private Sub Read_Click(ByVal sender As Object, ByVal e As EventArgs)
' Read the PDF file using IronPdf
Using pdf As PdfDocument = PdfDocument.FromFile(FilePath.Text)
' Extract and display the text from the PDF
FileContent.Text = pdf.ExtractAllText()
End Using
End Sub
FilePath is the name of the text field that displays the location of the PDF document we want to read. We will get the location of the file dynamically.
ExtractAllText with IronPDF is the IronPDF function that will extract all the data from PDF pages. This data will then be displayed in the Rich Text box and named as "File Content".
Next, let's write the code behind the "Clear Button". This is just an additional item if you wish to clear the screen once you have read the PDF document.
Double-click on the "Clear Button", and it will take you to the following code:
void Clear_Click(object sender, EventArgs e)
{
}
void Clear_Click(object sender, EventArgs e)
{
}
Private Sub Clear_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Write the following code inside the Clear_Click function:
void Clear_Click(object sender, EventArgs e)
{
// Clear the file path and content display fields
FileContent.Text = "";
FilePath.Text = "";
}
void Clear_Click(object sender, EventArgs e)
{
// Clear the file path and content display fields
FileContent.Text = "";
FilePath.Text = "";
}
Private Sub Clear_Click(ByVal sender As Object, ByVal e As EventArgs)
' Clear the file path and content display fields
FileContent.Text = ""
FilePath.Text = ""
End Sub
Run the Solution
Click on the "Browse" button and select the document you want to read. In my case, I am reading the IronPDF.pdf file as an example:
PDF documents
Press the "Open" button and the following window will appear:
Application with a selected PDF file
Press the "Read" button. It will read the file and display the content as shown below.
Display PDF text content
Podsumowanie
This is an example solution. No matter how many pages, images, or texts are in your PDF files, IronPDF will extract all the texts and images for you to use for any purpose. You simply need to get the license for the library and begin using it.
This completes the tutorial. I hope you have understood everything, and if you have any queries, feel free to post them in the comments section.
You can download the project zip file. If you wish to buy the complete package of Iron software products, our special offer means that you can now buy all of them for the price of just two Lite licenses.
Często Zadawane Pytania
Jak odczytać tekst z pliku PDF przy użyciu języka C#?
Możesz odczytać tekst z pliku PDF za pomocą IronPDF, korzystając z metody ExtractAllText, która pozwala w łatwy sposób wyodrębnić całą zawartość tekstową z dokumentu PDF.
Jakie są zalety korzystania z IronPDF do obróbki plików PDF w języku C#?
IronPDF oferuje proste podejście do odczytu, generowania i manipulowania plikami PDF w języku C#. Pozwala programistom wykonywać zadania, takie jak wyodrębnianie tekstu i pobieranie obrazów przy minimalnej liczbie linii kodu, poprawiając produktywność i wydajność.
Jak zainstalować bibliotekę IronPDF w moim projekcie C#?
Aby zainstalować IronPDF, użyj menedżera pakietów NuGet w Visual Studio. Po prostu wyszukaj „IronPdf” w konsoli menedżera pakietów i kliknij „Zainstaluj”, aby dodać go do swojego projektu.
Czy IronPDF może służyć do wyodrębniania obrazów z pliku PDF?
Tak, IronPDF oferuje funkcję wyodrębniania obrazów z pliku PDF, umożliwiając programistom dostęp do wszystkich obrazów zawartych w dokumencie oraz ich edycję.
Jakie kroki należy wykonać, aby skonfigurować projekt Visual Studio do odczytu plików PDF?
Konfiguracja projektu obejmuje utworzenie nowego projektu w Visual Studio, zainstalowanie pakietu IronPDF NuGet, zaprojektowanie aplikacji Windows Forms oraz wdrożenie kodu zaplecza do przeglądania i odczytu plików PDF.
Jak mogę zapewnić, że pola w mojej aplikacji zostaną wyczyszczone po odczytaniu pliku PDF?
W aplikacji można zaimplementować przycisk „Wyczyść”, który resetuje zawartość pól TextBox i RichTextBox do pustego ciągu znaków, zapewniając wyczyszczenie pól po przetworzeniu pliku PDF.
Czy można używać IronPDF z VB.NET?
Tak, IronPDF jest kompatybilny zarówno z C#, jak i VB.NET, co czyni go wszechstronnym rozwiązaniem dla programistów pracujących w różnych językach .NET.
Ile wierszy kodu jest potrzebnych do wyświetlenia treści PDF przy użyciu IronPDF?
Za pomocą IronPDF można wyświetlić zawartość pliku PDF za pomocą zaledwie dwóch wierszy kodu, co podkreśla jego zdolność do upraszczania zadań związanych z przetwarzaniem plików PDF.
Do czego służy metoda „RenderHtmlAsPdf” w IronPDF?
Metoda RenderHtmlAsPdf w IronPDF służy do konwersji ciągów znaków HTML na dokumenty PDF, umożliwiając płynną integrację treści internetowych z plikami PDF.
Czy IronPDF jest w pełni kompatybilny z .NET 10?
Tak. IronPDF został zaprojektowany tak, aby był w pełni kompatybilny z .NET 10, a także z wcześniejszymi wersjami, takimi jak .NET 6-9, .NET Core, .NET Standard i .NET Framework. Obsługuje instalację poprzez NuGet i działa płynnie na wielu platformach, w tym Windows, Linux i macOS.




