이 빠른 튜토리얼은 Python으로 URL을 PDF로 변환하는 방법을 안내합니다. IDE 설정 방법, 단계별 목록 및 Python으로 링크를 PDF로 변환하는 샘플 코드가 포함되어 있습니다. 요구 사항에 따라 다양한 매개변수를 설정하여 출력 PDF 파일을 사용자 정의하는 방법을 배우게 됩니다.
Python으로 웹 페이지를 PDF로 변환하는 단계
- Aspose.PDF for Python via .NET을 사용하여 URL을 PDF로 변환할 환경 설정
- 웹 페이지 URL을 정의하고 HtmlLoadOptions를 선언하여 출력 페이지 설정을 사용자 정의
- 지정된 URL에 GET 요청을 보내고 페이지 내용을 바이트 스트림으로 가져오기
- 웹 페이지 스트림에서 PDF 문서 생성
- 출력 문서를 PDF 파일로 저장
이 단계들은 Python으로 URL을 PDF로 변환하는 방법을 설명합니다. 대상 URL, 출력 PDF 페이지 옵션을 설정하고 GET 요청을 보내 웹 페이지 내용을 가져옵니다. 웹 페이지 스트림을 Document 클래스 객체에 로드하고 출력 문서를 PDF로 저장합니다.
Python으로 링크를 PDF 문서로 변환하는 코드
# Import necessary modules | |
import requests # For making HTTP requests to fetch webpage content | |
from io import BytesIO # To handle byte stream data | |
from aspose.pdf import Document # Import Aspose PDF's Document class for PDF operations | |
import aspose.pdf as ap # Import Aspose PDF module for additional functionality | |
def fetch_web_content_as_stream(webpage_url): | |
""" | |
Fetches the content of a webpage and returns it as a byte stream. | |
Parameters: | |
webpage_url (str): The URL of the webpage to fetch. | |
Returns: | |
BytesIO: A byte stream of the webpage content. | |
""" | |
response = requests.get(webpage_url) # Send GET request to the specified URL | |
response.raise_for_status() # Raise an error if the request fails | |
return BytesIO(response.content) # Return the content as a byte stream | |
def main(): | |
""" | |
Main function that converts a webpage into a PDF document. | |
""" | |
# Set Aspose.PDF license (assumes "license.lic" file is available) | |
license = ap.License() | |
license.set_license("license.lic") | |
# Define the webpage URL to be converted | |
webpage_url = "https://docs.aspose.com/" | |
# Configure HTML-to-PDF conversion options | |
pdf_options = ap.HtmlLoadOptions(webpage_url) # Create HTML load options with the webpage URL | |
pdf_options.page_info.width = 1200 # Set PDF page width | |
pdf_options.page_info.height = 850 # Set PDF page height | |
# Fetch webpage content as a byte stream | |
with fetch_web_content_as_stream(webpage_url) as web_stream: | |
# Uncomment the lines below to print and inspect the webpage content | |
# print(web_stream.read().decode('utf-8', errors='ignore')) | |
# web_stream.seek(0) # Reset the stream position after reading | |
# Create a PDF document from the webpage stream | |
pdf_document = Document(web_stream, pdf_options) | |
# Save the converted PDF document | |
pdf_document.save("Converted_WebPage.pdf") | |
print("URL converted to PDF successfully") | |
# Run the main function if the script is executed directly | |
if __name__ == "__main__": | |
main() |
이 코드는 Python으로 URL 링크를 PDF로 변환하는 방법을 보여줍니다. 변환 오류에 대한 콜백 함수를 구현하기 위한 경고 핸들러, 단일 페이지에 콘텐츠를 렌더링하기 위한 플래그 및 입력 인코딩을 설정합니다. 두 줄의 코드 주석을 해제하여 스트림을 읽고 출력하여 웹 페이지 내용을 검사할 수 있습니다.
이 글에서는 URL을 PDF로 변환하는 방법을 배웠습니다. HTML 콘텐츠를 PDF로 변환하려면 Python으로 HTML을 PDF로 변환하는 방법 글을 참조하세요.