푸터 콘텐츠로 바로가기
IRONPDF 사용

How to Open a PDF File in C#

As one of the most popular formats for digital documents, PDF allows users to generate invoices, print bank statements, and so much more. PDFs also allow users to sign documents digitally, as well as provide secure authentication. Learn about IronPDF abilities for creating, reading, and editing PDFs with ease. In this article, we are going to generate a PDF file in C# using IronPDF's C# integration and read the PDF using Acrobat Reader/Adobe Reader. We are also going to read the PDF file in C# using IronPDF.

How to Open PDF in C#

  1. Open Visual Studio and install the IronPdf NuGet Package
  2. Adding references to the code - enabling the use of available classes and functions
  3. Declare a common object for ChromePdfRenderer
  4. Using the RenderHtmlAsPdf function
  5. Using System.Diagnostics.Process.Start

1. Open Visual Studio and Install the NuGet Package

Open Visual Studio and go to the "File menu." Select "New Project," then select Console Application/Windows Forms/WPF Application. IronPDF can be used on all applications. You can also use it in apps such as Webform, MVC/MVC Core.

How to Open a PDF File in C#, Figure 1: Create a new project in Visual Studio Create a new project in Visual Studio

Enter the project name and select the file path in the appropriate text box. Then click the "Create" button. Next, select the required .NET Framework. Now the project will generate the structure for the selected application. If you have selected the console application, it will now open the Program.cs file where you can enter the code and build/run the application.

How to Open a PDF File in C#, Figure 2: Configure .Net project in Visual Studio Configure .Net project in Visual Studio

Next Install NuGet Package Install IronPdf from NuGet

Left-click the project and a menu will pop up. Select NuGet Package Manager from the menu and search for IronPDF. Select the first result in the NuGet Package dialog and click the Install/Download option.

How to Open a PDF File in C#, Figure 3: Install IronPdf package in NuGet Package Manager Install IronPdf package in NuGet Package Manager

Alternatively:

In Visual Studio go to Tools -> NuGet Package Manager -> Package Manager Console

Enter the following code on the Package Manager Console tab.

Install-Package IronPdf

Now the package will download/install on the current project and it is ready to use in the code.

2. Adding Reference to the Code - Enabling the use of available classes and functions

Add the reference IronPdf to the code as shown below. This will allow us to use the class and functions available from IronPdf in our code.

3. Declare a Common Object for ChromePdfRenderer

Declaring a common object for ChromePdfRenderer from IronPDF will help you convert any web page or HTML snippet into a PDF using IronPDF. By creating a common object, we will be able to use it without creating any more objects of the same class, allowing us to reuse the code more than once. Multiple functions can be used to create PDF files with IronPDF. We can use strings, transform URLs into PDF, or HTML files and convert them into PDFs, which can then be saved to the desired location.

We can also use a static function without creating any object for the ChromePdfRenderer. The static function is as follows:

We can use any one of these static methods to generate a PDF file. We can also include setting various PDF document options such as margins, titles, DPI, headers, footers, text, etc. By using ChromePdfRenderOptions, we can pass parameters to any one of these static methods.

We can declare the ChromePdfRenderOptions as common or individual for every PDF document. It is very simple and easy to use. We are going to use any one of the non-static functions to generate a PDF file and save it to a default location.

4. Using the RenderHtmlAsPdf

We can use any one of the above IronPDF functions to create a PDF. If you are using the function name RenderHtmlAsPdf, then pass any string as a parameter and then use the SaveAs Pdf file option from IronPDF function to save the PDF at the desired file path. While using the SaveAs function, we need to pass the filename and location as parameters, or if we are using a Windows application, we can use the SaveAs dialog to save the PDF file to the desired location. With the help of an HTML string, we can format the PDF document. Also, we can use CSS for designing text in PDF via HTML, and we can use any HTML tag to design a PDF document, as IronPDF does not have any restrictions on using HTML tags.

When we use large HTML text, it is difficult to add all the HTML text to the text box, so we can use another method which we have referred to above as RenderHtmlFileAsPdf, which will help us to convert all the HTML into a PDF document. With this method, we can add large HTML files. Also, we can include an external CSS file in these HTML files, as well as external images, etc.

IronPDF also helps us print data from any links using the RenderUrlAsPdf function. This function processes the link to generate a PDF and saves the PDF files to the desired file path using the SaveAs function. This IronPDF function will include the CSS and all the images available on the site.

The following code shows an example of the IronPDF function.

using IronPdf; // Ensure you add the IronPdf namespace

// Create an instance of the ChromePdfRenderer class
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render a PDF from a simple HTML string
PdfDocument pdf = renderer.RenderHtmlAsPdf("Hello IronPdf");

// Specify the path where the resulting PDF will be saved
var outputPath = "DemoIronPdf.pdf";

// Save the PDF document to the specified path
pdf.SaveAs(outputPath);

// Open the resulting PDF document using the default associated application
System.Diagnostics.Process.Start(outputPath);
using IronPdf; // Ensure you add the IronPdf namespace

// Create an instance of the ChromePdfRenderer class
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render a PDF from a simple HTML string
PdfDocument pdf = renderer.RenderHtmlAsPdf("Hello IronPdf");

// Specify the path where the resulting PDF will be saved
var outputPath = "DemoIronPdf.pdf";

// Save the PDF document to the specified path
pdf.SaveAs(outputPath);

// Open the resulting PDF document using the default associated application
System.Diagnostics.Process.Start(outputPath);
$vbLabelText   $csharpLabel

This example shows how we can use the IronPDF function to generate a PDF file from a string. In this code, we have created an instance object for the ChromePdfRenderer, and then by using the instance object with the help of RenderHtmlAsPdf, we generate the PDF file. Then, by using the SaveAs IronPDF function, we can save the PDF file on the given path. If we don't specify a file path, it will be saved at the execution location in the program.

5. Using System.Diagnostics.Process.Start to Preview the PDF file

For this last step, we are using System.Diagnostics.Process.Start to preview a PDF file. This function invokes the command line function to open the PDF file from the path. If we have a PDF reader, it will open the saved PDF file in the reader. If we do not have a PDF reader, it will open with a dialog, and from the dialog, we need to select the program to open the PDF.

How to Open a PDF File in C#, Figure 4: The PDF file displayed in a default PDF Reader The PDF file displayed in a default PDF Reader

We can read PDF files using IronPDF, and this will read the PDF document line-by-line. We are even able to open a password-restricted PDF file using IronPDF. The following code demonstrates how to read a PDF document.

using IronPdf; // Ensure you add the IronPdf namespace

// Open a password-protected PDF
PdfDocument pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Extract all text from the PDF document
string allText = pdf.ExtractAllText();

// Extract all images from the PDF document
IEnumerable<System.Drawing.Image> allImages = pdf.ExtractAllImages();

// Iterate through each page in the document
for (var index = 0; index < pdf.PageCount; index++)
{
    // Page numbers are typically 1-based, so add 1 to the index
    int pageNumber = index + 1;

    // Extract text from the current page
    string text = pdf.ExtractTextFromPage(index);

    // Extract images from the current page
    IEnumerable<System.Drawing.Image> images = pdf.ExtractImagesFromPage(index);
}
using IronPdf; // Ensure you add the IronPdf namespace

// Open a password-protected PDF
PdfDocument pdf = PdfDocument.FromFile("encrypted.pdf", "password");

// Extract all text from the PDF document
string allText = pdf.ExtractAllText();

// Extract all images from the PDF document
IEnumerable<System.Drawing.Image> allImages = pdf.ExtractAllImages();

// Iterate through each page in the document
for (var index = 0; index < pdf.PageCount; index++)
{
    // Page numbers are typically 1-based, so add 1 to the index
    int pageNumber = index + 1;

    // Extract text from the current page
    string text = pdf.ExtractTextFromPage(index);

    // Extract images from the current page
    IEnumerable<System.Drawing.Image> images = pdf.ExtractImagesFromPage(index);
}
$vbLabelText   $csharpLabel

The above code shows how we can read PDF files using IronPDF. IronPDF first reads the PDF document from the entered string filename, and it also allows users to include a password if there is one. It will read all the lines. This is very useful when we need to get data from a PDF, as it reduces the amount of manual work and does not require any human supervision.

Check out our code samples on PDF security and password handling.

Conclusion

IronPDF provides a simple and easy way to create a PDF with straightforward steps. The IronPDF library can be used in various environments such as Windows Forms, mobile apps, and web apps using .NET Framework or .Net Core's latest version. We don't need a separate library for each platform. We only need IronPDF to generate the PDF.

IronPDF offers a free trial key and you can currently buy five products from Iron Software for a bundled price package.

You can download a C# file project to help get started with IronPdf.

자주 묻는 질문

C#으로 PDF를 생성하려면 어떻게 해야 하나요?

IronPDF를 사용하면 HTML 문자열 또는 파일을 PDF 형식으로 변환하는 RenderHtmlAsPdf 메서드를 활용하여 C#으로 PDF를 생성할 수 있습니다. 그런 다음 SaveAs 메서드를 사용하여 PDF를 저장할 수 있습니다.

C# 프로젝트에서 IronPDF를 설정하려면 어떤 단계를 따라야 하나요?

C# 프로젝트에서 IronPDF를 설정하려면 Visual Studio의 NuGet 패키지 관리자를 통해 IronPdf NuGet 패키지를 설치합니다. 그런 다음 코드에 필요한 참조를 추가하고 IronPDF의 클래스와 메서드를 사용하여 PDF 조작을 시작하세요.

C#에서 PDF 파일을 열려면 어떻게 하나요?

IronPDF를 사용하여 C#에서 PDF 파일을 열려면 먼저 IronPDF의 메서드를 사용하여 PDF 문서를 로드한 다음 기본 PDF 리더로 PDF를 실행하는 System.Diagnostics.Process.Start로 PDF를 볼 수 있습니다.

IronPDF는 암호로 보호된 PDF 파일을 처리할 수 있나요?

예, IronPDF는 비밀번호로 보호된 PDF 파일을 처리할 수 있습니다. IronPDF의 기능을 사용하여 파일을 열 때 비밀번호를 제공해야만 보안 PDF 문서에 액세스하고 조작할 수 있습니다.

C#을 사용하여 PDF에서 텍스트를 추출하려면 어떻게 하나요?

C#을 사용하여 PDF에서 텍스트를 추출하려면 PDF 문서에서 텍스트 콘텐츠를 검색하여 반환하는 IronPDF의 ExtractAllText 메서드를 사용할 수 있습니다.

C#으로 생성된 PDF에 CSS 스타일을 추가할 수 있나요?

네, 가능합니다. IronPDF를 사용하면 PDF로 변환하는 HTML 콘텐츠에 CSS 스타일을 통합하여 PDF에 추가할 수 있으므로 풍부한 서식과 디자인을 구현할 수 있습니다.

IronPDF를 사용한 PDF 조작은 어떤 환경에서 지원되나요?

IronPDF는 .NET Framework와 .NET Core로 개발된 Windows Forms, 모바일 앱, 웹 앱 등 여러 환경을 지원하여 애플리케이션 개발의 유연성을 제공합니다.

구매하기 전에 IronPDF를 어떻게 사용해 볼 수 있나요?

IronPDF는 무료 평가판을 제공합니다. 평가판 키를 사용하여 구매를 결정하기 전에 IronPDF의 기능을 살펴볼 수 있습니다.

C#에서 PDF를 생성할 때 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 HTML에서 PDF로의 변환, 암호 보호, 콘텐츠 추출과 같은 강력한 기능을 제공하여 C#에서 PDF를 생성하는 프로세스를 간소화하여 .NET 애플리케이션에서 PDF 처리를 간소화합니다.

C#으로 생성된 PDF를 저장하지 않고 미리 보려면 어떻게 해야 하나요?

생성된 PDF를 저장하지 않고 C#에서 미리 보려면 IronPDF를 사용하여 PDF를 생성한 다음 System.Diagnostics.Process.Start를 사용하여 기본 PDF 리더 애플리케이션으로 PDF를 바로 열 수 있습니다.

.NET 10 호환성: IronPDF는 .NET 10 프로젝트를 지원하나요?

예 - IronPDF는 .NET 10과 완벽하게 호환됩니다. HTML-PDF 변환, URL 렌더링 및 ChromePdfRenderer에서 제공하는 모든 기능을 포함하여 .NET 10 프로젝트에서 즉시 사용할 수 있습니다. .NET 10 애플리케이션에서 IronPDF를 작동시키기 위해 추가 구성이 필요하지 않습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.