IRON SUITE 사용하기

HTML to PDF in C# for .NET 개발자 (최고의 가이드)

소개

오늘날의 웹 중심 세계에서 HTML 콘텐츠를 PDF 문서(Portable Document Format)로 변환할 수 있는 능력은 많은 애플리케이션에 중요한 기능입니다. 보고서, 송장에서 PDF 파일을 생성하거나 웹 콘텐츠를 보관함에 있어, HTML을 PDF로 변환하면 워크플로우가 단순해지고 고품질 PDF의 일관된 포맷을 보장합니다. IronPDF와 같은 라이브러리는 동적 콘텐츠 지원, HTML 양식CSSJavaScript의 정밀한 렌더링을 지원하는 개발자 친화적인 방식으로 이 변환을 다루도록 지원합니다.

.NET 개발자에게 적절한 HTML에서 PDF 변환기를 사용하는 것은 효율성, 코드 단순성 및 PDF 생성 품질에 영향을 미칩니다. 현대 라이브러리는 개발자가 HTML 문자열, 전체 웹 페이지 또는 HTML 파일을 몇 줄의 코드로 렌더링된 PDF 문서로 직접 변환할 수 있게 하여 동적 문서, 사용자 지정 헤더 및 인쇄 가능한 웹 콘텐츠 버전을 사용할 수 있게 합니다.

학습 내용

이 가이드에서는 여러 라이브러리를 통해 C#에서 HTML을 PDF로 변환하는 방법을 배우고, PDF 변환 기능, PDF 문서 조작, HTML 양식, 사용자 지정 여백 및 보안 PDF를 포함한 기능을 탐색합니다. 이 기사에서 다룰 주제는 다음과 같습니다:

  1. 왜 HTML에서 PDF 도구를 비교해야 하는가?
  2. IronPDF: HTML에서 PDF 변환
  3. Aspose: HTML에서 PDF 변환
  4. iText 9: HTML에서 PDF 변환
  5. wkhtmltopdf: HTML에서 PDF 변환
  6. PuppeteerSharp: HTML에서 PDF 변환
  7. 결론: IronPDF를 선택하는 이유는?

마지막에는 IronPDF가 개발자 친화적이고 효율적인 HTML에서 PDF 변환 도구로 돋보이는 이유를 이해하게 될 것입니다. 다른 비교 가이드를 반드시 확인하여 IronPDFAspose.PDF, iText 9, wkhtmltopdf, 그리고 PuppeteerSharp 와 비교했을 때, 프로젝트에 가장 잘 맞는지를 확인해보고, 왜 IronPDF가 항상 최고의 선택지인지 알아보십시오.

왜 HTML에서 PDF 도구를 비교해야 하는가?

적절한 HTML에서 PDF 변환 도구를 선택하는 것은 애플리케이션이 성능, 품질, 비용 요구 사항을 충족하는 데 필수적입니다. 다양한 옵션이 제공되며 각각이 다른 PDF 변환 기능을 제공하므로 철저한 비교는 정보에 입각한 결정을 내리는 데 도움이 됩니다. 다음은 고려해야 할 주요 평가 기준입니다:

  • 통합 복잡성: NuGet 패키지 매니저를 사용한 간단한 설치 및 API 통합 탭 설정과 같은 방법으로 기존 .NET 프로젝트와 얼마나 쉽게 통합되는지 확인하십시오.
  • 코드 간소화: 소스 코드를 작성하고 유지 관리하기 쉬운 정도, HTML 문자열 또는 전체 웹 페이지를 생성된 PDF 문서로 변환하기 위해 단 몇 줄만 필요로 하는 최소 코드 예제 포함.
  • 렌더링 정확도: 렌더링 엔진이 HTML 코드, JavaScript 실행, 인쇄 CSS, HTML 양식 및 기타 동적 콘텐츠를 정확하게 처리하고 고품질 PDF를 생산하는 능력.
  • 확장 시 성능: 여러 HTML 페이지 또는 동적 콘텐츠에서 PDF 파일을 생성할 때 과부하 속에서 PDF 변환기가 얼마나 잘 작동하는지 확인하십시오.
  • 라이선스 및 비용 절감 효과: 상업적 라이선스와 같은 가격 모델 및 프로젝트 예산에 대한 적합성.

.NET Core 또는 .NET Framework 프로젝트를 Visual Studio에서 작업할 때 개발자는 이러한 요소를 평가함으로써 기술적 요구 사항과 재정적 제약에 맞는 도구를 선택할 수 있습니다.

IronPDF: HTML에서 PDF로 변환

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 1

IronPDF는 개발자를 위해 특별히 설계된 기능이 풍부한 .NET 라이브러리입니다. 간단한 설정으로 HTML 변환 문자열, 로컬 파일 및 실시간 URL을 PDF로 변환하기 위한 기본 기능을 제공합니다. Chrome 기반 렌더링 엔진은 CSS 및 JavaScript 지원을 포함하여 높은 정확성을 보장합니다. IronPDF는 상용 제품이지만 강력한 지원과 직관적인 API를 제공합니다.

HTML 문자열에서 PDF로

IronPDF를 사용하여 문자열에서 PDF로 HTML을 변환하는 것은 간단합니다. 이 방식은 동적 콘텐츠 생성 또는 작은 HTML 스니펫에 이상적입니다.

예:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        pdf.SaveAs("output.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
        pdf.SaveAs("output.pdf");
    }
}
$vbLabelText   $csharpLabel

생성된 PDF 문서

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 2

설명:

  1. ChromePdfRenderer: IronPDF에서 HTML을 PDF로 변환하기 위한 주요 도구는 ChromePdfRenderer 클래스입니다. 대부분의 사용 사례를 최소한의 설정으로 처리할 수 있도록 사전 구성되어 제공됩니다.
  2. RenderHtmlAsPdf: 이 메서드는 HTML 문자열을 입력으로 받아 PDF 문서를 생성합니다.
  3. SaveAs: 생성된 PDF는 지정된 경로(output.pdf)에 저장됩니다.

로컬 HTML 파일을 PDF로

CSS 또는 JavaScript와 같은 외부 리소스를 포함하는 로컬 HTML 파일을 변환해야 하는 응용 프로그램을 위해 IronPDF는 이를 쉽게 만듭니다.

예:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
        pdf.SaveAs("report.pdf");
    }
}
$vbLabelText   $csharpLabel

입력 HTML 파일

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 3

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 4

설명:

  • RenderHtmlFileAsPdf: 로컬 HTML 파일을 PDF로 변환합니다.
  • 외부 CSS 및 JavaScript 파일과 같은 연결된 리소스를 자동으로 처리합니다.

URL에서 PDF로

IronPDF는 특히 JavaScript를 사용하는 페이지를 포함하여 동적 웹 콘텐츠를 URL에서 PDF로 변환할 때 강력합니다.

예:

using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
        renderer.RenderingOptions.WaitFor.RenderDelay(3000); // Wait up to 3 seconds for JS to load

        PdfDocument pdf = renderer.RenderUrlAsPdf("https://apple.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
using IronPdf;
class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();
        renderer.RenderingOptions.EnableJavaScript = true;
        renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
        renderer.RenderingOptions.WaitFor.RenderDelay(3000); // Wait up to 3 seconds for JS to load

        PdfDocument pdf = renderer.RenderUrlAsPdf("https://apple.com");
        pdf.SaveAs("url-to-pdf.pdf");
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 5

설명:

  • RenderUrlAsPdf: JavaScript로 렌더링된 요소를 포함한 URL 콘텐츠를 가져와서 PDF로 변환합니다.

평결 / 사용 시기

IronPDF는 쉬운 API 통합, 최소한의 코드, PDF 문서를 조작하고 동적 문서, HTML 양식, 사용자 정의 헤더, 웹 콘텐츠의 인쇄 가능한 버전을 생성하는 지원이 필요한 개발자에게 적합합니다. .NET Core 또는 .NET Framework 프로젝트를 Visual Studio에서 작업하기에 이상적입니다.

Aspose: HTML에서 PDF로 변환

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 6

Aspose.PDF는 HTML->PDF 변환 지원과 함께 PDF 조작을 위한 또 다른 강력한 라이브러리입니다. Aspose가 각 변환 시나리오를 어떻게 처리하는지 살펴보겠습니다:

HTML 문자열에서 PDF로

Aspose는 HTML 문자열을 변환할 때 IronPDF에 비해 조금 더 많은 설정이 필요합니다.

예:

using Aspose.Html;
using Aspose.Html.Saving;

Document doc = new Document();
Page page = doc.getPages().Add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().Add(htmlFragment);
doc.Save("HTMLStringUsingDOM.pdf");
using Aspose.Html;
using Aspose.Html.Saving;

Document doc = new Document();
Page page = doc.getPages().Add();
HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
page.getParagraphs().Add(htmlFragment);
doc.Save("HTMLStringUsingDOM.pdf");
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 7

설명:

  • Document doc: 변환된 HTML 문자열을 저장할 새 문서를 생성합니다.
  • Page page: 우리가 만든 빈 문서에 새 페이지를 추가합니다.
  • HtmlFragment htmlFragment: 우리가 변환하려는 HTML 문자열입니다.
  • page.getParagraphs().Add(htmlFragment): 문서에 HTML을 추가합니다.
  • doc.Save: HTML 콘텐츠를 PDF 문서로 저장합니다.

로컬 HTML 파일에서 PDF로

Aspose도 로컬 HTML 파일을 PDF로 변환하지만 IronPDF보다 더 많은 구성 요소가 필요합니다.

예:

using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;

var document = new HTMLDocument("document.html");
var options = new PdfSaveOptions();
Converter.ConvertHTML(document, options, "output.pdf");
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;

var document = new HTMLDocument("document.html");
var options = new PdfSaveOptions();
Converter.ConvertHTML(document, options, "output.pdf");
$vbLabelText   $csharpLabel

입력 HTML:

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 8

산출:

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 9

설명:

  • var document = new HTMLDocument("document.html"): HTML 파일을 불러옵니다.
  • var options: 새 PdfSaveOptions 객체를 생성합니다.
  • Converter.ConvertHTML(): HTML을 PDF로 변환합니다.

URL에서 PDF로

Aspose는 URL에서도 유사한 기능을 제공하지만 추가 설정이 필요합니다.

예:

using System.IO;
using System;
using System.Net.Http;
using Aspose.Pdf;

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.apple.com");
response.EnsureSuccessStatusCode();
string responseFromServer = await response.Content.ReadAsStringAsync();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://www.apple.com");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save("WebPageToPDF_out.pdf");
using System.IO;
using System;
using System.Net.Http;
using Aspose.Pdf;

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://www.apple.com");
response.EnsureSuccessStatusCode();
string responseFromServer = await response.Content.ReadAsStringAsync();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https://www.apple.com");
Document pdfDocument = new Document(stream, options);
pdfDocument.Save("WebPageToPDF_out.pdf");
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 10

설명:

  • dataDir 변수는 생성된 PDF가 저장될 디렉토리를 보유합니다.
  • WebRequest이(가) 위키백과 메인 페이지 URL에 액세스하기 위해 생성되며, 요청에 대한 기본 자격 증명이 사용됩니다.
  • GetResponse() 메서드는 요청을 보내고 응답을 HttpWebResponse로 수신합니다.
  • 응답에서 스트림이 얻어지고, StreamReader는 페이지의 전체 HTML 콘텐츠를 responseFromServer 문자열로 읽습니다.
  • responseFromServer에서 얻은 HTML 콘텐츠는 바이트 배열로 변환된 다음 MemoryStream에 로드됩니다.
  • HtmlLoadOptions은(는) 상대 링크 및 기타 설정을 위한 기본 URL을 지정하는 데 사용됩니다.
  • HTML을 포함하는 메모리 스트림에서 Aspose.Pdf.Document이(가) 생성되고, 문서는 지정된 디렉토리에 PDF로 저장됩니다.

판결 / 사용 시기

Aspose.PDF는 고급 PDF 조작과 변환이 필요한 Enterprise 프로젝트에 가장 적합합니다. 강력하지만 HTML을 PDF로 신속하게 변환하는 작업에는 덜 최적화되었습니다.

iText 9: HTML에서 PDF로 변환하기

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 11

iText 9은 iText PDF 라이브러리의 최신 버전으로, .NET 애플리케이션에서 PDF 문서를 생성하고 조작하기 위한 향상된 기능을 제공합니다. 더 간결하고 확장 가능한 API를 도입하여 성능을 향상시키고 최신 PDF 표준에 대한 더 나은 지원을 제공합니다.

HTML 문자열에서 PDF로

iText 9를 사용하여 HTML 문자열을 PDF 문서로 변환하는 기본 예제가 있습니다.

예:

using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string html = "<h1>Hello World</h1><p>This is a simple PDF generated from HTML.</p>";
        string outputFile = "SimpleHtmlToPdf.pdf";

        using (var pdfStream = new FileStream(outputFile, FileMode.Create))
        {
            HtmlConverter.ConvertToPdf(html, pdfStream);
        }

        System.Console.WriteLine("PDF generated: " + outputFile);
    }
}
using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string html = "<h1>Hello World</h1><p>This is a simple PDF generated from HTML.</p>";
        string outputFile = "SimpleHtmlToPdf.pdf";

        using (var pdfStream = new FileStream(outputFile, FileMode.Create))
        {
            HtmlConverter.ConvertToPdf(html, pdfStream);
        }

        System.Console.WriteLine("PDF generated: " + outputFile);
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 12

로컬 HTML 파일에서 PDF로

iText 9는 HtmlConverter.ConvertToPdf 클래스를 사용하여 HTML 파일 형식을 PDF로 변환할 수 있습니다.

예:

using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string htmlFile = "document.html";
        string outputPdf = "html-file-to-pdf.pdf";

        // Read HTML content from file
        string htmlContent = File.ReadAllText(htmlFile);

        // Convert HTML string to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        System.Console.WriteLine("PDF generated: " + outputPdf);
    }
}
using iText.Html2pdf;
using System.IO;

class Program
{
    static void Main()
    {
        string htmlFile = "document.html";
        string outputPdf = "html-file-to-pdf.pdf";

        // Read HTML content from file
        string htmlContent = File.ReadAllText(htmlFile);

        // Convert HTML string to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        System.Console.WriteLine("PDF generated: " + outputPdf);
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 13

설명:

  • HtmlConverter: HTML 파일을 직접 PDF로 변환합니다.

URL에서 PDF로

iText7은 또한 URL에서 콘텐츠를 변환하는 것을 지원합니다.

예:

using iText.Html2pdf;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string url = "https://apple.com";
        string outputPdf = "url-to-pdf.pdf";

        using var httpClient = new HttpClient();
        // Fetch the HTML content from the URL
        string htmlContent = await httpClient.GetStringAsync(url);

        // Convert HTML content to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        Console.WriteLine("PDF generated: " + outputPdf);
    }
}
using iText.Html2pdf;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string url = "https://apple.com";
        string outputPdf = "url-to-pdf.pdf";

        using var httpClient = new HttpClient();
        // Fetch the HTML content from the URL
        string htmlContent = await httpClient.GetStringAsync(url);

        // Convert HTML content to PDF
        HtmlConverter.ConvertToPdf(htmlContent, new FileStream(outputPdf, FileMode.Create));

        Console.WriteLine("PDF generated: " + outputPdf);
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 14

설명:

  • HttpClient.GetStringAsync(url): URL에서 실제 HTML 콘텐츠를 다운로드합니다.
  • HtmlConverter.ConvertToPdf(htmlContent, …): 가져온 HTML 문자열을 렌더링된 PDF로 변환합니다.

판결 / 사용 시기

iText 9는 PDF 생성, 조작, 그리고 HTML을 PDF로 변환하기 위한 강력하고 Enterprise급 솔루션이 필요한 개발자에게 적합합니다. 생성된 PDF에 대한 정확한 제어가 필요하거나 기존 iText 워크플로와의 통합, 또는 디지털 서명 및 양식과 같은 고급 PDF 기능이 필요할 때 잘 작동합니다. 그러나 간단한 HTML에서 PDF로의 작업에는 IronPDF와 같은 간결한 라이브러리에 비해 iText 9는 무겁고 더 복잡합니다.

wkhtmltopdf: HTML에서 PDF로 변환하기

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 15

아카이브 및 유지보수 상태

wkhtmltopdf는 더 이상 적극적으로 유지보수되고 있지 않습니다란 점을 주의하십시오. 그 GitHub 저장소는 2023년 1월에 공식적으로 아카이브되었으며 읽기 전용으로 표시되었습니다. 이는 미래 업데이트, 버그 수정, 또는 보안 패치가 적용되지 않음을 의미합니다.

개발자에게의 함축: wkhtmltopdf는 매우 기본적인 사용 사례에 여전히 효과적일 수 있지만, 유지보수되지 않는 상태와 구식 렌더링 엔진은 특히 동적 또는 외부 HTML 콘텐츠를 처리하는 프로덕션 환경이나 애플리케이션에서는 위험한 선택입니다.

wkhtmltopdf는 Webkit 렌더링을 사용하여 HTML 파일을 PDF로 변환하는 명령줄 도구입니다. 다양한 시나리오에서 어떻게 작동하는지 설명하겠습니다.

HTML 문자열에서 PDF로

wkhtmltopdf는 HTML 문자열을 먼저 파일에 기록해야 변환할 수 있습니다.

예:

using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.IO;
using System.Diagnostics;
class Program
{
    static void Main(string[] args)
    {
        // HTML string to be converted to PDF
        string html = "<html><body><h1>Hello, World!</h1></body></html>";
        // Write HTML string to temporary file
        string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
        File.WriteAllText(tempHtmlFile, html);
        // Set output PDF path
        string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        // Clean up the temporary HTML file
        File.Delete(tempHtmlFile);
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 16

설명:

  • wkhtmltopdf는 입력 파일이 필요하므로 HTML 문자열을 임시 파일(temp.html)로 먼저 작성합니다.
  • 그런 다음 Process 클래스를 사용하여 임시 HTML 파일의 파일 경로와 원하는 출력 PDF 경로를 인수로 전달하여 wkhtmltopdf 명령을 실행합니다.
  • 변환 후 임시 HTML 파일을 삭제하여 정리합니다.

로컬 HTML 파일에서 PDF로

wkhtmltopdf를 사용하여 로컬 HTML 파일을 PDF로 변환할 때는 HTML 파일의 파일 경로를 직접 지정할 수 있습니다.

예:

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\document.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // Path to the local HTML file
        string htmlFilePath = @"C:\path\to\your\document.html";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 17

설명:

  • 이 예제는 단순히 로컬 HTML 파일(template.html)의 경로와 PDF의 출력 경로를 제공합니다.
  • wkhtmltopdf는 로컬 파일을 직접 처리하여 명령을 간단하게 만듭니다.

URL에서 PDF로

URL을 PDF로 변환하는 것은 wkhtmltopdf로 쉽게 할 수 있습니다. 명령에 URL을 직접 전달하기만 하면 됩니다.

예:

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://apple.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        // URL to be converted to PDF
        string url = "https://apple.com";
        // Path for the output PDF file
        string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
        // Execute wkhtmltopdf command
        Process process = new Process();
        process.StartInfo.FileName = "wkhtmltopdf";
        process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
        process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.Start();
        process.WaitForExit();
        Console.WriteLine($"PDF saved to: {outputPdfFile}");
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 18

설명:

  • 이 예제에서는 wkhtmltopdf이(가) 입력으로 URL을 직접 수락합니다.
  • URL은 wkhtmltopdf에 대한 인수로 전달되며, 출력은 지정된 경로에 PDF로 저장됩니다.

PuppeteerSharp: HTML에서 PDF로 변환하기

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 19

PuppeteerSharp는 Google Puppeteer의 .NET 래퍼로, 헤드리스 Chrome/Chromium에 대한 제어를 제공합니다. JavaScript가 많은 동적 페이지를 렌더링하는 데 뛰어나지만 Chromium 인스턴스를 다운로드하고 관리해야 하므로 부가적인 작업이 필요합니다. Apache 2.0 라이선스 하에 오픈 소스입니다.

HTML 문자열에서 PDF로

Puppeteer는 전체 페이지 렌더링용으로 설계되었기 때문에 HTML 문자열을 변환하려면 파일에 쓰거나 브라우저에서 직접 렌더링해야 합니다.

예:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
       // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync();
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
       // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync();
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();
        string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
        await page.SetContentAsync(htmlContent);
        // Save the page as a PDF
        await page.PdfAsync("html-string-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 20

설명:

  • Puppeteer.LaunchAsync: 헤드리스 모드에서 새로운 Chromium 인스턴스를 시작합니다.
  • page.SetContentAsync: HTML 문자열을 브라우저 페이지에 로드합니다.
  • page.PdfAsync: 로드된 HTML을 PDF로 변환하여 파일로 저장합니다.

로컬 HTML 파일에서 PDF로

PuppeteerSharp를 사용하여 로컬 HTML 파일을 PDF로 변환하려면 파일을 헤드리스 브라우저에 로드하고 PDF를 생성할 수 있습니다.

예:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();

        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");

        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();

        // Load the local HTML file
        await page.GoToAsync("file:///path/to/your/template.html");

        // Save the page as a PDF
        await page.PdfAsync("html-file-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 21

설명:

  • page.GoToAsync: 로컬 HTML 파일을 로드합니다 (올바른 [file://]() 경로를 사용하세요).
  • page.PdfAsync: 로컬 HTML 파일의 내용을 PDF로 변환합니다.

URL에서 PDF로

URL을 PDF로 변환하는 것은 PuppeteerSharp의 핵심 기능 중 하나로, JavaScript가 복잡한 페이지를 처리할 수 있습니다.

예:

using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();

        // Navigate to the URL
        await page.GoToAsync("https://example.com");

        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
using PuppeteerSharp;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // Download the browser if necessary
        await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
        var page = await browser.NewPageAsync();

        // Navigate to the URL
        await page.GoToAsync("https://example.com");

        // Save the page as a PDF
        await page.PdfAsync("url-to-pdf.pdf");
        await browser.CloseAsync();
    }
}
$vbLabelText   $csharpLabel

산출

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 22

설명:

  • page.GoToAsync: 지정된 URL로 이동합니다.
  • page.PdfAsync: URL의 웹 페이지를 PDF로 변환하여 저장합니다.

평결 / 사용 시기

PuppeteerSharp는 현대의 JavaScript가 많은 웹 애플리케이션에서 픽셀 완벽한 렌더링이 필요할 때 이상적입니다. IronPDF보다 복잡하지만 동적 웹 콘텐츠 처리에는 뛰어납니다.

IronPDF 선택해야 하는 이유는 무엇일까요?

IronPDF는 사용의 용이성, 유연성 및 .NET 애플리케이션과의 매끄러운 통합으로 두드러집니다. 구현이 간단하며, HTML, CSS 및 JavaScript 렌더링을 지원하며 추가 설정이나 외부 종속성이 필요하지 않습니다. HTML에서 PDF로의 변환을 넘어서, IronPDF는 다양한 파일 형식에서 PDF 문서 생성, 기존 PDF 문서 편집 및 추가, 워터마크 삽입, PDF 파일 보안 등 광범위한 기능을 제공합니다! 이 라이브러리의 작동 모습을 더 보려면 각 기능이 작동하는 방법을 보여주는 How-to Guides를 확인해 보세요.

결론

C#에서 HTML을 PDF 파일로 변환할 때, 각기 다른 기능과 능력을 제공하는 몇 가지 강력한 도구를 사용할 수 있습니다. IronPDF, Aspose, iText 9, wkhtmltopdfPuppeteerSharp 모두 HTML 콘텐츠를 전문적인 수준의 PDF 문서로 변환하는 강력한 솔루션을 제공합니다. 그러나 프로젝트에 적합한 도구를 선택하려면 통합의 용이성, 동적 콘텐츠 지원, 성능 및 유연성과 같은 요소를 고려해야 합니다.

도구HTML 문자열을 PDF로 변환HTML 파일을 PDF로 변환PDF URL노트
IronPDF 로고
IronPDF
HTML 문자열을 위한 `RenderHtmlAsPdf`로 간단합니다. 사용이 쉽고 .NET 애플리케이션에 매끄럽게 통합됩니다.`RenderHtmlFileAsPdf`를 사용하여 연결된 리소스(CSS, JS)를 자동으로 처리합니다.`RenderUrlAsPdf`를 사용하며 JavaScript가 많은 페이지와 동적 콘텐츠를 지원합니다..NET에 완전히 통합되어 있어 .NET 개발자에게 적합합니다. HTML 문자열, 파일 및 URL을 지원합니다.
Aspose 로고
Aspose
더 많은 설정이 필요합니다. HTML 문자열을 변환하기 위해 `Document` 객체 내에서 `HtmlFragment`를 사용합니다.로컬 HTML 파일 변환을 위해 `HtmlDocument`와 `PdfSaveOptions`가 필요합니다. IronPDF보다 더 많은 구성이 필요합니다.변환 전에 콘텐츠를 가져오기 위해 `WebRequest`를 사용하여 추가 설정이 필요합니다.여러 문서 조작에 강력하지만 설정이 더 복잡할 수 있습니다. 더 복잡한 PDF 필요에 적합합니다.
iText 로고
iText7
`HtmlConverter.ConvertToPdf`를 사용하여 HTML 문자열을 PDF로 변환합니다.`HtmlConverter.ConvertToPdf`를 사용하여 로컬 HTML 파일을 PDF로 변환합니다.로컬 파일 처리와 유사하게 `HtmlConverter.ConvertToPdf`를 사용합니다.HTML에서 PDF로의 변환 이외에도 PDF 조작에 대해 더 많은 제어가 필요한 개발자에게 좋습니다.
wkhtmltopdf 로고
wkhtmltopdf
HTML 문자열을 먼저 파일에 작성하여 변환합니다. 명령줄 도구를 사용하여 PDF를 생성합니다.로컬 HTML 파일 경로를 지정하여 직접 PDF로 변환합니다.명령줄 도구에 URL을 전달하여 직접 PDF로 변환합니다.주로 명령행 도구로 사용되며, .NET에 통합하기 위해 추가 단계가 필요할 수 있습니다. 간단한 변환에 가장 적합합니다.
PuppeteerSharp의 로고
PuppeteerSharp
`page.SetContentAsync`를 사용하여 HTML 문자열을 로드한 다음 `page.PdfAsync`를 사용하여 PDF를 생성합니다.`page.GoToAsync`를 통해 로컬 HTML 파일을 로드한 다음 PDF로 변환합니다.`page.GoToAsync`와 `page.PdfAsync`를 사용하여 URL을 로드하고 이를 PDF로 변환합니다.동적 페이지, 특히 JavaScript가 많은 콘텐츠에 가장 적합합니다. Chromium을 다운로드하고 실행해야 합니다.
  • IronPDF는 .NET에 직접 통합할 수 있고 복잡한 HTML을 포함한 JavaScript 렌더링 페이지를 처리할 수 있는 점에서 두드러집니다. 설치가 간단하고 쉽게 사용할 수 있는 솔루션을 찾는 개발자에게 적합합니다.

  • Aspose는 광범위한 PDF 조작 기능을 제공하지만, 특히 로컬 파일과 외부 리소스를 처리하기 위해서는 HTML에서 PDF로의 변환 기능이 더 많은 구성이 필요합니다.

  • iText 9는 PDF 문서를 만들고자 하는 사람들에게 견고한 기반을 제공하지만, 특히 동적 콘텐츠의 경우 HTML을 PDF로 변환하는 데 추가적인 코딩이 필요할 수 있습니다. 맞춤 PDF 조작이 필요한 프로젝트에 훌륭한 선택입니다.

  • wkhtmltopdf는 명령행 인터페이스를 통해 기본 HTML을 PDF로 변환하기에 이상적이지만, 전체 .NET 라이브러리의 통합성과 유연성이 부족합니다.

  • PuppeteerSharp는 헤드리스 Chrome을 활용하여 복잡하고 동적인 웹 페이지를 렌더링하고 이를 PDF로 변환하는 도구입니다. 특히 JavaScript가 많은 콘텐츠를 다룰 때 유용합니다.

대부분의 .NET 개발자에게는, IronPDF를 사용해 보아 오늘 그 강력한 기능을 직접 경험해 보는 것이 가치 있습니다. 새로운 PDF 문서를 생성하거나 기존 PDF를 편집하는 것을 포함하여 IronPDF의 전체 기능을 직접 탐색해보세요. IronPDF를 설치하고 무료 체험판을 사용하여 직접 사용해 보세요. 오늘 PDF 워크플로우를 향상시키는 방법을 확인해 보세요.

궁극적으로, 적합한 도구는 특정 요구 사항에 따라 달라지지만, 여기에서 논의된 옵션을 통해 귀하의 프로젝트에 맞는 완벽한 솔루션을 찾을 수 있습니다.

참고: Aspose, iText, wkhtmltopdf, 그리고 PuppeteerSharp는 각각의 소유자의 등록 상표입니다. 본 사이트는 Aspose, iText, wkhtmltopdf 또는 Puppeteer와 제휴, 보증 또는 후원 관계가 없습니다. 모든 제품명, 로고 및 브랜드는 해당 소유자의 자산입니다. 비교는 정보 제공 목적만을 위해 제공되며 작성 당시의 공개적으로 이용 가능한 정보를 기반으로 합니다.