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

PDF Conversion in C# (Developer Tutorial)

PDF Conversion in C# (Developer Tutorial)

IronPDF lets you convert documents to PDF in C# applications with just a few lines of code. It handles HTML-to-PDF and image-to-PDF transformations seamlessly across Windows, Linux, and macOS platforms.

This article shows you how PDF conversion works using IronPDF, the PDF library for .NET and .NET Core. Whether you're working on Windows, Linux, or macOS, IronPDF provides cross-platform support for all your PDF needs. The library offers comprehensive documentation and tutorials to help you get started quickly.

What is IronPDF?

  1. PDF Generation: Easily create PDF documents programmatically in C# from various sources, including HTML, images, text, and existing files.
  2. HTML to PDF Conversion: Convert HTML content into PDFs, including web pages or HTML templates, into high-quality PDFs with full control over styling and formatting.
  3. Image to PDF Conversion: Convert image files (such as JPEG, PNG, or BMP) into PDF documents, allowing for easy integration of images into PDF reports and documents.
  4. PDF Manipulation: Comprehensive PDF editing capabilities, including text extraction from PDFs, merging and splitting PDFs, and rotation, as well as adding, modifying, or removing content and annotations.
  5. PDF Forms: Create, fill, and extract data from PDF forms, making it suitable for applications that require interactive forms and data collection.

Whether you need to generate PDFs from scratch, convert HTML pages, images, or existing documents into PDF format, or manipulate existing PDFs, IronPDF offers straightforward APIs to accomplish these tasks. The library uses a Chrome rendering engine to ensure your HTML conversions look exactly as they should. For a complete list of capabilities, check out the IronPDF Features Overview website.

  1. PDF Generation: Create PDFs programmatically from HTML, images, text, and files. Supports custom sizes, orientation, and margins. Handles international languages too.
  2. HTML to PDF Conversion: Convert HTML to PDF with full styling. Supports CSS media, JavaScript, and web fonts. Works with WebGL and responsive designs.
  3. Image to PDF Conversion: Convert JPEG, PNG, or BMP files to PDF. Supports TIFF conversion and SVG graphics. Can embed images with DataURIs.
  4. PDF Manipulation: Edit PDFs with text extraction, merging/splitting, and annotations. Also redact text, add stamps, and manage metadata.
  5. PDF Forms: Create and fill PDF forms. Supports creating and editing forms. Can flatten PDFs to static content.

How Do I Create a New Visual Studio Project?

Before diving into code, let's set up a new C# Console Application project. If you're new to .NET development, you might find the quickstart guide helpful for additional setup tips. F# developers can also use IronPDF with functional programming approaches.

  1. Open Visual Studio and create a new project by clicking File > New > Project.

    Visual Studio File menu expanded showing various options including New Project, Clone Repository, Open File/Project, and Save options with keyboard shortcuts The File menu in Visual Studio provides quick access to essential project management functions, from creating new projects to cloning repositories from version control systems.

  2. A new window appears. Select the Console Application template and click Next at the bottom. This template is perfect for learning PDF basics before moving to complex project types like Blazor applications or ASP.NET MVC.

    Visual Studio's 'Create a new project' dialog showing Console Application template selected for creating a .NET Core command-line application that supports Windows, Linux, and macOS. The Console Application template in Visual Studio provides a starting point for creating cross-platform command-line applications using .NET Core.

  3. In the next window, name your project and choose a location, then click Next. Consider organizing projects in a dedicated folder for easy access to code examples and sample files.

    Visual Studio's 'Configure your new project' dialog showing setup for a Console Application named 'PDF Conversion' with project location and solution settings. Step 2: Configuring the new Console Application project with appropriate naming and location settings for the PDF conversion application.

  4. Select your target framework and click Create. For modern applications, use .NET 6 or later for best performance and support. Recent versions offer improved performance and async capabilities.

    Visual Studio project creation dialog showing 'Additional information' page with .NET 5.0 selected as the target framework for a Console Application. The final step in creating a new Console Application in Visual Studio, where you select the target framework. Note that .NET 5.0 is marked as 'Out of support' - consider using .NET 6.0 or .NET 8.0 for current projects.

Your project is ready. Let's install IronPDF.

How Do I Install IronPDF?

IronPDF offers several installation methods. We'll use the NuGet Package Manager here. You can explore advanced installation methods for specific scenarios, including Windows Installer options and Linux configurations.

  1. In Visual Studio, open the Tools menu and hover over NuGet Package Manager.
  2. Click Manage NuGet Packages for Solutions.

    Visual Studio Tools menu expanded showing NuGet Package Manager submenu with options for Package Manager Console, Manage NuGet Packages for Solution, and Package Manager Settings The Tools menu in Visual Studio provides access to NuGet Package Manager features, which are essential for managing external libraries and dependencies in .NET projects

  3. A new window appears. Click the Browse tab and search for "IronPDF".
  4. Select IronPDF and click Install. For smaller deployments, consider IronPdf.Slim.
  5. You can also install via Package Manager Console:

    Install-Package IronPdf

Or download directly from the IronPDF NuGet page. For containers, see the Docker deployment guide or run IronPDF as a remote container.

How Do I Convert Files to PDF Using IronPDF?

Let's explore converting different document formats to PDF. IronPDF provides extensive rendering options for customizing output, including custom logging and performance monitoring.

  1. HTML Files to PDF Documents
  2. Image to PDF Documents

How Do I Convert HTML Files to PDF?

Converting HTML to PDF is incredibly straightforward with IronPDF. The library supports advanced features like headers and footers, page breaks, and custom CSS. You can handle Bootstrap layouts and implement cookie management for authenticated content.

Here's how to convert an HTML file into a PDF:

using IronPdf;

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

// Optional: Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;

// Enable JavaScript execution for dynamic content
renderer.RenderingOptions.EnableJavaScript = true;

// Set print CSS media type for proper formatting
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;

// Add custom headers for authenticated content
renderer.RenderingOptions.CustomCssUrl = "___PROTECTED_URL_142___";

// Configure viewport for responsive design
renderer.RenderingOptions.ViewPortWidth = 1024;

// Render the HTML file as a PDF document.
var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");

// Optional: Add metadata
pdf.MetaData.Author = "Your Company";
pdf.MetaData.Keywords = "invoice, pdf, conversion";
pdf.MetaData.CreationDate = System.DateTime.Now;

// Save the PDF document as an output file.
pdf.SaveAs("output.pdf");

// Alternative: Save with compression
pdf.CompressImages(80);
pdf.SaveAs("compressed-output.pdf");
using IronPdf;

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

// Optional: Configure rendering options for better output
renderer.RenderingOptions.MarginTop = 25;
renderer.RenderingOptions.MarginBottom = 25;
renderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.A4;

// Enable JavaScript execution for dynamic content
renderer.RenderingOptions.EnableJavaScript = true;

// Set print CSS media type for proper formatting
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;

// Add custom headers for authenticated content
renderer.RenderingOptions.CustomCssUrl = "___PROTECTED_URL_142___";

// Configure viewport for responsive design
renderer.RenderingOptions.ViewPortWidth = 1024;

// Render the HTML file as a PDF document.
var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");

// Optional: Add metadata
pdf.MetaData.Author = "Your Company";
pdf.MetaData.Keywords = "invoice, pdf, conversion";
pdf.MetaData.CreationDate = System.DateTime.Now;

// Save the PDF document as an output file.
pdf.SaveAs("output.pdf");

// Alternative: Save with compression
pdf.CompressImages(80);
pdf.SaveAs("compressed-output.pdf");
$vbLabelText   $csharpLabel

This code transforms an HTML file ("invoice.html") into a PDF document. By creating a ChromePdfRenderer, you're using the Chromium engine to ensure accurate conversion that preserves your web page's appearance. The rendering options let you set custom margins and paper size. The resulting PDF saves as "output.pdf" with a simple SaveAs call. This streamlined process makes HTML-to-PDF conversion straightforward for generating PDFs in C#.

For complex scenarios, explore converting URLs to PDF, working with HTML strings, or converting CSHTML files in ASP.NET MVC applications. You can also render JavaScript charts and handle Angular applications.

What Does the HTML to PDF Output Look Like?

PDF viewer interface showing a sample invoice template with placeholder company information, two line items totaling $190.00, and navigation controls Example of a basic invoice template viewed in a PDF reader, demonstrating standard invoice elements including sender/recipient details, itemized services, and pricing calculations

For enhanced PDF generation, consider adding page numbers, table of contents, or custom watermarks. You can optimize output with linearization for faster web viewing.

How Do I Convert Images to PDF?

Let's convert images to PDF documents. With minimal code, you can convert JPEG, PNG, BMP, and SVG files. The library also supports advanced features like drawing lines and rectangles or adding text and bitmaps to existing PDFs.

What Image Formats Can I Convert?

IronPDF homepage screenshot displaying the C# PDF library's key features for creating, editing, and reading PDFs in .NET applications. IronPDF offers a comprehensive C# PDF library with support for HTML to PDF conversion, cross-platform compatibility, and over 50 features for PDF manipulation in .NET applications.

using IronPdf;
using System.IO;
using System.Linq;

// Enumerate all PNG files from the specified directory.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".png"));

// Create an instance of ImageToPdfConverter
var imageToPdf = new ImageToPdfConverter();

// Optional: Set rendering options for better control
imageToPdf.ImageBehavior = ImageBehavior.CropPage;
imageToPdf.PaperSize = IronPdf.Imaging.PdfPaperSize.A4;

// Set margins for professional appearance
imageToPdf.PaperMargins = new IronPdf.Imaging.PdfPaperMargins(25);

// Control image quality and compression
imageToPdf.ImageQuality = 90; // 0-100 quality scale

// Convert the images to a PDF document.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");

// Alternative: Convert a single image with custom settings
var singleImagePdf = imageToPdf.ImageToPdf("assets/logo.png");
singleImagePdf.SaveAs("single-image.pdf");

// Advanced: Add metadata to image PDF
singleImagePdf.MetaData.Title = "Company Logo";
singleImagePdf.MetaData.Subject = "Brand Assets";
singleImagePdf.MetaData.CreationDate = DateTime.Now;
singleImagePdf.SaveAs("logo-with-metadata.pdf");
using IronPdf;
using System.IO;
using System.Linq;

// Enumerate all PNG files from the specified directory.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".png"));

// Create an instance of ImageToPdfConverter
var imageToPdf = new ImageToPdfConverter();

// Optional: Set rendering options for better control
imageToPdf.ImageBehavior = ImageBehavior.CropPage;
imageToPdf.PaperSize = IronPdf.Imaging.PdfPaperSize.A4;

// Set margins for professional appearance
imageToPdf.PaperMargins = new IronPdf.Imaging.PdfPaperMargins(25);

// Control image quality and compression
imageToPdf.ImageQuality = 90; // 0-100 quality scale

// Convert the images to a PDF document.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");

// Alternative: Convert a single image with custom settings
var singleImagePdf = imageToPdf.ImageToPdf("assets/logo.png");
singleImagePdf.SaveAs("single-image.pdf");

// Advanced: Add metadata to image PDF
singleImagePdf.MetaData.Title = "Company Logo";
singleImagePdf.MetaData.Subject = "Brand Assets";
singleImagePdf.MetaData.CreationDate = DateTime.Now;
singleImagePdf.SaveAs("logo-with-metadata.pdf");
$vbLabelText   $csharpLabel

This code shows two approaches: batch conversion of multiple PNG files and single image conversion. It finds all PNG files in the assets folder and converts them to PDF using ImageToPdfConverter.ImageToPdf. The ImageBehavior property controls image positioning on the page. Finally, it saves the PDF using SaveAs.

For advanced image handling, explore embedding images from Azure Blob Storage or working with Base64 encoded images. You can also rasterize PDFs to images for reverse conversion.

What Does the Image to PDF Output Look Like?

Screenshot of IronPDF documentation webpage showing the C# PDF library homepage with features for creating and editing PDFs in .NET applications The IronPDF library homepage displays key features including HTML to PDF conversion, cross-platform support for .NET frameworks, and a prominent 'Free 30 Day Trial' button

What Advanced PDF Conversion Features Are Available?

Beyond basic HTML and image conversion, IronPDF offers many advanced features for comprehensive PDF work. The library supports async operations and parallel processing for high-performance scenarios.

Which Document Types Can I Convert to PDF?

IronPDF supports conversion from various formats:

How Can I Enhance My Generated PDFs?

After converting documents to PDF, enhance them with:

How Do I Optimize PDF Conversion Performance?

For better performance in your applications:

What About Platform-Specific Considerations?

IronPDF provides comprehensive platform support:

What Are the Key Takeaways?

This article explored PDF conversion in C# for document management and sharing. With C# and IronPDF, you can easily integrate PDF functionality into your applications. From generating PDFs to converting HTML, images, and existing documents, IronPDF offers comprehensive capabilities. The code examples showed how to convert both HTML documents and images to PDFs with minimal effort.

IronPDF's strength lies in its comprehensive features:

  • Cross-platform support for Windows, Linux, macOS, and cloud
  • Multiple conversion formats including HTML, images, DOCX, RTF, and more
  • Advanced features like digital signatures, encryption, forms, and annotations
  • Performance optimization through async operations and parallel processing
  • Pixel-perfect rendering using the Chrome rendering engine
  • Comprehensive documentation with API reference and troubleshooting guides

As shown, IronPDF simplifies complex PDF tasks, making it valuable for developers enhancing document processing in .NET applications. Whether building web applications, desktop software, or cloud services, IronPDF provides the tools for professional PDF generation. The library's feature set includes creating, editing, converting, and securing PDF documents.

To download the PDF conversion library, visit the NuGet package for IronPDF. Also, check out the HTML-to-PDF conversion tutorial with IronPDF. For hands-on learning, explore our code examples and comprehensive tutorials. IronPDF developers can choose from various licenses to suit their needs. A free trial is available. For complete pricing and licensing information, visit the IronPDF Licensing Information page. Check the changelog for latest updates and improvements.

자주 묻는 질문

C#에서 HTML을 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF의 RenderHtmlAsPdf 메서드를 사용하여 HTML 문자열을 PDF로 변환할 수 있습니다. 또한 RenderHtmlFileAsPdf를 사용하여 HTML 파일을 PDF로 변환할 수도 있습니다.

Visual Studio 프로젝트에서 IronPDF를 설정하려면 어떤 단계를 거쳐야 하나요?

Visual Studio 프로젝트에서 IronPDF를 설정하려면 NuGet 패키지 관리자를 사용하여 'IronPDF'를 검색하고 최신 패키지를 설치하세요. 이 과정을 통해 IronPDF가 프로젝트에 통합되어 PDF 기능에 액세스할 수 있습니다.

PDF 조작을 위한 IronPDF의 기능은 무엇인가요?

IronPDF는 텍스트 추출, PDF 병합 및 분할, 페이지 회전, 콘텐츠 및 주석 수정 등 포괄적인 PDF 조작 기능을 제공합니다.

IronPDF를 사용하여 이미지를 PDF로 변환할 수 있나요?

예, JPEG, PNG, BMP와 같은 이미지 형식을 지원하는 IronPDF의 ImageToPdfConverter 메서드를 사용하여 이미지를 PDF로 변환할 수 있습니다.

IronPDF는 PDF 변환 중에 서식을 어떻게 유지하나요?

IronPDF는 강력한 렌더링 엔진 덕분에 HTML과 이미지 콘텐츠를 PDF 형식으로 정확하게 렌더링하여 변환하는 동안 원본 문서 서식이 보존되도록 합니다.

IronPDF에 대한 평가판이 있나요?

예, IronPDF 무료 평가판을 사용할 수 있습니다. 자세한 가격 및 라이선스에 대한 내용은 IronPDF 라이선스 정보 페이지를 참조하세요.

IronPDF는 어떤 프로그래밍 언어를 지원하나요?

IronPDF는 C#, VB.NET 및 F# 애플리케이션과의 통합을 지원하여 .NET 에코시스템 내에서 작업하는 개발자에게 다양한 가능성을 제공합니다.

IronPDF 사용에 대한 더 많은 튜토리얼이나 지원은 어디에서 찾을 수 있나요?

HTML에서 PDF로 변환 및 기타 기능에 대한 가이드를 포함하여 IronPDF 사용에 대한 추가 튜토리얼과 지원은 IronPDF 웹사이트 및 문서 페이지에서 확인할 수 있습니다.

IronPDF는 .NET 10과 완벽하게 호환되나요?

예 - IronPDF는 .NET 10과 완벽하게 호환되며 특별한 구성 없이도 원활하게 작동합니다. 크로스 플랫폼 배포 및 최신 비동기 친화적인 API를 포함하여 .NET 10의 최신 런타임 및 언어 기능을 지원합니다.

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

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

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