PuppeteerSharp(C#)
假设,在你阅读本篇文章前,已经了解并且创建了一个关于PuppeteerSharp的demo项目。
上篇文章的介绍: PuppeteerSharp无头浏览器.Net Sdk(Puppeteer)
今天主要介绍下,怎样向导出的PDF中添加页码。其实PuppeteerSharp sdk已经包含了此功能,请看:
这里,我新建了一个控制台项目(.net framework 4.6),这里我定义了一个test方法,代码如下:
// 摘要:
// HTML template for the print footer. Should be valid HTML markup with following
// classes used to inject printing values into them: date - formatted print date
// title - document title url - document location pageNumber - current page number
// totalPages - total pages in the document
public string FooterTemplate { get; set; }
这段注释,已经很清楚的告诉我们,我们可要通过设置FootTemplate或HeaderTemplate来实现。注释的大概意思就是说我们可要通过定义HTML标签,通过css中class类名,来显示当前页和总页数、标题、日期等信息。关键点有3个:第一个 PdfOptions对象的DisplayHeaderFooter属性设置为 true。第二个,定义FooterTemplate模板:
FooterTemplate = "<div style='font-size:12px;text-align:center;width:100%;border:0;color:#000;margin:0;padding:0;'><span style='vertical-align:bottom;color:#000;font-size:12px' class='pageNumber'></span>/<span style='vertical-align:bottom;' class='totalPages'></span></div>",
});
第三个,如果仍然不显示,注意MarginOptions的Bottom属性,我这里设置的45px。
/// <summary>
///
/// </summary>
/// <returns></returns>
static async Task Test()
{
try
{
// await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions()
{
Headless = true //侦测时可设定false观察网页显示结果(注:非Headless时不能汇出PDF)
}))
{
using (var page = await browser.NewPageAsync())
{
//http://score.xxxx.com/search/print?clkid=209&xuehao=5706180009 部分字体显示异常
//http://score.xxxxx.com/search/print?clkid=195&xuehao=1366180216 图片溢出
await page.GoToAsync("http://score.xxxxxx.com/search/print?clkid=209&xuehao=5706180009");
//透过SetViewport控制视窗大小决定抓图尺寸
await page.SetViewportAsync(new ViewPortOptions
{
Width = 960,
Height = 1000,
IsMobile = false,
IsLandscape = false,
});
await page.WaitForTimeoutAsync(1500);//25min
await page.EvaluateExpressionAsync("$(\"span\").css({\"font-family\":\"\"});");//清除字体格式
await page.PdfAsync($"D:\\FreewayTraffic\\Snapshot.pdf", new PdfOptions()
{
PrintBackground = true,
MarginOptions = new PuppeteerSharp.Media.MarginOptions()
{
Left = "20px",
Right = "20px",
Bottom = "45px",
Top = "10px",
},
DisplayHeaderFooter = true,
Format = PuppeteerSharp.Media.PaperFormat.A4,
FooterTemplate = "<div style='font-size:12px;text-align:center;width:100%;border:0;color:#000;margin:0;padding:0;'><span style='vertical-align:bottom;color:#000;font-size:12px' class='pageNumber'></span>/<span style='vertical-align:bottom;' class='totalPages'></span></div>",
});
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
然后,在Main函数中调用test方法:
static void Main(string[] args)
{
while (true)
{
Test().Wait();
Console.WriteLine("ok!");
Console.ReadLine();
}
}
启动起来看看效果吧!
PuppeteerSharp 系列文章: