【发布时间】:2018-03-08 09:07:39
【问题描述】:
我正在尝试从网页下载图像,该图像在调用后立即由 JavaScript(使用 html2canvas)返回。因此我使用了HTMLUnit库,但直到现在我还没有成功。
不幸的是,只下载了一个错误的 png 文件,大约 140kb。 Windows 无法打开它(例如绘制或预览)。
我的 HTML 页面的代码片段(在 div-element #div 加载后立即执行:
function saveMap() {
var element = $("#div");
html2canvas(element, {
useCORS: true,
onrendered: function(canvas) {
var dataUrl= canvas.toDataURL("image/png");
var a = $("<a>")
.attr("href", dataUrl)
.attr("download", "test.png")
.appendTo("body");
a[0].click();
a.remove();
}
});
}
Java-Code 尝试下载返回的 png-File:
WebClient webClient = new WebClient(BrowserVersion.CHROME);
try {
HtmlPage page1 = webClient.getPage( new URI("file:///D:/path/to/page/sample.html").toURL() );
webClient.waitForBackgroundJavaScript(5000);
InputStream is = page1.getWebResponse().getContentAsStream();
File f = new File("test.png");
OutputStream os = new FileOutputStream(f);
byte[] bytes = new byte[2048];
int b = 0;
while ((b = is.read()) != -1)
{
os.write(bytes, 0, b);
}
os.close();
is.close();
} catch (FailingHttpStatusCodeException | IOException | URISyntaxException e) {
e.printStackTrace();
}
完整的 HTML 页面:
<!DOCTYPE html>
<html>
<head>
<style>
html, body, #div {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="html2canvas.js"></script>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
</head>
<body>
<div id="div"></div>
<script>
// Some init stuff for div and after completion the following:
saveMap();
function saveMap() {
var element = $("#div");
html2canvas(element, {
useCORS: true,
onrendered: function(canvas) {
var dataUrl= canvas.toDataURL("image/png");
var a = $("<a>")
.attr("href", dataUrl)
.attr("download", "test.png")
.appendTo("body");
a[0].click();
a.remove();
}
});
}
</script>
</body>
</html>
【问题讨论】:
-
能否请您添加完整的示例 html 页面。
-
刚刚将完整的 html 源代码添加到我的初始帖子中。 HTML页面应该没有问题,因为当我通过普通浏览器(例如Chrome)调用它时,下载工作正常并且图像很好。
标签: javascript java html htmlunit html2canvas