当前位置:网站首页>Puppetersharp export PDF with page numbers

Puppetersharp export PDF with page numbers

2020-11-10 18:13:38 Li Chaoqiang

PuppeteerSharp(C#)

hypothesis , Before you read this article , We've learned about and created a project about PuppeteerSharp Of demo project .

The introduction of the last article : PuppeteerSharp Headless browser .Net Sdk(Puppeteer)

Today's main introduction , How to export to PDF Add page number to . Actually PuppeteerSharp sdk This feature is already included , Please have a look at :

here , I created a new console project (.net framework 4.6), Here I define a test Method , The code is as follows :

        //  Abstract :
        //     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; }

This note , It has been very clear to us that , We can do this by setting FootTemplate or HeaderTemplate To achieve . The general meaning of annotation is that we can define HTML label , adopt css in class Class name , To display the current page and the total number of pages 、 title 、 Date and other information . The key points are 3 individual : first  PdfOptions Object's DisplayHeaderFooter Property is set to  true. the second , Definition FooterTemplate Templates :

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>",
                        });

Third , If it still doesn't show , Be careful MarginOptions Of Bottom attribute , I set it up here 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 // You can set false Watch the web page show the results ( Note : Not Headless You can't remit PDF)
                }))
                {
                    using (var page = await browser.NewPageAsync())
                    {
                        //http://score.xxxx.com/search/print?clkid=209&xuehao=5706180009  Some fonts display abnormally 
                        //http://score.xxxxx.com/search/print?clkid=195&xuehao=1366180216  Image overflow 

                        await page.GoToAsync("http://score.xxxxxx.com/search/print?clkid=209&xuehao=5706180009");

                        // Through SetViewport Control the window size to determine the size of the snapshot 
                        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\":\"\"});");// Clear font format 
                        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;
            }
        }

then , stay Main Call in function test Method :

      static void Main(string[] args)
        {
            while (true)
            {
                Test().Wait();
                Console.WriteLine("ok!");
                Console.ReadLine();
            }
        }

Let's start it and see how it works !

PuppeteerSharp

版权声明
本文为[Li Chaoqiang]所创,转载请带上原文链接,感谢