Last active
March 7, 2025 10:30
Convert URL to PDF in Java. For details: https://kb.aspose.com/pdf/java/convert-url-to-pdf-in-java/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment