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 系列文章: