在 Java 中将 URL 转换为 PDF

本简短教程指导如何Java 中将 URL 转换为 PDF。它提供了设置 IDE 的所有详细信息,包括描述 在 Java 中将 URL 转换为 PDF 的步骤列表,以及用于开发基本转换器的示例代码。您可以根据自己的需求自定义输出 PDF。

在 Java 中将链接转换为 PDF 文档的步骤

  1. 设置 IDE 以使用 Aspose.PDF for Java 将 URL 转换为 PDF
  2. 定义要转换为 PDF 的网页 URL
  3. 使用 HtmlLoadOptions 类配置输出 PDF 页面设置和其他参数
  4. 获取网页内容
  5. 通过将内容加载到 Document 对象中生成 PDF 文件
  6. 保存生成的 PDF 文档

这些步骤总结了如何 在 Java 中将 URL 转换为 PDF。定义网页 URL,配置输出 PDF 页面设置并获取网页内容。通过将网页内容加载到 Document 对象中生成 PDF,并使用所需的页面设置保存输出 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 转换器。您可以设置页面边距、默认文本状态、用于将所有内容呈现到单个页面的标志,以及页面布局。如果您已经下载了网页内容,可以通过创建文档对象并将其保存到磁盘来将其转换为 PDF。

在本文中,我们学习了如何将 URL 转换为 PDF。如果您想从 PDF 中提取链接,请参阅关于 在 Java 中从 PDF 中提取链接 的文章。

 简体中文