C#를 사용하여 URL을 PDF로 변환

이 문서에서는 C#을 사용하여 URL을 PDF로 변환하는 방법에 대해 설명합니다. 여기의 지침을 따르면 환경을 설정하고, 단계 목록과 **C#을 사용하여 URL을 PDF로 변환하는 샘플 코드를 얻을 수 있습니다. 원하는 출력을 만들기 위해 출력 PDF 페이지에 대한 사용자 지정 설정도 공유됩니다.

C#을 사용하여 URL을 PDF로 변환하는 단계

  1. Aspose.PDF for .NET을 사용하여 URL을 PDF로 변환하도록 환경을 설정합니다.
  2. PDF로 변환하기 위한 URL과 출력 PDF 페이지를 구성하기 위한 HtmlLoadOptions을 정의합니다.
  3. HTTP 요청을 하기 위한 HttpClient 객체를 생성합니다.
  4. URL에 Get 요청을 보내고 응답을 기다립니다.
  5. 요청이 성공했는지 확인하고 응답 내용을 스트림으로 받습니다.
  6. 스트림에서 PDF 문서를 생성하고 디스크에 save합니다.

이 단계에서는 C#을 사용하여 웹사이트 페이지를 PDF로 변환하는 프로세스를 설명합니다. 출력 PDF 페이지 설정을 정의하고, HttpClient 클래스의 인스턴스를 만들고, URL에 Get 요청을 보내고, 응답 스트림을 페치하고, 페이지 설정을 사용하여 Document 객체에 전달합니다. 마지막으로 URL 콘텐츠에서 생성된 출력 PDF를 디스크에 저장합니다.

C#을 사용한 URL 링크를 PDF로 변환하는 코드

// Importing required namespaces
using System;
using System.IO;
using System.Net.Http;
using Aspose.Pdf;
// Defining a namespace for the project
namespace HtmlToPdfConverter
{
// Main class of the program
class ConverterApp
{
// Entry point of the program
static void Main(string[] args)
{
// Initialize and apply Aspose.PDF license
License pdfLicense = new License();
pdfLicense.SetLicense("Aspose_License.lic");
// Convert an online HTML page to PDF
GeneratePdfFromWebPage();
}
// Method to fetch and convert an HTML webpage to a PDF document
private static void GeneratePdfFromWebPage()
{
// Define the webpage URL to be converted
const string webpageUrl = "https://docs.aspose.com/";
// Configure PDF page settings for conversion
var pdfOptions = new HtmlLoadOptions(webpageUrl)
{
PageInfo =
{
Width = 1200, // Setting custom page width
Height = 850, // Setting custom page height
IsLandscape = false // Keeping portrait orientation
}
};
// Fetch the webpage content and create a PDF document
using (var pdfDocument = new Document(FetchWebContentAsStream(webpageUrl), pdfOptions))
{
// Save the generated PDF file
pdfDocument.Save("Converted_WebPage.pdf");
}
}
// Method to retrieve the content of a webpage as a stream
static Stream FetchWebContentAsStream(string webpageUrl)
{
// Initialize HTTP client to make web requests
HttpClient httpClient = new HttpClient();
// Send a GET request and retrieve the response
HttpResponseMessage webResponse = httpClient.GetAsync(webpageUrl, HttpCompletionOption.ResponseHeadersRead).Result;
// Ensure the response was successful
webResponse.EnsureSuccessStatusCode();
// Return the webpage content as a stream
return webResponse.Content.ReadAsStreamAsync().Result;
}
}
}

이 코드는 C#을 사용하여 웹 페이지 링크를 PDF로 변환하는 방법을 보여주었습니다. HtmlLoadOptions 클래스를 사용하여 글꼴을 포함하는 플래그, 입력 인코딩 설정, 페이지 레이아웃 옵션, 페이지 여백 등과 같은 추가 설정을 적용할 수 있습니다. WarningHandler를 사용하여 경고를 처리하기 위한 콜백을 설정할 수 있습니다.

이 튜토리얼은 C#을 사용하여 PDF 문서에 대한 링크를 변경하는 방법을 안내했습니다. PDF 파일에 하이퍼링크를 추가하려면 C#을 사용하여 PDF에 하이퍼링크를 추가하는 방법에 대한 문서를 참조하세요.

 한국인