Java에서 URL을 PDF로 변환하기

이 간단한 튜토리얼은 Java에서 URL을 PDF로 변환하는 방법을 안내합니다. IDE 설정, Java에서 URL을 PDF로 변환하는 과정을 설명하는 단계별 목록과 간단한 변환기 개발을 위한 샘플 코드가 포함되어 있습니다. 출력 PDF를 사용자 요구 사항에 맞게 사용자 정의할 수 있는 다양한 옵션도 제공됩니다.

Java에서 링크를 PDF 문서로 변환하는 단계

  1. Aspose.PDF for Java를 사용하여 URL을 PDF로 변환할 IDE 설정
  2. 변환할 웹 페이지 URL 정의
  3. HtmlLoadOptions 클래스를 사용하여 출력 PDF 페이지 설정 및 기타 매개변수 구성
  4. 웹 페이지 콘텐츠 가져오기
  5. 웹 페이지 콘텐츠를 Document 객체에 로드하여 PDF 파일 생성
  6. 생성된 PDF 문서 저장

이 단계들은 Java에서 URL을 PDF로 변환하는 방법을 요약한 것입니다. 웹 페이지 URL을 정의하고, 출력 PDF 페이지 설정을 구성한 후, 웹 페이지 콘텐츠를 가져옵니다. 그 후, 웹 페이지 콘텐츠에서 PDF Document 객체를 생성하고 원하는 페이지 설정으로 PDF를 저장합니다.

Java에서 웹사이트 페이지를 PDF로 변환하는 코드

import com.aspose.pdf.*;
import java.io.*;
import java.net.*;
public class HtmlToPdfConverter {
public static void main(String[] args) throws Exception {
// Initialize and apply Aspose.PDF license
License pdfLicense = new License();
pdfLicense.setLicense("license.lic");
// Convert an online HTML page to PDF
generatePdfFromWebPage();
System.out.println("Webpage Link to PDF process finished.");
}
// Method to fetch and convert an HTML webpage to a PDF document
private static void generatePdfFromWebPage() {
// Define the webpage URL to be converted
final String webpageUrl = "https://docs.aspose.com/";
// Configure PDF page settings for conversion
HtmlLoadOptions pdfOptions = new HtmlLoadOptions(webpageUrl);
pdfOptions.getPageInfo().setWidth(1200); // Setting custom page width
pdfOptions.getPageInfo().setHeight(850); // Setting custom page height
pdfOptions.getPageInfo().setLandscape(false); // Keeping portrait orientation
// Fetch the webpage content and create a PDF document
try (InputStream webContentStream = fetchWebContentAsStream(webpageUrl);
Document pdfDocument = new Document(webContentStream, pdfOptions)) {
// Save the generated PDF file
pdfDocument.save("Converted_WebPage.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
// Method to retrieve the content of a webpage as a stream
private static InputStream fetchWebContentAsStream(String webpageUrl) throws IOException {
// Create a URL object from the given webpage URL
URL url = new URL(webpageUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Allow input stream retrieval
connection.setDoInput(true);
// Establish the connection
connection.connect();
// Return the webpage content as an input stream
return connection.getInputStream();
}
}

이 코드는 Java에서 URL 링크를 PDF로 변환하는 변환기를 개발하는 방법을 보여줍니다. 페이지 여백, 기본 텍스트 상태, 모든 콘텐츠를 하나의 페이지에 렌더링할지 여부를 나타내는 플래그 및 페이지 레이아웃을 설정할 수 있습니다. 이미 웹 페이지 콘텐츠를 다운로드한 경우, 이를 Document 객체를 생성하고 디스크에 저장하여 PDF로 변환할 수 있습니다.

이 기사에서는 URL을 PDF로 변환하는 방법을 배웠습니다. PDF에서 링크를 추출하려면 Java에서 PDF에서 링크 추출하기 기사를 참조하세요.

 한국인