As there are no answers, I will explain my workaround. Instead of trying to find how to request from Chrome to print the current page, I went down another route.
For this example we will try to download the results page from Google on the query 'example':
- Navigate with
driver.get("google.com")
, input the query 'example', click 'Google Search'
- Wait for the results page to load
- Retrieve the page source with
driver.getPageSource()
- Parse source with e.g. Jsoup in order to remap all relative links to point to an endpoint defined for this purpose (explained below) - example to
localhost:8080
. Link './style.css' would become 'localhost:8080/style.css'
- Save HTML to a file, e.g. named 'query-example'
- Run
chrome --print-to-pdf localhost:8080/search?id=query-example
What will happen is that chrome will request the HTML from our controller, and for resources defined in the HTML we return, it will go to our controller - since we remapped relative links - which will in turn forward that request to the real location of the resource - google.com. Below is an example Spring controller, and note that the example is incomplete and is here only as a guidance.
@RestController
@RequestMapping
public class InternationalOffloadRestController {
@RequestMapping(method = RequestMethod.GET, value = "/search/html")
public String getHtml(@RequestParam("id") String id) {
File file = new File("location of the HTML file", id);
try (FileInputStream input = new FileInputStream(file)) {
return IOUtils.toString(input, HTML_ENCODING);
}
}
@RequestMapping("/**") // forward all remapped links to google.com
public void forward(HttpServletResponse httpServletResponse, ...) {
URI uri = new URI("https", null, "google.com", -1,
request.getRequestURI(), request.getQueryString(), null);
httpServletResponse.setHeader("Location", uri.toString());
httpServletResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…