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

IronPDF를 사용하여 .NET PDF API 생성하는 방법

현대 애플리케이션을 다룰 때, .NET 개발자처럼 중앙 집중화된 PDF 생성 서비스를 구축해야 할 수도 있습니다. 송장, 보고서, 증명서, 계약서를 생성하건 간에 전 for .NET PDF API가 PDF 파일을 효율적으로 관리하는 데 유익할 수 있습니다. 그래서 어떻게 PDF 생성 작업을 개선할 수 있나요? 데스크톱 및 웹 애플리케이션 전반에 일관성, 유지 보수성, 확장성을 제공함으로써 이를 수행합니다. 문서 내용, PDF 페이지 및 PDF 양식 필드를 관리하기가 전례 없이 쉬워졌습니다.

이 튜토리얼에서는 ASP.NET Core와 강력한 .NET PDF 라이브러리인 IronPDF를 사용하여 생산 준비된 PDF API를 구축하는 방법을 배웁니다. 우리는 HTML에서 PDF를 생성하고, 문서를 병합하며, 워터마크를 추가하고, 다양한 실제 PDF 생성 시나리오를 Web API에서 처리할 수 있는 RESTful 엔드포인트를 만들 것입니다.

전용 PDF API를 구축해야 하는 이유는 무엇입니까?

코드를 실행하기 전에, 전용 PDF API를 생성하는 것이 왜 합리적인지 이해해 봅시다:

  • 중앙 집중화된 로직: 모든 PDF 생성 로직이 한 곳에 위치하여 유지 관리 및 업데이트가 용이합니다.
  • 마이크로서비스 아키텍처: 다른 애플리케이션이 PDF 기능이 필요한 서비스 지향 아키텍처에 적합합니다.
  • 성능 최적화: 대형 PDF 파일, 여러 페이지 및 동적 데이터를 위한 전용 서비스를 확장하고 최적화하기가 쉽습니다.
  • 언어 독립성: 모든 클라이언트 애플리케이션은 프로그래밍 언어와 상관없이 API를 사용할 수 있습니다.
  • 일관된 출력: 조직 전반의 모든 PDF 문서가 일관된 문서 레이아웃, 단락 형식 및 PDF 내용을 유지하도록 보장합니다.

건축을 시작할 준비가 되셨나요? IronPDF의 무료 체험판을 다운로드하고 이 튜토리얼을 따라가면서 .NET Framework 프로젝트에서 프로그래밍으로 PDF 파일을 생성하세요.

IronPDF: 완벽한 .NET PDF 라이브러리

IronPDF는 .NET 개발자를 위한 최고의 PDF 라이브러리로, Web API 프로젝트에서 PDF 생성을 간편하고 신뢰할 수 있게 만드는 포괄적인 기능 세트를 제공합니다. 이 라이브러리는 Chrome 렌더링 엔진을 기반으로 하여, HTML에서 PDF로의 변환을 픽셀 단위로 정확하게 실행하며, 코드를 몇 줄만 추가하면 가능합니다. 모든 스타일링, JavaScript 실행 및 반응형 레이아웃을 유지하면서 이를 수행합니다.

.NET PDF API 개발에 적합한 IronPDF의 주요 기능들:

  • Chrome 기반 렌더링: Google Chrome의 렌더링 엔진을 활용하여 HTML 컨텐츠를 PDF 문서로 정확하게 변환하며 임베디드 이미지 및 기타 웹 자산을 완벽하게 지원합니다.
  • 풍부한 기능 세트: 디지털 서명, PDF 양식, 주석, 암호화, 압축 등과 함께 새로운 및 기존 문서를 편집할 수 있습니다.
  • 안전한 PDF 문서 생성: 암호화, 디지털 서명, 문서 보호를 통해 민감한 PDF 콘텐츠를 관리합니다.
  • 다양한 입력 형식: HTML, URL, 이미지, 오피스 문서를 사용하여 PDF 문서를 생성합니다.
  • 고급 조작: PDF 페이지를 병합하고, 문서를 분할하고, 워터마크를 적용하며, 인터랙티브 PDF 양식을 생성하고, PDF 파일을 프로그래밍으로 조작합니다.
  • 크로스 플랫폼 지원: Windows, Linux, macOS, Docker, 클라우드 플랫폼에서 작동합니다.
  • 성능 최적화: 비동기 작업, 효율적 메모리 관리 및 빠른 렌더링

PDF 문서 API 프로젝트를 설정하는 방법은?

새 ASP.NET Core Web API 프로젝트를 생성하고 필요한 패키지를 설치하는 것부터 시작해 봅시다.

필수 조건

  • .NET 6.0 SDK 또는 그 이상
  • Visual Studio 2022 또는 Visual Studio Code
  • Postman 또는 유사한 API 테스트 도구를 사용하여 PDF REST API를 테스트합니다.

프로젝트 생성

먼저 PDF 생성 도구를 구축할 프로젝트를 만듭니다.

dotnet new webapi -n PdfApiService
cd PdfApiService

IronPDF 설치 중

다음 단계는 NuGet을 통해 프로젝트에 IronPDF를 추가하는 것입니다.

dotnet add package IronPdf

또는, Visual Studio의 NuGet 패키지 관리 콘솔을 사용하여:

Install-Package IronPdf

프로젝트 구조

C# 개발의 중요한 측면은 깨끗하고 잘 구조화된 프로젝트 폴더를 유지하는 것입니다. 예를 들어:

첫 PDF 엔드포인트를 생성하는 방법은?

HTML을 PDF 형식으로 변환하는 간단한 엔드포인트를 만들어 봅시다. 먼저 서비스 인터페이스와 구현을 만듭니다:

PDF 서비스 생성

먼저, IPdfService.cs 파일에 다음을 추가합니다:

public interface IPdfService
{
    byte[] GeneratePdfFromHtml(string htmlContent);
    byte[] GeneratePdfFromUrl(string url);
}
public interface IPdfService
{
    byte[] GeneratePdfFromHtml(string htmlContent);
    byte[] GeneratePdfFromUrl(string url);
}
Public Interface IPdfService
    Function GeneratePdfFromHtml(htmlContent As String) As Byte()
    Function GeneratePdfFromUrl(url As String) As Byte()
End Interface
$vbLabelText   $csharpLabel

PdfService.cs 파일에 다음을 추가합니다:

using IronPdf;
public class PdfService : IPdfService
{
    private readonly ChromePdfRenderer _renderer;
    public PdfService()
    {
        _renderer = new ChromePdfRenderer();
        // Configure rendering options for optimal PDF generation in .NET
        _renderer.RenderingOptions.MarginTop = 20;
        _renderer.RenderingOptions.MarginBottom = 20;
        _renderer.RenderingOptions.PrintHtmlBackgrounds = true;
    }
    public byte[] GeneratePdfFromHtml(string htmlContent)
    {
        // Generate PDF from HTML using the .NET PDF API
        var pdf = _renderer.RenderHtmlAsPdf(htmlContent);
        return pdf.BinaryData;
    }
    public byte[] GeneratePdfFromUrl(string url)
    {
        // Convert URL to PDF in the REST API
        var pdf = _renderer.RenderUrlAsPdf(url);
        return pdf.BinaryData;
    }
}
using IronPdf;
public class PdfService : IPdfService
{
    private readonly ChromePdfRenderer _renderer;
    public PdfService()
    {
        _renderer = new ChromePdfRenderer();
        // Configure rendering options for optimal PDF generation in .NET
        _renderer.RenderingOptions.MarginTop = 20;
        _renderer.RenderingOptions.MarginBottom = 20;
        _renderer.RenderingOptions.PrintHtmlBackgrounds = true;
    }
    public byte[] GeneratePdfFromHtml(string htmlContent)
    {
        // Generate PDF from HTML using the .NET PDF API
        var pdf = _renderer.RenderHtmlAsPdf(htmlContent);
        return pdf.BinaryData;
    }
    public byte[] GeneratePdfFromUrl(string url)
    {
        // Convert URL to PDF in the REST API
        var pdf = _renderer.RenderUrlAsPdf(url);
        return pdf.BinaryData;
    }
}
Imports IronPdf

Public Class PdfService
    Implements IPdfService

    Private ReadOnly _renderer As ChromePdfRenderer

    Public Sub New()
        _renderer = New ChromePdfRenderer()
        ' Configure rendering options for optimal PDF generation in .NET
        _renderer.RenderingOptions.MarginTop = 20
        _renderer.RenderingOptions.MarginBottom = 20
        _renderer.RenderingOptions.PrintHtmlBackgrounds = True
    End Sub

    Public Function GeneratePdfFromHtml(htmlContent As String) As Byte()
        ' Generate PDF from HTML using the .NET PDF API
        Dim pdf = _renderer.RenderHtmlAsPdf(htmlContent)
        Return pdf.BinaryData
    End Function

    Public Function GeneratePdfFromUrl(url As String) As Byte()
        ' Convert URL to PDF in the REST API
        Dim pdf = _renderer.RenderUrlAsPdf(url)
        Return pdf.BinaryData
    End Function

End Class
$vbLabelText   $csharpLabel

PdfService는 HTML을 PDF로 변환하는 핵심 프로세스를 처리합니다. IronPDF의 ChromePdfRenderer를 이용하여, 이 클래스는 페이지 여백 및 배경 렌더링과 같은 합리적인 기본값으로 설정되어 최종 문서를 깔끔하게 만듭니다.

컨트롤러가 원시 HTML을 전달하면, 서비스는 IronPDF를 사용하여 이를 전문적인 품질의 PDF로 렌더링하고 결과를 바이트 데이터로 반환하여 다운로드할 준비를 합니다. 또한, 전체 웹 페이지를 URL을 바로 PDF로 변환하여 처리할 수도 있습니다.

컨트롤러 생성

이제 API의 컨트롤러를 생성할 차례입니다. 이는 HTML에서 PDF 파일을 생성할 수 있는 API 엔드포인트를 제공합니다. 그 후에는 PDF 문서를 시스템에 다운로드 및 저장하여 더 나은 사용이나 공유를 위해 사용할 수 있습니다.

// Controllers/PdfController.cs
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
    private readonly IPdfService _pdfService;
    public PdfController(IPdfService pdfService)
    {
        _pdfService = pdfService;
    }
    [HttpPost("html-to-pdf")]
    public IActionResult ConvertHtmlToPdf([FromBody] HtmlRequest request)
    {
        try
        {
            var pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent);
            // Return as downloadable file
            return File(pdfBytes, "application/pdf", "document.pdf");
        }
        catch (Exception ex)
        {
            return BadRequest($"Error generating PDF: {ex.Message}");
        }
    }
}
// Controllers/PdfController.cs
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class PdfController : ControllerBase
{
    private readonly IPdfService _pdfService;
    public PdfController(IPdfService pdfService)
    {
        _pdfService = pdfService;
    }
    [HttpPost("html-to-pdf")]
    public IActionResult ConvertHtmlToPdf([FromBody] HtmlRequest request)
    {
        try
        {
            var pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent);
            // Return as downloadable file
            return File(pdfBytes, "application/pdf", "document.pdf");
        }
        catch (Exception ex)
        {
            return BadRequest($"Error generating PDF: {ex.Message}");
        }
    }
}
Imports Microsoft.AspNetCore.Mvc

<ApiController>
<Route("api/[controller]")>
Public Class PdfController
    Inherits ControllerBase

    Private ReadOnly _pdfService As IPdfService

    Public Sub New(pdfService As IPdfService)
        _pdfService = pdfService
    End Sub

    <HttpPost("html-to-pdf")>
    Public Function ConvertHtmlToPdf(<FromBody> request As HtmlRequest) As IActionResult
        Try
            Dim pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent)
            ' Return as downloadable file
            Return File(pdfBytes, "application/pdf", "document.pdf")
        Catch ex As Exception
            Return BadRequest($"Error generating PDF: {ex.Message}")
        End Try
    End Function
End Class
$vbLabelText   $csharpLabel

그런 다음 HtmlRequest.cs 파일에 다음을 추가합니다:

// Models/HtmlRequest.cs
public class HtmlRequest
{
    public string HtmlContent { get; set; }
    public string FileName { get; set; } = "document.pdf";
}
// Models/HtmlRequest.cs
public class HtmlRequest
{
    public string HtmlContent { get; set; }
    public string FileName { get; set; } = "document.pdf";
}
' Models/HtmlRequest.vb
Public Class HtmlRequest
    Public Property HtmlContent As String
    Public Property FileName As String = "document.pdf"
End Class
$vbLabelText   $csharpLabel

첫 번째 파일에서는 HTML을 다운로드 가능한 PDF로 변환하는 간단한 API 엔드포인트를 설정합니다. 누군가 HTML 내용을 api/pdf/html-to-pdf 경로로 간단한 POST 요청을 보내면, PdfController는 해당 내용을 PDF로 변환하는 일을 전용 서비스에 맡깁니다.

PDF가 생성되면, 컨트롤러는 이를 사용자가 다운로드할 준비가 된 파일 형태로 다시 전달합니다. 요청 자체는 HtmlRequest 모델을 사용하여 구성되며, 원시 HTML과 최종 문서를 위한 선택적 파일 이름을 함께 전달합니다. 간단히 말해, 이 설정은 클라이언트가 HTML을 보내고 즉시 깔끔한 PDF를 받을 수 있게 해 줍니다.

서비스 등록

PDF 서비스를 등록하기 위해 Program.cs를 업데이트합니다.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register PDF service
builder.Services.AddSingleton<IPdfService, PdfService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register PDF service
builder.Services.AddSingleton<IPdfService, PdfService>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
Imports Microsoft.AspNetCore.Builder
Imports Microsoft.Extensions.DependencyInjection

Dim builder = WebApplication.CreateBuilder(args)
builder.Services.AddControllers()
builder.Services.AddEndpointsApiExplorer()
builder.Services.AddSwaggerGen()
' Register PDF service
builder.Services.AddSingleton(Of IPdfService, PdfService)()
Dim app = builder.Build()
If app.Environment.IsDevelopment() Then
    app.UseSwagger()
    app.UseSwaggerUI()
End If
app.UseHttpsRedirection()
app.MapControllers()
app.Run()
$vbLabelText   $csharpLabel

다양한 응답 유형을 처리하는 방법?

귀하의 API는 클라이언트 요구 사항에 따라 PDF를 반환하는 다양한 방법을 지원해야 합니다:

[HttpPost("generate")]
 public IActionResult GeneratePdf([FromBody] PdfRequest request)
 {
     var pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent);
     switch (request.ResponseType?.ToLower())
     {
         case "base64":
             return Ok(new
             {
                 data = Convert.ToBase64String(pdfBytes),
                 filename = request.FileName
             });
         case "inline":
             return File(pdfBytes, "application/pdf");
         default: // download
             return File(pdfBytes, "application/pdf", request.FileName);
     }
 }
[HttpPost("generate")]
 public IActionResult GeneratePdf([FromBody] PdfRequest request)
 {
     var pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent);
     switch (request.ResponseType?.ToLower())
     {
         case "base64":
             return Ok(new
             {
                 data = Convert.ToBase64String(pdfBytes),
                 filename = request.FileName
             });
         case "inline":
             return File(pdfBytes, "application/pdf");
         default: // download
             return File(pdfBytes, "application/pdf", request.FileName);
     }
 }
Imports Microsoft.AspNetCore.Mvc

<HttpPost("generate")>
Public Function GeneratePdf(<FromBody> request As PdfRequest) As IActionResult
    Dim pdfBytes = _pdfService.GeneratePdfFromHtml(request.HtmlContent)
    Select Case request.ResponseType?.ToLower()
        Case "base64"
            Return Ok(New With {
                .data = Convert.ToBase64String(pdfBytes),
                .filename = request.FileName
            })
        Case "inline"
            Return File(pdfBytes, "application/pdf")
        Case Else ' download
            Return File(pdfBytes, "application/pdf", request.FileName)
    End Select
End Function
$vbLabelText   $csharpLabel

여기서는 컨트롤러에 보다 유연한 PDF 생성 끝점을 추가했습니다. 파일 다운로드를 항상 강제하는 대신, GeneratePdf 메서드를 통해 클라이언트가 결과를 어떤 방식으로 반환받을지 선택할 수 있도록 합니다. 이 옵션은 다양한 형식으로 PDF를 디스플레이할 수 있는 유연성을 제공하며, 다운로드 가능한 파일, 브라우저에서 직접 또는 API에서 쉽게 사용할 수 있도록 Base64 문자열로 인코딩할 수 있습니다.

요청은 PdfRequest 모델로 정의되며, 이는 이전의 HtmlRequest를 기반으로 하고 ResponseType 옵션을 추가합니다. 간단히 말해, 이는 사용자가 PDF를 어떻게 받는지에 대한 더 많은 제어권을 제공하며, API를 더 다양하고 사용자 친화적으로 만듭니다.

이제 프로그램을 실행하면 Swagger에서 이 출력을 볼 수 있습니다.

IronPDF를 사용하여 .NET PDF API를 생성하는 방법: 그림 4 - Swagger UI

일반적인 PDF 작업을 구현하는 방법?

다양한 PDF 생성 시나리오를 처리할 수 있도록 서비스를 확장해 봅시다:

URL을 PDF로 변환

[HttpPost("url-to-pdf")]
public async Task<IActionResult> ConvertUrlToPdf([FromBody] UrlRequest request)
{
    try
    {
        var pdfBytes = await Task.Run(() => 
            _pdfService.GeneratePdfFromUrl(request.Url));
        return File(pdfBytes, "application/pdf", 
            $"{request.FileName ?? "website"}.pdf");
    }
    catch (Exception ex)
    {
        return BadRequest($"Failed to convert URL: {ex.Message}");
    }
}
public class UrlRequest
{
    public string Url { get; set; }
    public string FileName { get; set; }
}
[HttpPost("url-to-pdf")]
public async Task<IActionResult> ConvertUrlToPdf([FromBody] UrlRequest request)
{
    try
    {
        var pdfBytes = await Task.Run(() => 
            _pdfService.GeneratePdfFromUrl(request.Url));
        return File(pdfBytes, "application/pdf", 
            $"{request.FileName ?? "website"}.pdf");
    }
    catch (Exception ex)
    {
        return BadRequest($"Failed to convert URL: {ex.Message}");
    }
}
public class UrlRequest
{
    public string Url { get; set; }
    public string FileName { get; set; }
}
Imports System.Threading.Tasks
Imports Microsoft.AspNetCore.Mvc

<HttpPost("url-to-pdf")>
Public Async Function ConvertUrlToPdf(<FromBody> request As UrlRequest) As Task(Of IActionResult)
    Try
        Dim pdfBytes = Await Task.Run(Function() _pdfService.GeneratePdfFromUrl(request.Url))
        Return File(pdfBytes, "application/pdf", $"{If(request.FileName, "website")}.pdf")
    Catch ex As Exception
        Return BadRequest($"Failed to convert URL: {ex.Message}")
    End Try
End Function

Public Class UrlRequest
    Public Property Url As String
    Public Property FileName As String
End Class
$vbLabelText   $csharpLabel

이 끝점은 클라이언트가 URL을 보내고 그 웹페이지의 바로 다운로드 가능한 PDF를 반환받을 수 있도록 합니다. POST /api/pdf/url-to-pdf 요청이 수신되면, 컨트롤러는 _pdfService를 사용하여 배경에서 주어진 URL을 PDF 바이트로 변환한 후 파일 다운로드로 반환합니다. 변환 중 문제가 발생하면 명확한 오류 메시지로 우아하게 응답합니다.

URL 'https://www.apple.com/nz'를 사용해 보고 POST 요청을 테스트해 봅시다. 아래는 우리가 얻은 출력 결과입니다.

출력

IronPDF를 사용하여 .NET PDF API를 생성하는 방법: 그림 5 - URL PDF 출력

커스텀 워터마크 추가

public byte[] AddWatermarkFromFile(string filePath, string watermarkText)
{
    // Load PDF directly from file
    var pdf = PdfDocument.FromFile(filePath);
    pdf.ApplyWatermark(
        $"<h1 style='color:red;font-size:72px;'>{watermarkText}</h1>",
        75,
        IronPdf.Editing.VerticalAlignment.Middle,
        IronPdf.Editing.HorizontalAlignment.Center
    );
    return pdf.BinaryData;
}
public byte[] AddWatermarkFromFile(string filePath, string watermarkText)
{
    // Load PDF directly from file
    var pdf = PdfDocument.FromFile(filePath);
    pdf.ApplyWatermark(
        $"<h1 style='color:red;font-size:72px;'>{watermarkText}</h1>",
        75,
        IronPdf.Editing.VerticalAlignment.Middle,
        IronPdf.Editing.HorizontalAlignment.Center
    );
    return pdf.BinaryData;
}
Imports IronPdf

Public Function AddWatermarkFromFile(filePath As String, watermarkText As String) As Byte()
    ' Load PDF directly from file
    Dim pdf = PdfDocument.FromFile(filePath)
    pdf.ApplyWatermark(
        $"<h1 style='color:red;font-size:72px;'>{watermarkText}</h1>",
        75,
        IronPdf.Editing.VerticalAlignment.Middle,
        IronPdf.Editing.HorizontalAlignment.Center
    )
    Return pdf.BinaryData
End Function
$vbLabelText   $csharpLabel

여기서는 테스트 목적을 위해 로컬 파일을 수동으로 로드하고 있습니다. 그러나 PDF API 생성 시 PDF 문서를 생성한 후 커스텀 워터마크를 쉽게 적용할 수 있도록 조정할 수 있습니다.

워터마크 출력

IronPDF를 사용하여 .NET PDF API를 생성하는 방법: 그림 6 - 위 코드 예제의 워터마크 출력

템플릿으로 동적 데이터 추가하는 방법

실제 애플리케이션의 경우, 종종 동적 데이터로 템플릿에서 PDF를 생성해야 합니다:

[HttpPost("from-template")]
public IActionResult GenerateFromTemplate([FromBody] TemplateRequest request)
{
    // Simple template replacement
    var html = request.Template;
    foreach (var item in request.Data)
    {
        html = html.Replace($"{{{{{item.Key}}}}}", item.Value);
    }
    var pdfBytes = _pdfService.GeneratePdfFromHtml(html);
    return File(pdfBytes, "application/pdf", request.FileName);
}
public class TemplateRequest
{
    public string Template { get; set; }
    public Dictionary<string, string> Data { get; set; }
    public string FileName { get; set; } = "document.pdf";
}
[HttpPost("from-template")]
public IActionResult GenerateFromTemplate([FromBody] TemplateRequest request)
{
    // Simple template replacement
    var html = request.Template;
    foreach (var item in request.Data)
    {
        html = html.Replace($"{{{{{item.Key}}}}}", item.Value);
    }
    var pdfBytes = _pdfService.GeneratePdfFromHtml(html);
    return File(pdfBytes, "application/pdf", request.FileName);
}
public class TemplateRequest
{
    public string Template { get; set; }
    public Dictionary<string, string> Data { get; set; }
    public string FileName { get; set; } = "document.pdf";
}
Imports Microsoft.AspNetCore.Mvc

<HttpPost("from-template")>
Public Function GenerateFromTemplate(<FromBody> request As TemplateRequest) As IActionResult
    ' Simple template replacement
    Dim html As String = request.Template
    For Each item In request.Data
        html = html.Replace($"{{{{{item.Key}}}}}", item.Value)
    Next
    Dim pdfBytes As Byte() = _pdfService.GeneratePdfFromHtml(html)
    Return File(pdfBytes, "application/pdf", request.FileName)
End Function

Public Class TemplateRequest
    Public Property Template As String
    Public Property Data As Dictionary(Of String, String)
    Public Property FileName As String = "document.pdf"
End Class
$vbLabelText   $csharpLabel

Razor, Handlebars 또는 다른 엔진을 사용한 보다 고급 템플릿 시나리오는 IronPDF의 HTML to PDF 문서를 참조하십시오. 또한 MVC 애플리케이션을 위한 CSHTML to PDF 변환 및 Blazor 애플리케이션을 위한 Razor to PDF를 탐색할 수 있습니다.

성능을 최적화하는 방법?

프로덕션 PDF API를 구축할 때 성능은 매우 중요합니다. 여기에 주요 최적화 전략이 있습니다:

비동기 작업

I/O 작업을 포함하는 프로젝트를 구축할 때 비동기 코딩을 사용하는 것이 현명합니다. 이는 특히 PDF 콘텐츠가 다음과 같은 외부 리소스에서 올 때 유용합니다:

  • HTML 페이지 다운로드 (RenderUrlAsPdf)
  • 이미지, CSS 또는 글꼴을 HTTP를 통해 가져오기
  • 디스크 또는 클라우드 저장소에 파일을 읽고 쓰기

이러한 작업은 스레드를 차단할 수 있지만 비동기를 사용하면 API 스레드가 대기 상태로 머물지 않습니다.

예:

public async Task<byte[]> GeneratePdfFromHtmlAsync(string htmlContent)
{
    return await Task.Run(() => 
    {
        var pdf = _renderer.RenderHtmlAsPdf(htmlContent);
        return pdf.BinaryData;
    });
}
public async Task<byte[]> GeneratePdfFromHtmlAsync(string htmlContent)
{
    return await Task.Run(() => 
    {
        var pdf = _renderer.RenderHtmlAsPdf(htmlContent);
        return pdf.BinaryData;
    });
}
Imports System.Threading.Tasks

Public Async Function GeneratePdfFromHtmlAsync(htmlContent As String) As Task(Of Byte())
    Return Await Task.Run(Function()
                              Dim pdf = _renderer.RenderHtmlAsPdf(htmlContent)
                              Return pdf.BinaryData
                          End Function)
End Function
$vbLabelText   $csharpLabel

렌더링 옵션

IronPDF를 최적의 성능으로 구성하십시오:

_renderer.RenderingOptions.EnableJavaScript = false; // If JS not needed
_renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
_renderer.RenderingOptions.RenderDelay = 0; // Remove if no JS
_renderer.RenderingOptions.Timeout = 30; // Set reasonable timeout
_renderer.RenderingOptions.EnableJavaScript = false; // If JS not needed
_renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;
_renderer.RenderingOptions.RenderDelay = 0; // Remove if no JS
_renderer.RenderingOptions.Timeout = 30; // Set reasonable timeout
$vbLabelText   $csharpLabel

PDF API를 보안하는 방법?

프로덕션 API에서는 보안이 필수적입니다. 다음은 간단한 API 키 인증 접근 방법입니다:

// Middleware/ApiKeyMiddleware.cs
public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string ApiKeyHeader = "X-API-Key";
    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(ApiKeyHeader, out var apiKey))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("API Key required");
            return;
        }
        // Validate API key (in production, check against database)
        var validApiKey = context.RequestServices
            .GetRequiredService<IConfiguration>()["ApiKey"];
        if (apiKey != validApiKey)
        {
            context.Response.StatusCode = 403;
            await context.Response.WriteAsync("Invalid API Key");
            return;
        }
        await _next(context);
    }
}
// In Program.cs
app.UseMiddleware<ApiKeyMiddleware>();
// Middleware/ApiKeyMiddleware.cs
public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;
    private const string ApiKeyHeader = "X-API-Key";
    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue(ApiKeyHeader, out var apiKey))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("API Key required");
            return;
        }
        // Validate API key (in production, check against database)
        var validApiKey = context.RequestServices
            .GetRequiredService<IConfiguration>()["ApiKey"];
        if (apiKey != validApiKey)
        {
            context.Response.StatusCode = 403;
            await context.Response.WriteAsync("Invalid API Key");
            return;
        }
        await _next(context);
    }
}
// In Program.cs
app.UseMiddleware<ApiKeyMiddleware>();
Imports Microsoft.AspNetCore.Http
Imports Microsoft.Extensions.Configuration
Imports System.Threading.Tasks

' Middleware/ApiKeyMiddleware.vb
Public Class ApiKeyMiddleware
    Private ReadOnly _next As RequestDelegate
    Private Const ApiKeyHeader As String = "X-API-Key"

    Public Sub New(next As RequestDelegate)
        _next = next
    End Sub

    Public Async Function InvokeAsync(context As HttpContext) As Task
        Dim apiKey As String = Nothing
        If Not context.Request.Headers.TryGetValue(ApiKeyHeader, apiKey) Then
            context.Response.StatusCode = 401
            Await context.Response.WriteAsync("API Key required")
            Return
        End If

        ' Validate API key (in production, check against database)
        Dim validApiKey As String = context.RequestServices.GetRequiredService(Of IConfiguration)()("ApiKey")
        If apiKey <> validApiKey Then
            context.Response.StatusCode = 403
            Await context.Response.WriteAsync("Invalid API Key")
            Return
        End If

        Await _next(context)
    End Function
End Class

' In Program.vb
app.UseMiddleware(Of ApiKeyMiddleware)()
$vbLabelText   $csharpLabel

더 고급 인증 시나리오를 위해 고려하십시오:

실제 사례: 송장 생성 API

완전한 구현을 보여주는 실용적인 송장 생성 끝점을 구축해 봅시다. 이 예시는 프로덕션 .NET PDF API가 동적 데이터로 전문 송장을 생성하는 방법을 보여줍니다.

지금 바로 IronPDF으로 시작하세요.
green arrow pointer

먼저, Models 폴더에 새 파일을 만듭니다. 여기서는 파일 이름을 Invoice.cs로 했습니다. 그런 다음 새 파일에 다음 코드를 추가하십시오.

public class Invoice
{
    public string InvoiceNumber { get; set; }
    public DateTime Date { get; set; }
    public string CustomerName { get; set; }
    public string CustomerAddress { get; set; }
    public List<InvoiceItem> Items { get; set; }
    public decimal Tax { get; set; }
}
public class InvoiceItem
{
    public string Description { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal Total => Quantity * UnitPrice;
}
public class Invoice
{
    public string InvoiceNumber { get; set; }
    public DateTime Date { get; set; }
    public string CustomerName { get; set; }
    public string CustomerAddress { get; set; }
    public List<InvoiceItem> Items { get; set; }
    public decimal Tax { get; set; }
}
public class InvoiceItem
{
    public string Description { get; set; }
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public decimal Total => Quantity * UnitPrice;
}
Public Class Invoice
    Public Property InvoiceNumber As String
    Public Property [Date] As DateTime
    Public Property CustomerName As String
    Public Property CustomerAddress As String
    Public Property Items As List(Of InvoiceItem)
    Public Property Tax As Decimal
End Class

Public Class InvoiceItem
    Public Property Description As String
    Public Property Quantity As Integer
    Public Property UnitPrice As Decimal
    Public ReadOnly Property Total As Decimal
        Get
            Return Quantity * UnitPrice
        End Get
    End Property
End Class
$vbLabelText   $csharpLabel

그런 다음 송장 생성기를 위한 새 서비스 파일을 작성해야 합니다. 서비스 폴더에 다음 코드를 추가하세요. 저는 InvoiceService.cs라는 새 파일을 만들었습니다. 이 코드는 우리의 인보이스 PDF 파일의 스타일링과 레이아웃을 처리할 것입니다.

public class InvoiceService
{
    private readonly ChromePdfRenderer _renderer;
    public InvoiceService()
    {
        _renderer = new ChromePdfRenderer();
        _renderer.RenderingOptions.MarginTop = 10;
        _renderer.RenderingOptions.MarginBottom = 10;
        _renderer.RenderingOptions.PrintHtmlBackgrounds = true;
    }
    public byte[] GenerateInvoice(Invoice invoice)
{
    var html = BuildInvoiceHtml(invoice);
    // Add footer with page numbers
    _renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
    {
        MaxHeight = 15,
        HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
        DrawDividerLine = true
    };
    var pdf = _renderer.RenderHtmlAsPdf(html);
    return pdf.BinaryData;
}
    private string BuildInvoiceHtml(Invoice invoice)
    {
        var subtotal = invoice.Items.Sum(i => i.Total);
        var taxAmount = subtotal * (invoice.Tax / 100);
        var total = subtotal + taxAmount;
        var itemsHtml = string.Join("", invoice.Items.Select(item => 
            $@"<tr>
                <td>{item.Description}</td>
                <td class='text-center'>{item.Quantity}</td>
                <td class='text-right'>${item.UnitPrice:F2}</td>
                <td class='text-right'>${item.Total:F2}</td>
            </tr>"));
        return $@"
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; }}
                .invoice-header {{ 
                    background-color: #f8f9fa; 
                    padding: 20px; 
                    margin-bottom: 20px; 
                }}
                table {{ 
                    width: 100%; 
                    border-collapse: collapse; 
                }}
                th, td {{ 
                    padding: 10px; 
                    border-bottom: 1px solid #ddd; 
                }}
                th {{ 
                    background-color: #007bff; 
                    color: white; 
                }}
                .text-right {{ text-align: right; }}
                .text-center {{ text-align: center; }}
                .total-section {{ 
                    margin-top: 20px; 
                    text-align: right; 
                }}
            </style>
        </head>
        <body>
            <div class='invoice-header'>
                <h1>Invoice #{invoice.InvoiceNumber}</h1>
                <p>Date: {invoice.Date:yyyy-MM-dd}</p>
            </div>   
            <div>
                <h3>Bill To:</h3>
                <p>{invoice.CustomerName}<br/>{invoice.CustomerAddress}</p>
            </div>    
            <table>
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Quantity</th>
                        <th>Unit Price</th>
                        <th>Total</th>
                    </tr>
                </thead>
                <tbody>
                    {itemsHtml}
                </tbody>
            </table>
            <div class='total-section'>
                <p>Subtotal: ${subtotal:F2}</p>
                <p>Tax ({invoice.Tax}%): ${taxAmount:F2}</p>
                <h3>Total: ${total:F2}</h3>
            </div>
        </body>
        </html>";
    }
}
public class InvoiceService
{
    private readonly ChromePdfRenderer _renderer;
    public InvoiceService()
    {
        _renderer = new ChromePdfRenderer();
        _renderer.RenderingOptions.MarginTop = 10;
        _renderer.RenderingOptions.MarginBottom = 10;
        _renderer.RenderingOptions.PrintHtmlBackgrounds = true;
    }
    public byte[] GenerateInvoice(Invoice invoice)
{
    var html = BuildInvoiceHtml(invoice);
    // Add footer with page numbers
    _renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter
    {
        MaxHeight = 15,
        HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
        DrawDividerLine = true
    };
    var pdf = _renderer.RenderHtmlAsPdf(html);
    return pdf.BinaryData;
}
    private string BuildInvoiceHtml(Invoice invoice)
    {
        var subtotal = invoice.Items.Sum(i => i.Total);
        var taxAmount = subtotal * (invoice.Tax / 100);
        var total = subtotal + taxAmount;
        var itemsHtml = string.Join("", invoice.Items.Select(item => 
            $@"<tr>
                <td>{item.Description}</td>
                <td class='text-center'>{item.Quantity}</td>
                <td class='text-right'>${item.UnitPrice:F2}</td>
                <td class='text-right'>${item.Total:F2}</td>
            </tr>"));
        return $@"
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; }}
                .invoice-header {{ 
                    background-color: #f8f9fa; 
                    padding: 20px; 
                    margin-bottom: 20px; 
                }}
                table {{ 
                    width: 100%; 
                    border-collapse: collapse; 
                }}
                th, td {{ 
                    padding: 10px; 
                    border-bottom: 1px solid #ddd; 
                }}
                th {{ 
                    background-color: #007bff; 
                    color: white; 
                }}
                .text-right {{ text-align: right; }}
                .text-center {{ text-align: center; }}
                .total-section {{ 
                    margin-top: 20px; 
                    text-align: right; 
                }}
            </style>
        </head>
        <body>
            <div class='invoice-header'>
                <h1>Invoice #{invoice.InvoiceNumber}</h1>
                <p>Date: {invoice.Date:yyyy-MM-dd}</p>
            </div>   
            <div>
                <h3>Bill To:</h3>
                <p>{invoice.CustomerName}<br/>{invoice.CustomerAddress}</p>
            </div>    
            <table>
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Quantity</th>
                        <th>Unit Price</th>
                        <th>Total</th>
                    </tr>
                </thead>
                <tbody>
                    {itemsHtml}
                </tbody>
            </table>
            <div class='total-section'>
                <p>Subtotal: ${subtotal:F2}</p>
                <p>Tax ({invoice.Tax}%): ${taxAmount:F2}</p>
                <h3>Total: ${total:F2}</h3>
            </div>
        </body>
        </html>";
    }
}
Imports System
Imports System.Linq

Public Class InvoiceService
    Private ReadOnly _renderer As ChromePdfRenderer

    Public Sub New()
        _renderer = New ChromePdfRenderer()
        _renderer.RenderingOptions.MarginTop = 10
        _renderer.RenderingOptions.MarginBottom = 10
        _renderer.RenderingOptions.PrintHtmlBackgrounds = True
    End Sub

    Public Function GenerateInvoice(invoice As Invoice) As Byte()
        Dim html = BuildInvoiceHtml(invoice)
        ' Add footer with page numbers
        _renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter With {
            .MaxHeight = 15,
            .HtmlFragment = "<center><i>{page} of {total-pages}</i></center>",
            .DrawDividerLine = True
        }
        Dim pdf = _renderer.RenderHtmlAsPdf(html)
        Return pdf.BinaryData
    End Function

    Private Function BuildInvoiceHtml(invoice As Invoice) As String
        Dim subtotal = invoice.Items.Sum(Function(i) i.Total)
        Dim taxAmount = subtotal * (invoice.Tax / 100)
        Dim total = subtotal + taxAmount
        Dim itemsHtml = String.Join("", invoice.Items.Select(Function(item) 
            $"<tr>
                <td>{item.Description}</td>
                <td class='text-center'>{item.Quantity}</td>
                <td class='text-right'>${item.UnitPrice:F2}</td>
                <td class='text-right'>${item.Total:F2}</td>
            </tr>"))
        Return $"
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body {{ font-family: Arial, sans-serif; }}
                .invoice-header {{ 
                    background-color: #f8f9fa; 
                    padding: 20px; 
                    margin-bottom: 20px; 
                }}
                table {{ 
                    width: 100%; 
                    border-collapse: collapse; 
                }}
                th, td {{ 
                    padding: 10px; 
                    border-bottom: 1px solid #ddd; 
                }}
                th {{ 
                    background-color: #007bff; 
                    color: white; 
                }}
                .text-right {{ text-align: right; }}
                .text-center {{ text-align: center; }}
                .total-section {{ 
                    margin-top: 20px; 
                    text-align: right; 
                }}
            </style>
        </head>
        <body>
            <div class='invoice-header'>
                <h1>Invoice #{invoice.InvoiceNumber}</h1>
                <p>Date: {invoice.Date:yyyy-MM-dd}</p>
            </div>   
            <div>
                <h3>Bill To:</h3>
                <p>{invoice.CustomerName}<br/>{invoice.CustomerAddress}</p>
            </div>    
            <table>
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Quantity</th>
                        <th>Unit Price</th>
                        <th>Total</th>
                    </tr>
                </thead>
                <tbody>
                    {itemsHtml}
                </tbody>
            </table>
            <div class='total-section'>
                <p>Subtotal: ${subtotal:F2}</p>
                <p>Tax ({invoice.Tax}%): ${taxAmount:F2}</p>
                <h3>Total: ${total:F2}</h3>
            </div>
        </body>
        </html>"
    End Function
End Class
$vbLabelText   $csharpLabel

마지막으로 API를 사용하여 새 인보이스를 접근 및 생성하기 위해 새 컨트롤러를 만들어야 합니다.

[ApiController]
[Route("api/[controller]")]
public class InvoiceController : ControllerBase
{
    private readonly InvoiceService _invoiceService;
    public InvoiceController(InvoiceService invoiceService)
    {
        _invoiceService = invoiceService;
    }
    [HttpPost("generate")]
    public IActionResult GenerateInvoice([FromBody] Invoice invoice)
    {
        try
        {
            var pdfBytes = _invoiceService.GenerateInvoice(invoice);
            var fileName = $"Invoice_{invoice.InvoiceNumber}.pdf";
            return File(pdfBytes, "application/pdf", fileName);
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Error generating invoice: {ex.Message}");
        }
    }
}
[ApiController]
[Route("api/[controller]")]
public class InvoiceController : ControllerBase
{
    private readonly InvoiceService _invoiceService;
    public InvoiceController(InvoiceService invoiceService)
    {
        _invoiceService = invoiceService;
    }
    [HttpPost("generate")]
    public IActionResult GenerateInvoice([FromBody] Invoice invoice)
    {
        try
        {
            var pdfBytes = _invoiceService.GenerateInvoice(invoice);
            var fileName = $"Invoice_{invoice.InvoiceNumber}.pdf";
            return File(pdfBytes, "application/pdf", fileName);
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Error generating invoice: {ex.Message}");
        }
    }
}
Imports Microsoft.AspNetCore.Mvc

<ApiController>
<Route("api/[controller]")>
Public Class InvoiceController
    Inherits ControllerBase

    Private ReadOnly _invoiceService As InvoiceService

    Public Sub New(invoiceService As InvoiceService)
        _invoiceService = invoiceService
    End Sub

    <HttpPost("generate")>
    Public Function GenerateInvoice(<FromBody> invoice As Invoice) As IActionResult
        Try
            Dim pdfBytes = _invoiceService.GenerateInvoice(invoice)
            Dim fileName = $"Invoice_{invoice.InvoiceNumber}.pdf"
            Return File(pdfBytes, "application/pdf", fileName)
        Catch ex As Exception
            Return StatusCode(500, $"Error generating invoice: {ex.Message}")
        End Try
    End Function
End Class
$vbLabelText   $csharpLabel

인보이스 출력

IronPDF를 사용하여 .NET PDF API를 생성하는 방법: 그림 7 - PDF 인보이스 출력

컨테이너 배포 고려사항

이 튜토리얼은 로컬 개발에 중점을 두지만, PDF API를 컨테이너화하는 간단한 개요는 다음과 같습니다:

기본 Dockerfile

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["PdfApiService.csproj", "."]
RUN dotnet restore
COPY . .
RUN dotnet build -c Release -o /app/build
FROM build AS publish
RUN dotnet publish -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
# IronPDF requires additional dependencies on Linux
RUN apt-get update && apt-get install -y \
    libgdiplus \
    libc6-dev \
    libx11-dev \
    && rm -rf /var/lib/apt/lists/*     
ENTRYPOINT ["dotnet", "PdfApiService.dll"]
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["PdfApiService.csproj", "."]
RUN dotnet restore
COPY . .
RUN dotnet build -c Release -o /app/build
FROM build AS publish
RUN dotnet publish -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
# IronPDF requires additional dependencies on Linux
RUN apt-get update && apt-get install -y \
    libgdiplus \
    libc6-dev \
    libx11-dev \
    && rm -rf /var/lib/apt/lists/*     
ENTRYPOINT ["dotnet", "PdfApiService.dll"]
The provided code is a Dockerfile written for building and running a .NET application, not C# code. Dockerfiles are not converted to VB.NET as they are not programming language code but configuration scripts for Docker. If you have C# code that needs conversion to VB.NET, please provide that code instead.
$vbLabelText   $csharpLabel

귀하의 .NET PDF API에 대한 상세한 배포 가이드는 여기를 참조하세요:

에러 처리 모범 사례

보다 신뢰성 있는 프로그램을 위해, 최선의 방법은 아래와 같이 일관된 오류 응답을 위한 전역 에러 핸들러를 구현하는 것입니다:

// Middleware/ErrorHandlingMiddleware.cs
public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;
    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }
    private static async Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = 500;
        var response = new
        {
            error = "An error occurred processing your request",
            message = ex.Message
        };
        await context.Response.WriteAsync(JsonSerializer.Serialize(response));
    }
}
// Middleware/ErrorHandlingMiddleware.cs
public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;
    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }
    private static async Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = 500;
        var response = new
        {
            error = "An error occurred processing your request",
            message = ex.Message
        };
        await context.Response.WriteAsync(JsonSerializer.Serialize(response));
    }
}
Imports System.Text.Json
Imports Microsoft.AspNetCore.Http
Imports System.Threading.Tasks

Public Class ErrorHandlingMiddleware
    Private ReadOnly _next As RequestDelegate

    Public Sub New(next As RequestDelegate)
        _next = next
    End Sub

    Public Async Function InvokeAsync(context As HttpContext) As Task
        Try
            Await _next(context)
        Catch ex As Exception
            Await HandleExceptionAsync(context, ex)
        End Try
    End Function

    Private Shared Async Function HandleExceptionAsync(context As HttpContext, ex As Exception) As Task
        context.Response.ContentType = "application/json"
        context.Response.StatusCode = 500
        Dim response = New With {
            .error = "An error occurred processing your request",
            .message = ex.Message
        }
        Await context.Response.WriteAsync(JsonSerializer.Serialize(response))
    End Function
End Class
$vbLabelText   $csharpLabel

특정 IronPDF 문제 해결 시나리오에 대해서는 IronPDF 문제 해결 가이드를 참조하세요.

결론

이제 다양한 문서 생성 시나리오를 처리할 수 있는 ASP.NET Core 및 IronPDF를 사용한 견고한 .NET PDF API를 구축했습니다. 이 REST API는 응용 프로그램에서 중앙 집중식 PDF 작업을 위한 견고한 기반을 제공합니다.

핵심 요약:

  • IronPDF는 Chrome 기반의 렌더링을 통해 Web API 프로젝트에서 PDF 생성을 쉽게 만듭니다.
  • IronPDF의 고급 편집 도구를 사용하여 기존 PDF 문서를 편집하기 위해 Web API를 쉽게 조정할 수 있습니다.
  • RESTful 설계 원칙은 PDF API가 직관적이고 유지보수가 용이함을 보장합니다.
  • 적절한 오류 처리 및 보안 조치는 프로덕션에 필수적입니다.
  • 비동기 작업 및 캐싱을 통한 성능 최적화는 확장성을 개선합니다.
  • 확장 가능한 문서 솔루션을 통해 데스크톱 및 웹 애플리케이션에 대한 지원을 받으실 수 있습니다.

IronPDF는 개발자가 PDF 문서를 생성하고, PDF 파일을 저장하고, HTML을 효율적으로 변환할 수 있게 하여 최신 .NET Framework 응용 프로그램에 필수적인 PDF 문서 API로 만듭니다.

다음 단계

프로덕션 .NET PDF API에서 IronPDF를 구현할 준비가 되었나요? 여기에서 다음 행동을 취하세요:

  1. 무료 체험판 시작하기 - 개발 환경에서 IronPDF를 전체 기능을 가지고 테스트하십시오
  2. 고급 기능 탐색하기 - 디지털 서명, PDF 폼 및 기타 고급 PDF 기능을 확인하십시오
  3. 안심하고 확장하기 - 귀하의 프로덕션 API 요구에 맞는 라이선스 옵션을 검토하십시오

오늘 .NET PDF API를 구축하여 IronPDF로 전체 응용 프로그램 생태계의 문서 생성을 간소화 하세요!

자주 묻는 질문

.NET PDF API란 무엇인가요?

.NET PDF API는 개발자가 .NET 애플리케이션 내에서 PDF 콘텐츠를 생성, 편집 및 추출할 수 있도록 하는 라이브러리입니다. 복잡한 PDF 작업을 단순화하고 PDF 파일 관리의 효율성을 보장합니다.

.NET PDF API가 내 애플리케이션에 어떤 이점을 제공할 수 있나요?

.NET PDF API는 인보이스, 보고서, 증명서 또는 계약서를 생성하는 등 PDF 파일 관리를 하는 데 있어 일관성, 유지 보수성 및 확장성을 제공하여 애플리케이션을 향상시킬 수 있습니다.

.NET PDF API의 일반적인 사용 사례는 무엇인가요?

.NET PDF API의 일반적인 사용 사례는 데스크톱 및 웹 애플리케이션 내에서 인보이스 생성, 보고서 작성, 증명서 생산 및 계약 관리 등을 포함합니다.

IronPDF는 어떻게 PDF 생성 작업을 간소화하나요?

IronPDF는 문서 콘텐츠, PDF 페이지 및 양식 필드의 쉬운 관리를 가능하게 하는 강력한 라이브러리를 제공하여 PDF 생성 작업을 간소화하여 애플리케이션의 유지 관리 및 확장을 쉽게 할 수 있게 합니다.

IronPDF는 PDF 양식 필드를 처리할 수 있나요?

네, IronPDF는 PDF 문서 내의 양식을 생성, 채우고 데이터를 추출할 수 있도록 PDF 양식 필드를 효율적으로 관리할 수 있습니다.

IronPDF는 데스크톱 및 웹 애플리케이션 모두에 적합한가요?

물론입니다. IronPDF는 데스크톱 및 웹 애플리케이션 간의 원활한 작업을 위해 설계되어 일관되고 확장 가능한 PDF 관리 솔루션을 제공합니다.

IronPDF는 .NET 개발자에게 신뢰할 수 있는 선택이 되는 이유는 무엇인가요?

IronPDF는 사용의 용이성, 종합적인 기능 및 PDF 작업을 간소화하는 능력 덕분에 .NET 개발자에게 신뢰할 수 있는 선택입니다. 이는 생산성과 애플리케이션 성능을 향상시킵니다.

IronPDF는 PDF 추출 기능을 지원하나요?

네, IronPDF는 PDF 추출 기능을 지원하며 PDF 문서에서 텍스트, 이미지 및 기타 데이터를 효율적으로 추출할 수 있도록 합니다.

IronPDF는 PDF 관리의 확장성을 어떻게 향상시키나요?

IronPDF는 성능을 희생하지 않고 증가하는 요구를 처리할 수 있는 중앙 집중식 PDF 생성 서비스를 제공하여 확장성을 향상시키며 성장하는 애플리케이션에 이상적입니다.

IronPDF는 .NET 애플리케이션에 어떤 종류의 지원을 제공하나요?

IronPDF는 .NET 애플리케이션을 위한 광범위한 지원을 제공하며, 자세한 문서, 샘플 코드 및 PDF 기능 통합을 도와주는 응답성이 좋은 지원 팀을 포함합니다.

IronPDF .NET 10과 완벽하게 호환됩니까?

네 — IronPDF는 .NET 10과 완전 호환됩니다. .NET 10이 도입하는 모든 성능, 언어 및 런타임 향상을 지원하며, .NET 6, 7, 8 및 9와 마찬가지로 .NET 10 프로젝트에서 바로 사용할 수 있습니다.

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

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

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

아이언 서포트 팀

저희는 주 5일, 24시간 온라인으로 운영합니다.
채팅
이메일
전화해