是否有一种方法将html渲染成PNG那样的图像?我知道这是可能的与画布,但我想渲染标准的html元素,如div为例。
当前回答
有很多选择,它们都有各自的优点和缺点。
选项1:使用API
ApiFlash(基于chrome) EvoPDF(有html选项) Grabzit HTML/CSS图像API ...
Pros
执行Javascript 近乎完美渲染 正确使用缓存选项时快速 缩放由api处理 精确计时,视口,… 大多数时候,他们提供的是免费方案
Cons
如果你打算经常使用它们,就不是免费的
选项2:使用众多可用库中的一个
dom-to-image Wkhtmltoimage(包含在wkhtmltopdf工具中) IMGKit(用于ruby和基于wkhtmltoimage) Imgkit(适用于python,基于wkhtmltoimage) python-webkit2png ...
Pros
大多数时候,转换是相当快的
Cons
坏的呈现 不执行javascript 不支持最近的网页功能(FlexBox,高级选择器,网页字体,盒子大小,媒体查询,…) 有时不容易安装 缩放复杂
选项3:使用PhantomJs和包装器库
PhantomJs node-webshot(用于PhantomJs的javascript包装库) ...
Pros
执行Javascript 很快
Cons
坏的呈现 不支持最近的网页功能(FlexBox,高级选择器,网页字体,盒子大小,媒体查询,…) 缩放复杂 不那么容易使它工作,如果有图像要加载…
选项4:使用Chrome Headless和一个包装器库
Chrome无头 chrome-devtools-protocol Puppeteer (Chrome无头浏览器的javascript包装库) ...
Pros
执行Javascript 近乎完美渲染
Cons
要得到想要的结果并不容易: 页面加载时间 视窗尺寸 缩放复杂 相当慢,甚至更慢,如果html包含外部链接
披露:我是ApiFlash的创始人。我尽力提供了一个诚实而有用的答案。
其他回答
使用这段代码,它一定会工作:
<脚本type = " text / javascript”> 美元(文档)。Ready (function () { setTimeout(函数(){ downloadImage (); }, 1000) }); 函数downloadImage () { html2canvas (document.querySelector(“# dvContainer”))。然后(canvas => { a = document.createElement('a'); document.body.appendChild(一个); A.download = "test.png"; a.href = canvas.toDataURL(); a.click (); }); } > < /脚本
不要忘记在你的程序中包含Html2CanvasJS文件。 https://html2canvas.hertzen.com/dist/html2canvas.js
仅用JavaScript无法100%准确地做到这一点。
有一个Qt Webkit工具,还有一个python版本。如果你想自己做,我已经成功地用可可:
[self startTraverse:pagesArray performBlock:^(int collectionIndex, int pageIndex) {
NSString *locale = [self selectedLocale];
NSRect offscreenRect = NSMakeRect(0.0, 0.0, webView.frame.size.width, webView.frame.size.height);
NSBitmapImageRep* offscreenRep = nil;
offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
pixelsWide:offscreenRect.size.width
pixelsHigh:offscreenRect.size.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bitmapFormat:0
bytesPerRow:(4 * offscreenRect.size.width)
bitsPerPixel:32];
[NSGraphicsContext saveGraphicsState];
NSGraphicsContext *bitmapContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep];
[NSGraphicsContext setCurrentContext:bitmapContext];
[webView displayRectIgnoringOpacity:offscreenRect inContext:bitmapContext];
[NSGraphicsContext restoreGraphicsState];
// Create a small + large thumbs
NSImage *smallThumbImage = [[NSImage alloc] initWithSize:thumbSizeSmall];
NSImage *largeThumbImage = [[NSImage alloc] initWithSize:thumbSizeLarge];
[smallThumbImage lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[offscreenRep drawInRect:CGRectMake(0, 0, thumbSizeSmall.width, thumbSizeSmall.height)];
NSBitmapImageRep *smallThumbOutput = [[NSBitmapImageRep alloc] initWithFocusedViewRect:CGRectMake(0, 0, thumbSizeSmall.width, thumbSizeSmall.height)];
[smallThumbImage unlockFocus];
[largeThumbImage lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[offscreenRep drawInRect:CGRectMake(0, 0, thumbSizeLarge.width, thumbSizeLarge.height)];
NSBitmapImageRep *largeThumbOutput = [[NSBitmapImageRep alloc] initWithFocusedViewRect:CGRectMake(0, 0, thumbSizeLarge.width, thumbSizeLarge.height)];
[largeThumbImage unlockFocus];
// Write out small
NSString *writePathSmall = [issueProvider.imageDestinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@-collection-%03d-page-%03d_small.png", locale, collectionIndex, pageIndex]];
NSData *dataSmall = [smallThumbOutput representationUsingType:NSPNGFileType properties: nil];
[dataSmall writeToFile:writePathSmall atomically: NO];
// Write out lage
NSString *writePathLarge = [issueProvider.imageDestinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@-collection-%03d-page-%03d_large.png", locale, collectionIndex, pageIndex]];
NSData *dataLarge = [largeThumbOutput representationUsingType:NSPNGFileType properties: nil];
[dataLarge writeToFile:writePathLarge atomically: NO];
}];
希望这能有所帮助!
你可以添加引用HtmlRenderer到你的项目,并执行以下操作:
string htmlCode ="<p>This is a sample html.</p>";
Image image = HtmlRender.RenderToImage(htmlCode ,new Size(500,300));
我也在思考这个问题。 我发现这是解决你问题的最好办法
我们可以使用javascript的HTML -to-image库将HTML代码转换为图像
NPM安装html-to-image
HTML代码
<div>
<div id="capture">
<p>
<span>Heading Of Image</span><br></br>
<span>This is color Image</span><br></br>
<img src="Your/ImagePath/ifany.jpg" width="100%" />
<span>Footer Of the Image</span>
</p>
</div>
<h2>Generated Image</h2>
<div id="real">
</div></div>
Javascript代码
var htmlToImage = require('html-to-image');
var node = document.getElementById('capture');
htmlToImage.toJpeg(node, { quality: 1, backgroundColor: "#FFFFFF", height: node.clientHeight, width: node.clientWidth })
.then(function (dataUrl) {
var img = new Image();
img.src = dataUrl;
var div = document.getElementById("real")
div.appendChild(img)
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});
通过这个例子,你现在可以在<div>标签中看到你的图像,其中id = 'real'。 现在可以在代码中添加保存和下载或上传图像选项。
你可以使用像wkhtmltopdf这样的HTML转PDF工具。然后你可以使用像imagemagick这样的PDF图像工具。不可否认,这是服务器端,一个非常复杂的过程…
推荐文章
- CSS div元素-如何显示水平滚动条只?
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 如何指定一个元素后包装在css flexbox?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?
- 使用“!”的含义是什么?重要的”?