I want to make a PDF for my webpage using Flying Saucer to generate a PDF. With this below code I am able to generate a PDF but without any style and css.
HTML source code,
<link rel="stylesheet" href="/css/jquery-ui.aeeab65fc7671696263825aac469a40d.css" type="text/css">
<link rel="stylesheet" href="/css/site.bc5eb8ab7795d16a0a599fbaef2adfe6.css" type="text/css">
<script src="js/sidebar.974c35aeb63e852d3fd100cc1c3ab02b.js"></script>
I am trying to set my base URL using renderer.getSharedContext().setUserAgentCallback(new NaiveUserAgent(baseUrl)) but it is not working.
Java code
try {
// Define the URL
String urlcheck = "http://localhost:8888/index.html";
// Establish a URL connection
HttpURLConnection connection = (HttpURLConnection) new URL(urlcheck).openConnection();
connection.setRequestMethod("GET");
// Set up Basic Authentication with username "admin" and password "admin"
String username = "admin";
String password = "admin";
String authString = username + ":" + password;
String encodedAuthString = Base64.getEncoder().encodeToString(authString.getBytes());
connection.setRequestProperty("Authorization", "Basic " + encodedAuthString);
// Check the response code (200 indicates success)
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
// Get the input stream from the connection
InputStream urlInputStream = connection.getInputStream();
LOG.info("PDF START ");
// Create an ITextRenderer instance
ITextRenderer renderer = new ITextRenderer();
// Convert the InputStream to a String
String htmlContent = convertInputStreamToString(urlInputStream);
HtmlCleaner cleaner = new HtmlCleaner();
TagNode rootTagNode = cleaner.clean(htmlContent);
// set up properties for the serializer (optional, see online docs)
CleanerProperties cleanerProperties = cleaner.getProperties();
// use the getAsString method on an XmlSerializer class
XmlSerializer xmlSerializer = new PrettyXmlSerializer(cleanerProperties);
String cleanedHtml = xmlSerializer.getAsString(rootTagNode);
LOG.info("cleanedHtml::"+cleanedHtml);
// Set the HTML content as the document
renderer.setDocumentFromString(cleanedHtml);
// Render to PDF
String baseUrl = "http://localhost:8888";
renderer.getSharedContext().setUserAgentCallback(new NaiveUserAgent(baseUrl)); // Error
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
renderer.layout();
renderer.createPDF(outputStream);
renderer.finishPDF();
} else {
LOG.error("Failed to retrieve URL content. Response code: " + responseCode);
}
}