前言
本文將使用PuppeteerSharp組件、實(shí)現(xiàn)Html代碼片段生成Jpg照片
PuppeteerSharp地址
https://github.com/hardkoded/puppeteer-sharp
1、安裝引用PuppeteerSharp
使用Nuget界面管理器
搜索 "PuppeteerSharp",找到對(duì)應(yīng)的包點(diǎn)安裝即可。
2、實(shí)現(xiàn)一段Html頁(yè)面
<body>
<div class="box">
<h1>考場(chǎng)號(hào): 01</h1>
<h1>座位號(hào): 01</h1>
<div class="center-box">
<h4>姓 名: 花卷</h4>
<h4>身份證號(hào): 545645456456465</h4>
<h4>準(zhǔn)考證號(hào): 54564545454</h4>
</div>
<div class="botom-box">
<h2>溫馨提示:</h2>
<h3>請(qǐng)核對(duì)信息無(wú)誤后,張貼在準(zhǔn)考證指定位置!</h3>
</div>
</div>
</body>
<style>
.box{
box-sizing: border-box;
padding-top: 10px;
text-align: center;
font-family: fangsong;
}
.box>h1 {
font-size: 46px;
}
.center-box {
text-align: left;
width:290px;
margin:60px auto;
}
.center-box > h4{
font-size: 18px;
}
.botom-box {
text-align: center;
margin-left: 20px;
}
</style>
Html預(yù)覽效果
C#實(shí)現(xiàn)代碼
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true
});
string destFilePath = AppDomain.CurrentDomain.BaseDirectory + "TestImgCreate\\";
if (!Directory.Exists(destFilePath))
{
Directory.CreateDirectory(destFilePath);
}
string outputFile = destFilePath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
using (var page = await browser.NewPageAsync())
{
await page.SetViewportAsync(new ViewPortOptions
{
Width = 425,//圖片寬度
Height = 635//圖片高度
});
await page.SetContentAsync(@"
<html>
<body>
<div class=\""box\"">
<h1>考場(chǎng)號(hào): 01</h1>
<h1>座位號(hào): 01</h1>
<div class=\""center-box\"">
<h4>姓 名: 花卷</h4>
<h4>身份證號(hào): 545645456456465</h4>
<h4>準(zhǔn)考證號(hào): 54564545454</h4>
</div>
<div class=\""botom-box\"">
<h2>溫馨提示:</h2>
<h3>請(qǐng)核對(duì)信息無(wú)誤后,張貼在準(zhǔn)考證指定位置!</h3>
</div>
</div>
</body>
</html>
<style>
.box{
box-sizing: border-box;
padding-top: 10px;
text-align: center;
font-family: fangsong;
}
.box>h1 {
font-size: 46px;
}
.center-box {
text-align: left;
width:290px;
margin:60px auto;
}
.center-box > h4{
font-size: 18px;
}
.botom-box {
text-align: center;
margin-left: 20px;
}
</style>");
ScreenshotOptions screenshotOptions = new ScreenshotOptions();
screenshotOptions.FullPage = true; //是否截取整個(gè)頁(yè)面
screenshotOptions.OmitBackground = false;//是否使用透明背景,而不是默認(rèn)白色背景
screenshotOptions.Quality = 100; //截圖質(zhì)量 0-100(png不可用)
screenshotOptions.Type = ScreenshotType.Jpeg; //截圖格式
await page.ScreenshotAsync(outputFile, screenshotOptions);
}
生成之后發(fā)現(xiàn)樣式?jīng)]有進(jìn)行渲染,效果如下
發(fā)現(xiàn)html中的樣式丟失了,后將Html中的雙引號(hào)替換成單引號(hào)后,樣式可以正常展示,效果如下
如果需要生成PDF文件,只需要進(jìn)行以下修改
await page.ScreenshotAsync(outputFile, screenshotOptions);
->
await page.PdfAsync(outputFile);
文件名稱修改成PDF后綴
轉(zhuǎn)自:小吳的成長(zhǎng)之路
鏈接:cnblogs.com/wuyongfu/p/17243490.html
該文章在 2024/2/27 18:36:15 編輯過(guò)