C#에서 PDF로 내보내는 방법 | IronPDF

C# PDF 내보내기 코드 예제 튜토리얼

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPDF를 사용하면 SaveAs(), Stream, BinaryData와 같은 간단한 메서드를 통해 C#에서 HTML 콘텐츠를 PDF로 내보낼 수 있습니다. 이 C# PDF 라이브러리를 사용하면 개발자는 HTML을 PDF 문서로 프로그래밍 방식으로 변환하여 웹 브라우저에 제공하거나 디스크에 저장할 수 있습니다.

IronPDF는 C#을 사용하여 HTML을 PDF로 저장할 수 있게 해주는 C# PDF 라이브러리 입니다. 또한 C#/VB 개발자가 PDF 문서를 프로그래밍 방식으로 편집할 수 있도록 해줍니다. 보고서 생성, 송장 작성 또는 웹 페이지 변환 등 어떤 작업을 하든 IronPDF는 C# 애플리케이션에서 PDF를 생성하기 위한 강력한 솔루션을 제공합니다.

빠른 시작: IronPDF를 사용하여 C#에서 HTML을 PDF로 내보내기

IronPDF를 사용하여 C#에서 HTML 콘텐츠를 PDF로 내보내세요. 이 가이드에서는 단 몇 줄의 코드로 HTML을 PDF 문서로 변환하고 저장하는 방법을 보여줍니다. IronPDF는 PDF 생성 과정을 간소화하여 개발자가 애플리케이션에 PDF 내보내기 기능을 통합할 수 있도록 해줍니다.

Nuget Icon지금 바로 NuGet을 사용하여 PDF 만들기를 시작하세요.

  1. NuGet 패키지 관리자를 사용하여 IronPDF를 설치하세요.

    PM > Install-Package IronPdf

  2. 다음 코드 조각을 복사하여 실행하세요.

    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");
  3. 실제 운영 환경에서 테스트할 수 있도록 배포하세요.

    지금 바로 무료 체험판을 통해 프로젝트에서 IronPDF를 사용해 보세요.
    arrow pointer


PDF 파일을 저장하는 방법에는 어떤 것들이 있나요?

C#에서 PDF 문서를 다룰 때 IronPDF는 생성된 PDF를 저장하고 내보내는 다양한 옵션을 제공합니다. 각 방법은 단순 파일 저장부터 웹 애플리케이션에서 PDF를 제공하는 것까지 다양한 사용 사례에 적합합니다. 다음 섹션에서는 C#에서 PDF를 내보내고 저장하는 데 사용할 수 있는 옵션에 대해 설명합니다.

PDF 파일을 디스크에 저장하는 방법

PDF 파일을 디스크에 저장하려면 PdfDocument.SaveAs 방법을 사용하십시오. 이는 데스크톱 애플리케이션이나 서버에 PDF 파일을 영구적으로 저장해야 할 때 가장 간단한 접근 방식입니다.

// Complete example for saving PDF to disk
using IronPdf;

// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();

// Create HTML content with styling
string htmlContent = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
        .content { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Invoice #12345</h1>
    <div class='content'>
        <p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
        <p>Thank you for your business!</p>
    </div>
</body>
</html>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");

// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");
// Complete example for saving PDF to disk
using IronPdf;

// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();

// Create HTML content with styling
string htmlContent = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
        .content { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Invoice #12345</h1>
    <div class='content'>
        <p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
        <p>Thank you for your business!</p>
    </div>
</body>
</html>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");

// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");
$vbLabelText   $csharpLabel

이 방법은 비밀번호 보호 기능을 추가하는 것을 지원합니다. 내보낸 PDF 문서에 디지털 서명을 하는 방법에 대한 자세한 내용은 ' PDF 문서에 디지털 서명하기 ' 문서를 참조하세요. 추가 보안 옵션에 대해서는 PDF 권한 및 암호 가이드를 살펴보세요.

C#에서 PDF 파일을 MemoryStream에 저장하는 방법 (System.IO.MemoryStream)

IronPdf.PdfDocument.Stream 속성은 System.IO.MemoryStream를 사용하여 PDF를 메모리에 저장합니다. 이 접근 방식은 임시 파일을 생성하지 않고 메모리에서 PDF 데이터를 조작하거나 다른 메서드로 전달해야 할 때 이상적입니다. PDF 메모리 스트림 작업 에 대해 자세히 알아보세요.

// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");

// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;

// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);

// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");

// Remember to dispose of the stream when done
stream.Dispose();
// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");

// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;

// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);

// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");

// Remember to dispose of the stream when done
stream.Dispose();
$vbLabelText   $csharpLabel

바이너리 데이터로 저장하는 방법

IronPdf.PdfDocument.BinaryData 속성은 PDF 문서를 메모리에 바이너리 데이터로 내보냅니다. 이는 특히 데이터베이스 저장이나 바이트 배열을 필요로 하는 API와의 통합에 유용합니다.

이 코드는 PDF를 ByteArray 형식으로 출력하며, 이는 C#으로 표현하면 byte []가 됩니다.

// Example: Convert PDF to binary data
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};

// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");

// Get binary data
byte[] binaryData = pdf.BinaryData;

// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);

// Example: Send via API
// apiClient.UploadDocument(binaryData);
// Example: Convert PDF to binary data
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};

// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");

// Get binary data
byte[] binaryData = pdf.BinaryData;

// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);

// Example: Send via API
// apiClient.UploadDocument(binaryData);
$vbLabelText   $csharpLabel

이진 데이터 조작과 관련된 고급 시나리오의 경우 PDF를 MemoryStream으로 변환하는 방법 에 대한 가이드를 참조하십시오.

웹 서버에서 브라우저로 콘텐츠를 제공하는 방법

웹에 PDF 파일을 제공하려면 HTML 형식이 아닌 바이너리 데이터 형식으로 전송해야 합니다. 이는 사용자가 브라우저에서 PDF 파일을 직접 다운로드하거나 볼 필요가 있는 웹 애플리케이션에 필수적입니다. IronPDF는 MVC 및 기존 ASP.NET 애플리케이션 모두와 통합됩니다.

MVC PDF 내보내기

최신 MVC 애플리케이션에서 PDF를 제공하는 것은 FileStreamResult를 사용하면 간단합니다. 이 접근 방식은 ASP.NET Core MVC 애플리케이션 에서 효과적입니다.

// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
    // Generate your HTML content
    string htmlContent = GenerateInvoiceHtml(invoiceId);

    // Create PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Get the PDF stream
    MemoryStream stream = pdf.Stream;

    // Reset stream position
    stream.Position = 0;

    // Return file to browser - will prompt download
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Return PDF for browser viewing
    return File(pdf.BinaryData, "application/pdf");
}
// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
    // Generate your HTML content
    string htmlContent = GenerateInvoiceHtml(invoiceId);

    // Create PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Get the PDF stream
    MemoryStream stream = pdf.Stream;

    // Reset stream position
    stream.Position = 0;

    // Return file to browser - will prompt download
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Return PDF for browser viewing
    return File(pdf.BinaryData, "application/pdf");
}
$vbLabelText   $csharpLabel

ASP.NET PDF 내보내기

기존 ASP.NET WebForms 애플리케이션의 경우, Response 객체를 통해 PDF 파일을 직접 제공할 수 있습니다.

// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
    // Create your PDF document
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        PrintHtmlBackgrounds = true,
        CreatePdfFormsFromHtml = true
    };

    // Generate PDF from current page or custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieves the PDF binary data
    byte[] Binary = MyPdfDocument.BinaryData;

    // Clears the existing response content
    Response.Clear();

    // Sets the response content type to 'application/octet-stream', suitable for PDF files
    Response.ContentType = "application/octet-stream";

    // Add content disposition header for download
    Response.AddHeader("Content-Disposition", 
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");

    // Writes the binary data to the response output stream
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);

    // Flushes the response to send the data to the client
    Response.Flush();

    // End the response
    Response.End();
}
// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
    // Create your PDF document
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        PrintHtmlBackgrounds = true,
        CreatePdfFormsFromHtml = true
    };

    // Generate PDF from current page or custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieves the PDF binary data
    byte[] Binary = MyPdfDocument.BinaryData;

    // Clears the existing response content
    Response.Clear();

    // Sets the response content type to 'application/octet-stream', suitable for PDF files
    Response.ContentType = "application/octet-stream";

    // Add content disposition header for download
    Response.AddHeader("Content-Disposition", 
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");

    // Writes the binary data to the response output stream
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);

    // Flushes the response to send the data to the client
    Response.Flush();

    // End the response
    Response.End();
}
$vbLabelText   $csharpLabel

고급 수출 시나리오

일괄 PDF 내보내기

여러 개의 PDF 파일을 처리할 때 내보내기 프로세스를 최적화할 수 있습니다.

// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
    using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
    {
        var renderer = new ChromePdfRenderer();

        for (int i = 0; i < htmlDocuments.Count; i++)
        {
            // Render each HTML document
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);

            // Add to zip archive
            var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
            using (var entryStream = entry.Open())
            {
                pdf.Stream.CopyTo(entryStream);
            }
        }
    }
}
// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
    using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
    {
        var renderer = new ChromePdfRenderer();

        for (int i = 0; i < htmlDocuments.Count; i++)
        {
            // Render each HTML document
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);

            // Add to zip archive
            var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
            using (var entryStream = entry.Open())
            {
                pdf.Stream.CopyTo(entryStream);
            }
        }
    }
}
$vbLabelText   $csharpLabel

사용자 권한에 따른 조건부 내보내기

// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Apply security based on user role
    if (userRole == UserRole.Guest)
    {
        // Restrict printing and copying for guests
        pdf.SecuritySettings.AllowUserPrinting = false;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    }
    else if (userRole == UserRole.Standard)
    {
        // Allow printing but not editing
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserEditing = false;
    }

    return pdf.BinaryData;
}
// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Apply security based on user role
    if (userRole == UserRole.Guest)
    {
        // Restrict printing and copying for guests
        pdf.SecuritySettings.AllowUserPrinting = false;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    }
    else if (userRole == UserRole.Standard)
    {
        // Allow printing but not editing
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserEditing = false;
    }

    return pdf.BinaryData;
}
$vbLabelText   $csharpLabel

PDF 내보내기 모범 사례

실제 운영 환경에서 PDF 파일을 내보낼 때 다음과 같은 모범 사례를 고려하십시오.

  1. 메모리 관리 : 대용량 PDF 파일이나 트래픽이 많은 애플리케이션의 경우, 메모리 누수를 방지하기 위해 PDF 객체와 스트림을 적절하게 해제해야 합니다. 성능 향상을 위해 async 메서드를 사용하는 것을 고려해 보세요.
  2. 오류 처리 : PDF를 내보낼 때, 특히 네트워크 문제가 발생할 수 있는 웹 애플리케이션의 경우, 항상 적절한 오류 처리를 구현해야 합니다.
  3. 압축 : 대용량 PDF 파일의 경우, 사용자에게 제공하기 전에 파일 크기를 줄이기 위해 PDF 압축을 사용하십시오.
  4. 메타데이터 : 문서 관리를 효율적으로 하기 위해 제목, 작성자, 생성 날짜 등 적절한 PDF 메타데이터를 설정하십시오.
  5. 플랫폼 간 호환성 : 내보내기 기능이 다양한 플랫폼에서 작동하는지 확인하십시오. IronPDF는 Windows, LinuxmacOS를 지원합니다.

결론

IronPDF는 간단한 파일 저장부터 복잡한 웹 서버 시나리오에 이르기까지 C# 애플리케이션에서 PDF를 내보내기 위한 포괄적인 옵션을 제공합니다. 사용 사례에 맞는 적절한 내보내기 방법을 사용하면 보안 및 성능 표준을 유지하면서 PDF 문서를 효율적으로 생성하고 사용자에게 전달할 수 있습니다.

자주 묻는 질문

C#에서 HTML 콘텐츠를 PDF로 내보내는 방법은 무엇인가요?

IronPDF의 ChromePdfRenderer 클래스를 사용하면 C#에서 HTML을 PDF로 내보낼 수 있습니다. 렌더러 인스턴스를 생성하고 RenderHtmlAsPdf() 메서드를 사용하여 HTML 콘텐츠를 변환한 다음 SaveAs() 메서드를 사용하여 저장하면 됩니다. IronPDF를 사용하면 HTML 문자열, 파일 또는 URL을 PDF 문서로 간편하게 변환할 수 있습니다.

C#을 사용하여 PDF를 저장하는 다양한 방법에는 무엇이 있습니까?

IronPDF는 PDF를 저장하는 여러 가지 방법을 제공합니다. SaveAs()는 디스크에 저장하는 방식이고, Stream은 임시 파일을 생성하지 않고 웹 애플리케이션에서 PDF를 제공하는 방식이며, BinaryData는 PDF를 바이트 배열로 가져오는 방식입니다. IronPDF의 각 방법은 단순 파일 저장부터 동적 웹 전송에 이르기까지 다양한 사용 사례에 적합합니다.

PDF 파일을 디스크 대신 메모리에 저장할 수 있나요?

네, IronPDF는 System.IO.MemoryStream을 사용하여 PDF를 메모리에 저장할 수 있도록 지원합니다. 이는 서버에 임시 파일을 생성하지 않고 웹 애플리케이션에서 사용자에게 PDF를 직접 제공하려는 경우에 유용합니다. Stream 속성을 사용하거나 PDF를 바이너리 데이터로 변환하여 저장할 수 있습니다.

PDF 파일을 저장할 때 암호로 보호하려면 어떻게 해야 하나요?

IronPDF는 저장하기 전에 PdfDocument 객체의 Password 속성을 설정하여 암호 보호 기능을 활성화합니다. pdf.Password에 암호 문자열을 할당한 다음 SaveAs()를 사용하여 암호를 입력해야만 열 수 있는 보호된 PDF 파일을 생성하면 됩니다.

PDF 파일을 디스크에 저장하지 않고 웹 브라우저에 바로 제공할 수 있나요?

네, IronPDF를 사용하면 PDF 파일을 바이너리 데이터 형태로 웹 브라우저에 직접 제공할 수 있습니다. BinaryData 속성을 이용하면 PDF 파일을 바이트 배열로 가져와 웹 애플리케이션의 응답 스트림을 통해 제공할 수 있으므로 임시 파일 저장소가 필요하지 않습니다.

HTML을 PDF로 변환하여 한 줄로 저장하는 가장 간단한 방법은 무엇일까요?

IronPDF는 다음과 같은 한 줄짜리 해결책을 제공합니다. `new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Your HTML").SaveAs("output.pdf")`. 이 코드는 렌더러를 생성하고, HTML을 PDF로 변환하고, 디스크에 저장하는 작업을 단 한 번의 명령으로 수행합니다.

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

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

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

검토자:
제프 프리츠
제프리 T. 프리츠
.NET 커뮤니티 팀의 수석 프로그램 관리자
제프는 .NET 및 Visual Studio 팀의 수석 프로그램 관리자이기도 합니다. 그는 .NET Conf 가상 컨퍼런스 시리즈의 총괄 프로듀서이며, 개발자를 위한 라이브 스트림 'Fritz and Friends'를 주 2회 진행하며 시청자들과 함께 기술에 대해 이야기하고 코드를 작성합니다. 제프는 Microsoft Build, Microsoft Ignite, .NET Conf, Microsoft MVP Summit 등 주요 Microsoft 개발자 행사를 위한 워크숍, 프레젠테이션 및 콘텐츠 기획을 담당합니다.
시작할 준비 되셨나요?
Nuget 다운로드 17,527,568 | 버전: 2026.2 방금 출시되었습니다