.NET에서 HTML을 PDF로 변환

개요

이 문서는 C#을 사용하여 HTML을 PDF로 변환하는 방법을 설명합니다. 다음 주제를 다룹니다.

다음 코드 스니펫은 Aspose.PDF.Drawing 라이브러리와도 함께 사용할 수 있습니다.

Aspose.PDF for .NET는 기존 HTML 문서를 PDF로 원활하게 변환할 수 있는 PDF 조작 API입니다. HTML을 PDF로 변환하는 과정은 유연하게 맞춤 설정할 수 있습니다.

HTML을 PDF로 변환

다음 C# 코드 샘플은 HTML 문서를 PDF로 변환하는 방법을 보여줍니다.

HTML을 PDF로 변환

  1. HtmlLoadOptions 클래스의 인스턴스를 생성합니다.
  2. Document 객체를 초기화합니다.
  3. Document.Save() 메서드를 호출하여 출력 PDF 문서를 저장합니다.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document using HtmlLoadOptions
    var options = new Aspose.Pdf.HtmlLoadOptions();

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "ConvertHTMLtoPDF_out.pdf");
    }
}

HTML을 PDF로 변환하는 고급 기능

HTML 변환 엔진에는 변환 프로세스를 제어할 수 있는 여러 옵션이 있습니다.

미디어 쿼리 지원

미디어 쿼리는 다양한 장치에 맞춤형 스타일 시트를 제공하는 인기 있는 기술입니다. HtmlMediaType 속성을 사용하여 장치 유형을 설정할 수 있습니다.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvancedMediaType()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document using HtmlLoadOptions with Print media type
    var options = new HtmlLoadOptions
    {
        // Set Print or Screen mode
        HtmlMediaType = Aspose.Pdf.HtmlMediaType.Print
    };

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "ConvertHTMLtoPDFAdvancedMediaType_out.pdf");
    }
}

글꼴 포함(비활성화) 설정

HTML 페이지는 종종 로컬 폴더, Google Fonts 등에서 가져온 글꼴을 사용합니다. IsEmbedFonts 속성을 사용하여 문서에 글꼴을 포함할지 여부를 제어할 수 있습니다.

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedEmbedFonts()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     // Load the HTML file into a document using HtmlLoadOptions with the font embedding option set
     var options = new Aspose.Pdf.HtmlLoadOptions
     {
         // Disable font embedding
         IsEmbedFonts = false
     };

     // Open HTML document
     using (var document = new Aspose.Pdf.Document(dataDir + "test_fonts.html", options))
     {
         // Save PDF document
         document.Save(dataDir + "ConvertHTMLtoPDFAdvanced_EmbedFonts_out.pdf");
     }
 }

외부 리소스 로딩 관리

Conversion Engine은 HTML 문서와 연결된 특정 리소스의 로딩을 제어할 수 있는 메커니즘을 제공합니다.
HtmlLoadOptions 클래스에는 리소스 로더의 동작을 정의할 수 있는 CustomLoaderOfExternalResources 속성이 있습니다.
예를 들어 모든 PNG 이미지를 단일 이미지 test.jpg 로 교체하고, 외부 URL을 내부 URL로 바꾸어야 한다고 가정해 보겠습니다.
이를 위해 사용자 정의 로더 SamePictureLoader 를 정의하고 CustomLoaderOfExternalResources 를 해당 이름으로 지정하면 됩니다.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvanced_DummyImage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document with a custom resource loader for external images
    var options = new Aspose.Pdf.HtmlLoadOptions
    {
        CustomLoaderOfExternalResources = SamePictureLoader
    };

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "html_test.pdf");
    }
}

private static Aspose.Pdf.LoadOptions.ResourceLoadingResult SamePictureLoader(string resourceURI)
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();
    Aspose.Pdf.LoadOptions.ResourceLoadingResult result;

    if (resourceURI.EndsWith(".png"))
    {
        byte[] resultBytes = File.ReadAllBytes(dataDir + "test.jpg");
        result = new Aspose.Pdf.LoadOptions.ResourceLoadingResult(resultBytes)
        {
            // Set MIME Type
            MIMETypeIfKnown = "image/jpeg"
        };
    }
    else
    {
        result = new Aspose.Pdf.LoadOptions.ResourceLoadingResult(GetContentFromUrl(resourceURI));
    }
    return result;
}

private static byte[] GetContentFromUrl(string url)
{
    var httpClient = new System.Net.Http.HttpClient();
    return httpClient.GetByteArrayAsync(url).GetAwaiter().GetResult();
}

모든 HTML 콘텐츠를 단일 페이지에 렌더링

Aspose.PDF for .NET는 HTML 파일을 PDF 형식으로 변환할 때 모든 콘텐츠를 단일 페이지에 렌더링하는 기능을 제공합니다. 예를 들어 출력 크기가 한 페이지를 초과하는 HTML 콘텐츠가 있는 경우, 옵션을 사용하여 출력 데이터를 단일 PDF 페이지에 렌더링할 수 있습니다. 이 옵션을 활성화하려면 HtmlLoadOptions 클래스에 IsRenderToSinglePage 플래그가 추가되었습니다. 아래 코드 스니펫은 이 기능을 사용하는 방법을 보여줍니다.

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedSinglePageRendering()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     // Initialize HtmlLoadOptions
     var options = new Aspose.Pdf.HtmlLoadOptions
     {
         // Set Render to single page property
         IsRenderToSinglePage = true
     };

     // Open PDF document
     using (var document = new Aspose.Pdf.Document(dataDir + "HTMLToPDF.html", options))
     {
         // Save PDF document
         document.Save(dataDir + "RenderContentToSamePage_out.pdf");
     }
 }

SVG 데이터와 함께 HTML 렌더링

Aspose.PDF for .NET는 HTML 페이지를 PDF 문서로 변환하는 기능을 제공합니다. HTML은 페이지에 SVG 그래픽 요소를 태그 형태로 추가할 수 있기 때문에 Aspose.PDF도 이러한 데이터를 결과 PDF 파일로 변환하는 것을 지원합니다. 다음 코드 스니펫은 SVG 그래픽 태그가 포함된 HTML 파일을 태그가 지정된 PDF 문서로 변환하는 방법을 보여줍니다.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFWithSVG()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Initialize HtmlLoadOptions
    var options = new Aspose.Pdf.HtmlLoadOptions(Path.GetDirectoryName(dataDir + "HTMLSVG.html"));

    // Initialize Document object
    using (var document = new Aspose.Pdf.Document(dataDir + "HTMLSVG.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "RenderHTMLwithSVGData_out.pdf");
    }
}

HTML 태그에서 논리 구조 생성

접근성 요구 사항을 충족하려면 PDF 문서에 읽기 순서를 정의하고, 화면 판독기가 문서의 삽화 부분을 설명할 수 있도록 대체 텍스트를 제공하며, 내용의 계층 구조를 표시하는 논리 구조 요소가 포함되어야 합니다.

많은 HTML 문서가 이미 이러한 유형의 논리 구조를 포함하고 있습니다. Aspose.PDF는 HTML‑to‑PDF 변환 중에 이를 보존하고 PDF로 전달할 수 있습니다.

HtmlLoadOptions.CreateLogicalStructure 속성을 true 로 설정하면 PDF 논리 구조 요소를 사용하여 원본 HTML 문서의 구조를 복제합니다.

웹 페이지를 PDF로 변환

웹 페이지를 변환하는 것은 로컬 HTML 문서를 변환하는 것과 약간 다릅니다. 웹 페이지 내용을 PDF 형식으로 변환하려면 먼저 HttpClient 인스턴스를 사용해 HTML 페이지 내용을 가져오고, Stream 객체를 생성한 뒤, 해당 내용을 Document 객체에 전달하고 PDF 형식으로 렌더링하면 됩니다.

웹 서버에 호스팅된 웹 페이지를 PDF로 변환할 때:

웹 페이지를 PDF로 변환

  1. HttpClient 객체를 사용해 페이지 내용을 읽어옵니다.
  2. HtmlLoadOptions 객체를 인스턴스화하고 기본 URL을 설정합니다.
  3. 스트림 객체를 전달하면서 Document 객체를 초기화합니다.
  4. 필요에 따라 페이지 크기 및/또는 방향을 설정합니다.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvanced_WebPage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    const string url = "https://en.wikipedia.org/wiki/Aspose_API";

    // Set page size A3 and Landscape orientation;   
    var options = new Aspose.Pdf.HtmlLoadOptions(url)
    {
        PageInfo =
        {
            Width = 842,
            Height = 1191,
            IsLandscape = true
        }
    };

    // Load the web page content as a stream and create a PDF document
    using (var document = new Aspose.Pdf.Document(GetContentFromUrlAsStream(url), options))
    {
        // Save PDF document
        document.Save(dataDir + "html_test.pdf");
    }
}

private static Stream GetContentFromUrlAsStream(string url, System.Net.ICredentials credentials = null)
{
    using (var handler = new System.Net.Http.HttpClientHandler { Credentials = credentials })
    using (var httpClient = new System.Net.Http.HttpClient(handler))
    {
        return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
    }
}

웹 페이지를 PDF로 변환할 때 자격 증명 제공

때때로 인증 및 접근 권한이 필요한 HTML 파일을 변환해야 할 경우가 있습니다. 이는 권한이 있는 사용자만 페이지 내용을 가져올 수 있도록 하기 위함이며, HTML 내부에서 참조되는 일부 리소스/데이터가 인증이 필요한 외부 서버에서 가져와야 하는 상황도 포함됩니다. 이러한 요구를 충족하기 위해 HtmlLoadOptions 클래스에 ExternalResourcesCredentials 속성이 추가되었습니다. 아래 코드 스니펫은 HTML 및 해당 리소스를 요청할 때 자격 증명을 전달하는 단계를 보여줍니다.

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedAuthorized()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     const string url = "http://httpbin.org/basic-auth/user1/password1";
     var credentials = new System.Net.NetworkCredential("user1", "password1");

     var options = new Aspose.Pdf.HtmlLoadOptions(url)
     {
         ExternalResourcesCredentials = credentials
     };

     using (var document = new Aspose.Pdf.Document(GetContentFromUrlAsStream(url, credentials), options))
     {
         // Save PDF document
         document.Save(dataDir + "HtmlTest_out.pdf");
     }
 }

private static Stream GetContentFromUrlAsStream(string url, System.Net.ICredentials credentials = null)
{
    using (var handler = new System.Net.Http.HttpClientHandler { Credentials = credentials })
    using (var httpClient = new System.Net.Http.HttpClient(handler))
    {
        return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
    }
}

MHTML을 PDF로 변환

MHTML은 MIME HTML의 약자로, 이미지, 플래시 애니메이션, Java 애플릿, 오디오 파일 등 외부 링크로 일반적으로 표시되는 리소스를 HTML 코드와 함께 하나의 파일로 결합하는 웹 페이지 아카이브 형식입니다. MHTML 파일의 내용은 MIME 타입 multipart/related를 사용하여 HTML 이메일 메시지처럼 인코딩됩니다. Aspose.PDF for .NET는 HTML 파일을 PDF 형식으로 변환할 수 있으며, Aspose.PDF for .NET 9.0.0 릴리스와 함께 MHTML 파일을 PDF 형식으로 변환하는 새로운 기능을 도입했습니다. 다음 코드 스니펫은 C#으로 MHTML 파일을 PDF 형식으로 변환하는 방법을 보여줍니다:

MHTML을 PDF로 변환

  1. MhtLoadOptions 클래스의 인스턴스를 생성합니다.
  2. Document 객체를 초기화합니다.
  3. Document.Save() 메서드를 호출하여 출력 PDF 문서를 저장합니다.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertMHTtoPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Initialize MhtLoadOptions with page setup
    var options = new Aspose.Pdf.MhtLoadOptions()
    {
        PageInfo = { Width = 842, Height = 1191, IsLandscape = true }
    };

    // Initialize Document object using the MHT file and options
    using (var document = new Aspose.Pdf.Document(dataDir + "fileformatinfo.mht", options))
    {
        // Save PDF document
        document.Save(dataDir + "MhtmlTest_out.pdf");
    }
}