Esempio n. 1
0
        public async Task <byte[]> ConvertHtmlToPdf(string html, string cssPath)
        {
            var pdfOptions = new PdfOptions();

            var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions
            {
                Path = _chromiumPath
            });

            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            using var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                ExecutablePath = browserFetcher.RevisionInfo(BrowserFetcher.DefaultRevision).ExecutablePath,
                Headless       = true
            });

            var page = await browser.NewPageAsync();

            await page.SetContentAsync(html);

            await page.AddStyleTagAsync(new AddTagOptions { Path = cssPath });

            var stream = await page.PdfStreamAsync(pdfOptions);

            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);

            return(ms.ToArray());
        }
Esempio n. 2
0
        public static async Task Main(string[] args)
        {
            var options = new LaunchOptions
            {
                Headless = true
            };

            Console.WriteLine("Downloading chromium");
            using var browserFetcher = new BrowserFetcher();
            await browserFetcher.DownloadAsync();

            Console.WriteLine("Navigating google");
            using (var browser = await Puppeteer.LaunchAsync(options))
                using (var page = await browser.NewPageAsync())
                {
                    await page.GoToAsync("http://www.google.com");

                    Console.WriteLine("Generating PDF");
                    await page.PdfAsync(Path.Combine(Directory.GetCurrentDirectory(), "google.pdf"));

                    Console.WriteLine("Export completed");

                    if (!args.Any(arg => arg == "auto-exit"))
                    {
                        Console.ReadLine();
                    }
                }
        }
Esempio n. 3
0
        public async Task Should_render_properly(string name, string url)
        {
            using (var browserFetcher = new BrowserFetcher())
            {
                await browserFetcher.DownloadAsync();
            }

            await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless        = true,
                DefaultViewport = new ViewPortOptions
                {
                    Height      = 800,
                    IsLandscape = true,
                    IsMobile    = false,
                    Width       = 1000
                },
                Args = new string[]
                {
                    "--no-sandbox"
                }
            });

            await using var page = await browser.NewPageAsync();

            await page.GoToAsync(_.ClientManager.Options.Url + url + "?skip-setup");

            await page.ScreenshotAsync($"__{name}.jpg");

            var diff = ImageSharpCompare.CalcDiff($"__{name}.jpg", $"Assets/{name}.jpg");

            Assert.InRange(diff.MeanError, 0, 10);
        }
Esempio n. 4
0
        private static void DownloadBrowser()
        {
            var browserFetcher = new BrowserFetcher();

            browserFetcher.DownloadProgressChanged += (sender, e) =>
            {
                Logger.Debug(
                    $"Browser download progress {e.ProgressPercentage}% - {e.BytesReceived}/{e.TotalBytesToReceive}bytes");
            };

            Logger.Debug("Download browser");
            AsyncHelper.RunSync(() => browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision));

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var       executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);
                const int _0755          =
                    S_IRUSR | S_IXUSR | S_IWUSR
                    | S_IRGRP | S_IXGRP
                    | S_IROTH | S_IXOTH;
                chmod(executablePath, _0755);
            }

            Logger.Debug("Browser downloaded");
        }
Esempio n. 5
0
        public async Task Usage()
        {
            var outputFile = Path.Combine(BaseDirectory, "Usage.pdf");
            var fileInfo   = new FileInfo(outputFile);

            if (fileInfo.Exists)
            {
                fileInfo.Delete();
            }

            #region PdfAsync

            using var browserFetcher = new BrowserFetcher();
            await browserFetcher.DownloadAsync();

            await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });

            await using var page = await browser.NewPageAsync();

            await page.GoToAsync("http://www.google.com");                    // In case of fonts being loaded from a CDN, use WaitUntilNavigation.Networkidle0 as a second param.

            await page.EvaluateExpressionHandleAsync("document.fonts.ready"); // Wait for fonts to be loaded. Omitting this might result in no text rendered in pdf.

            await page.PdfAsync(outputFile);

            #endregion

            Assert.True(File.Exists(outputFile));
        }
Esempio n. 6
0
        private static async Task <FileInfo> DownloadAsync(DirectoryInfo directory, int revision)
        {
            await _semaphoreSlim.WaitAsync();

            if (!directory.Exists)
            {
                directory.Create();
            }
            var fetchOpt = new BrowserFetcherOptions()
            {
                Host = Environment.GetEnvironmentVariable("PUPPETEER_CHROMIUM_DOWNLOADHOST"),
                Path = directory.FullName
            };
            var fetcher = new BrowserFetcher(fetchOpt);

            if (revision < 1)
            {
                string revisionStr = Environment.GetEnvironmentVariable("PUPPETEER_CHROMIUM_REVISION");
                if (!int.TryParse(revisionStr, out revision) || revision < 1)
                {
                    revision = BrowserFetcher.DefaultRevision;
                }
            }
            var info = await fetcher.DownloadAsync(revision).ConfigureAwait(false);

            _semaphoreSlim.Release();
            if (!string.IsNullOrWhiteSpace(info.ExecutablePath))
            {
                return(new FileInfo(info.ExecutablePath));
            }
            TryGetChromeExePath(directory, out var exeFile);
            return(exeFile);
        }
        public async Task <Browser> BuildBrowser()
        {
            var downloadPath = Path.Combine(Path.GetTempPath(), "puppeteer");

            var browserFetcherOptions = new BrowserFetcherOptions {
                Path = downloadPath
            };
            var browserFetcher = new BrowserFetcher(browserFetcherOptions);
            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);

            var executableDirectory = Directory.EnumerateDirectories(
                Directory.EnumerateDirectories(downloadPath)
                .First())
                                      .First();

            var executableFilename = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                                    ? "chrome.exe"
                                    : "chrome";

            var executablePath = Path.Combine(executableDirectory, executableFilename);

            var options = new LaunchOptions {
                Headless = true, ExecutablePath = executablePath
            };

            var browser = await Puppeteer.LaunchAsync(options);

            return(browser);
        }
Esempio n. 8
0
        static PicGen()
        {
            var downloadsFolder = Path.GetTempPath();
            var option          = new BrowserFetcherOptions
            {
                Path = downloadsFolder
            };
            var fetcher = new BrowserFetcher(option);

            fetcher.DownloadAsync(BrowserFetcher.DefaultRevision).Wait();
            var browser = Puppeteer.LaunchAsync(new LaunchOptions
            {
                ExecutablePath = fetcher.RevisionInfo(BrowserFetcher.DefaultRevision).ExecutablePath,
                Headless       = true,
                Args           = new[]
                {
                    !isProd ? "--proxy-server=winip:1080" : ""
                }
            }).Result;

            page = browser.NewPageAsync().Result;
            page.SetViewportAsync(new ViewPortOptions
            {
                Height = 800,
                Width  = 1300
            }).Wait();
        }
Esempio n. 9
0
        public async Task GetActivity(string mssv)
        {
            var fetcher = new BrowserFetcher();

            if (await fetcher.CanDownloadAsync(BrowserFetcher.DefaultRevision))
            {
                await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);
            }

            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = true
            });

            var page = await browser.NewPageAsync();

            await page.GoToAsync("http://ctct.ueh.edu.vn/modules.php?name=xemdiemmacle", WaitUntilNavigation.DOMContentLoaded);

            await page.TypeAsync("input[id='madoi']", mssv);

            await page.Keyboard.PressAsync("Enter");

            await page.WaitForNavigationAsync();

            string res = await page.GetContentAsync();

            Debug.WriteLine(res);

            System.IO.File.WriteAllText(@"D:\demo.txt", res);

            await page.CloseAsync();

            await browser.CloseAsync();
        }
Esempio n. 10
0
        public static IApplicationBuilder UseBrowserFetcher(this IApplicationBuilder app)
        {
            BrowserFetcher browserFetcher = new BrowserFetcher();

            browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision).GetAwaiter().GetResult();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var path = Launcher.GetExecutablePath();
                Bash($"chmod 777 {path}");
            }
            return(app);

            void Bash(string cmd)
            {
                var escapedArgs = cmd.Replace("\"", "\\\"");

                var process = new Process()
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName  = "/bin/bash",
                        Arguments = $"-c \"{escapedArgs}\"",
                        RedirectStandardOutput = true,
                        UseShellExecute        = false,
                        CreateNoWindow         = true,
                    }
                };

                process.Start();
                string result = process.StandardOutput.ReadToEnd();

                process.WaitForExit();
            }
        }
Esempio n. 11
0
 private void InitializeEnvironment()
 {
     // var executablePath = PuppeteerSharp.Launcher.GetExecutablePath();
     UpdateLog($"正在检测浏览器环境");
     try
     {
         var bf = new BrowserFetcher()
         {
             //WebProxy = new WebProxy("http://127.0.0.1:10809")
         };
         bf.DownloadProgressChanged += (s, e) =>
         {
             UpdateLog($"正在下载 {BrowserFetcher.DefaultRevision},已完成 {e.ProgressPercentage} %");
         };
         var revisionInfo = bf.DownloadAsync(BrowserFetcher.DefaultRevision).GetAwaiter().GetResult();
         BuildBrowser();
         //var page = _browser.NewPageAsync().GetAwaiter().GetResult();
         UpdateLog($"环境初始化完成,Downloaded={revisionInfo.Downloaded} ExecutablePath={revisionInfo.ExecutablePath} FolderPath={revisionInfo.FolderPath} {revisionInfo.Local} Platform={revisionInfo.Platform} Revision={revisionInfo.Revision}");
     }
     catch (Exception ex)
     {
         XtraMessageBox.Show(this, $"初始化环境出错,{ex.Message}");
         Environment.Exit(-1);
     }
 }
Esempio n. 12
0
        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripProgressBar1.Maximum = 100;
            toolStripProgressBar1.Value   = 0;
            Task.Run(async() =>
            {
                var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions()
                {
                    Host = "http://cdn.npm.taobao.org/dist"
                });

                try
                {
                    var cp = Process.GetProcessesByName("chrome");
                    if (cp.Length > 0)
                    {
                        foreach (var item in cp)
                        {
                            if (!item.HasExited && item.MainModule.FileName == browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision))
                            {
                                item.Kill();
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
                browserFetcher.DownloadProgressChanged += Bf_DownloadProgressChanged;
                await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);
            });
        }
Esempio n. 13
0
        public async Task Usage()
        {
            var outputFile = Path.Combine(BaseDirectory, "Usage.pdf");
            var fileInfo   = new FileInfo(outputFile);

            if (fileInfo.Exists)
            {
                fileInfo.Delete();
            }

            #region PdfAsync

            var browserFetcher = new BrowserFetcher();
            await browserFetcher.DownloadAsync();

            await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });

            await using var page = await browser.NewPageAsync();

            await page.GoToAsync("http://www.google.com");

            await page.PdfAsync(outputFile);

            #endregion

            Assert.True(File.Exists(outputFile));
        }
Esempio n. 14
0
        public async Task <int> ScrapeAndAddProducts()
        {
            int result = 0;

            var browserFetcher = new BrowserFetcher();
            await browserFetcher.DownloadAsync();

            await using var browser = await Puppeteer.LaunchAsync(
                            new LaunchOptions { Headless = false, DefaultViewport = new ViewPortOptions { Width = 1920, Height = 1024 } });

            foreach (var categoryUrl in _categoryUrlsToScrape)
            {
                await using var page = await browser.NewPageAsync();

                await page.GoToAsync(categoryUrl);
                await ScrollUntilEnd(page);

                var products = await ExtractProducts(page);
                await AddProductsIfMissing(products);

                result += products.Count;
            }

            return(result);
        }
        static async Task Browser(bool headless)
        {
            Console.WriteLine("Loading chromium");
            var fetcher = new BrowserFetcher();
            await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            using var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                UserDataDir     = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Puppeteer"),
                Headless        = headless,
                DefaultViewport = new ViewPortOptions { IsMobile = false, HasTouch = false, IsLandscape = true, Width = 1600, Height = 800 },
            });

            Console.WriteLine("Loading codesignal.com");
            var pages = await browser.PagesAsync();

            var page = pages.Length > 0 ? pages[0] : await browser.NewPageAsync();

            var areas = (await Scraping.ScanAreas(page));
            var tasks = (await Scraping.ScanTasks(page, areas));

            Console.WriteLine($"Located {tasks.Count} tasks where {tasks.Count(t => t.Solved)} is solved");
            Console.WriteLine("Please note that only solved tasks and first new task and unlocked tasks are found!");

            tasks = Source.FilterTasks(tasks).ToList();
            Console.WriteLine($"Retrieving {tasks.Count} task to update source and tests.");

            int failed = 0;

            //            var tasks = new TaskInfo[] { new TaskInfo("https://app.codesignal.com/arcade/code-arcade", "The Core", "Cliffs Of Pain", "https://app.codesignal.com/arcade/code-arcade/cliffs-of-pain/iGBDQE3KjqbYyF8DH", "timeASCIIRepresentation", false) };
            foreach (var task in tasks)
            {
                await Scraping.RetrieveTask(page, task);

                if (task.Failed)
                {
                    failed++;
                    continue;
                }
                Source.WriteTask(task);
                task.Description = null;
                task.Source      = null;
                task.Tests       = null;
            }

            Console.WriteLine("Finished, press space to end the program.");
            if (failed != 0)
            {
                Console.WriteLine();
                Console.WriteLine($"However, failed to import {failed} tasks.");
                Console.WriteLine($"Please, rerun to try again.");
            }

            Console.ReadKey();
            await page.CloseAsync();

            await browser.CloseAsync();
        }
Esempio n. 16
0
        public static async Task DownloadRevision(RevisionInfo revision)
        {
            if (Directory.Exists(revision.FolderPath) && !IsValidRevision(revision))
            {
                Directory.Delete(revision.FolderPath, true);
            }

            await BrowserFetcher.DownloadAsync(revision.Revision);
        }
        public static IServiceCollection AddPuppeteerSharpPdfConverter(this IServiceCollection services)
        {
            var browserFetcher = new BrowserFetcher();

            browserFetcher.DownloadAsync().GetAwaiter().GetResult();

            services.AddSingleton <IPdfConverter, PuppeteerSharpConverter>();

            return(services);
        }
Esempio n. 18
0
        private static async Task DownloadBrowserAsync()
        {
            var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions()
            {
                Host = "https://npm.taobao.org/mirrors",
            });

            browserFetcher.DownloadProgressChanged += new MyHandler().DownloadProgressChangedHandler;
            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);
        }
Esempio n. 19
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var bfOptions = new BrowserFetcherOptions();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                bfOptions.Path = Path.GetTempPath();
            }
            var bf = new BrowserFetcher(bfOptions);
            var a  = bf.DownloadAsync(BrowserFetcher.DefaultChromiumRevision).Result;

            bf.DownloadAsync(BrowserFetcher.DefaultChromiumRevision).Wait();
            var info = new AppInfo
            {
                BrowserExecutablePath = bf.GetExecutablePath(BrowserFetcher.DefaultChromiumRevision)
            };

            builder.Services.AddSingleton(info);
        }
Esempio n. 20
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine("This example downloads the default version of Chromium to a custom location");

            var currentDirectory = Directory.GetCurrentDirectory();
            var downloadPath     = Path.Combine(currentDirectory, "..", "..", "CustomChromium");

            Console.WriteLine($"Attemping to set up puppeteer to use Chromium found under directory {downloadPath} ");

            if (!Directory.Exists(downloadPath))
            {
                Console.WriteLine("Custom directory not found. Creating directory");
                Directory.CreateDirectory(downloadPath);
            }

            Console.WriteLine("Downloading Chromium");

            var browserFetcherOptions = new BrowserFetcherOptions {
                Path = downloadPath
            };
            var browserFetcher = new BrowserFetcher(browserFetcherOptions);
            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            var executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);

            if (string.IsNullOrEmpty(executablePath))
            {
                Console.WriteLine("Custom Chromium location is empty. Unable to start Chromium. Exiting.\n Press any key to continue");
                Console.ReadLine();
                return;
            }

            Console.WriteLine($"Attemping to start Chromium using executable path: {executablePath}");

            var options = new LaunchOptions {
                Headless = true, ExecutablePath = executablePath
            };

            using (var browser = await Puppeteer.LaunchAsync(options))
                using (var page = await browser.NewPageAsync())
                {
                    await page.GoToAsync("http://www.google.com");

                    var jsSelectAllAnchors = @"Array.from(document.querySelectorAll('a')).map(a => a.href);";
                    var urls = await page.EvaluateExpressionAsync <string[]>(jsSelectAllAnchors);

                    foreach (string url in urls)
                    {
                        Console.WriteLine($"Url: {url}");
                    }
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadLine();
                }
            return;
        }
Esempio n. 21
0
        static async Task <Browser> FetchAndLaunchBrowser()
        {
            var browserFetcher = new BrowserFetcher();
            var revision       = await browserFetcher.DownloadAsync();

            var launchOptions = new LaunchOptions {
                ExecutablePath = revision.ExecutablePath
            };

            return(await Puppeteer.LaunchAsync(launchOptions));
        }
        private async Task <string> DownloadChrome(string path)
        {
            BrowserFetcherOptions options = new BrowserFetcherOptions()
            {
                Path = path,
            };
            BrowserFetcher fetcher = new BrowserFetcher(options);
            RevisionInfo   info    = await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            return(info.ExecutablePath);
        }
Esempio n. 23
0
        private async Task SetupAsync()
        {
            using var browserFetcher = new BrowserFetcher(TestConstants.IsChrome ? Product.Chrome : Product.Firefox);
            var downloaderTask = browserFetcher.DownloadAsync();

            Server      = SimpleServer.Create(TestConstants.Port, TestUtils.FindParentDirectory("PuppeteerSharp.TestServer"));
            HttpsServer = SimpleServer.CreateHttps(TestConstants.HttpsPort, TestUtils.FindParentDirectory("PuppeteerSharp.TestServer"));

            var serverStart      = Server.StartAsync();
            var httpsServerStart = HttpsServer.StartAsync();

            await Task.WhenAll(downloaderTask, serverStart, httpsServerStart);
        }
Esempio n. 24
0
        public async Task DownloadChromium()
        {
            if (File.Exists(_settings.ChromiumPath))
            {
                return;
            }
            Console.WriteLine(MessageResources.DownloadChromiumStart);

            var fetcher = new BrowserFetcher();
            var result  = await fetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            _settings.ChromiumPath = result.ExecutablePath;
            JsonSettings.Save(_settings, SettingsPath);
        }
Esempio n. 25
0
        private static async System.Threading.Tasks.Task InstallBrowserAsync()
        {
            // Установка и обновление браузера chromium
            var browserFetcher = new BrowserFetcher();
            var localVersions  = browserFetcher.LocalRevisions();

            if (!localVersions.Any() || BrowserFetcher.DefaultRevision != localVersions.Max())
            {
                Log.Information("Downloading chromium...");
                browserFetcher.DownloadProgressChanged += (_, e) => { Console.Write("\r" + e.ProgressPercentage + "%"); };
                await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

                Console.WriteLine(); // Перевод курсора на следующую строку(чтобы небыло "100%Успешно")
            }
        }
Esempio n. 26
0
        private async Task <Browser> CreateWebBrowser(string ChromePath)
        {
            async Task <WebSocket> CreateWebSocketTask(Uri url, IConnectionOptions options, CancellationToken cancellationToken)
            {
                var result = new System.Net.WebSockets.Managed.ClientWebSocket();

                result.Options.KeepAliveInterval = TimeSpan.Zero;
                await result.ConnectAsync(url, cancellationToken).ConfigureAwait(false);

                return(result);
            }

            var downloadChrome = string.IsNullOrEmpty(ChromePath) || !File.Exists(ChromePath);

            if (downloadChrome)
            {
                Debug.Write("downloading Chrome...");
                var browserFetcherOptions = new BrowserFetcherOptions
                {
                    Path     = $"{AppDomain.CurrentDomain.BaseDirectory}",
                    Platform = Platform.Win64,
                    Product  = Product.Chrome
                };
                var browserFetcher = new BrowserFetcher(browserFetcherOptions);
                var revisionInfo   = await browserFetcher.DownloadAsync();

                ChromePath = revisionInfo.ExecutablePath;  // set the created chrome path
                Debug.WriteLine("done!");
            }

            var launchOptions = new LaunchOptions
            {
                Headless          = false,
                Timeout           = (10 * 1000), // 10 sec
                ExecutablePath    = ChromePath,  /// $"{AppDomain.CurrentDomain.BaseDirectory}Win64-884014\\chrome-win\\chrome.exe",
                DefaultViewport   = null,        // max resolution
                IgnoreHTTPSErrors = true,
                Args = new[] { "--no-sandbox", "--disable-gpu" }  // "--window-size=800,1080"
            };

            if (Environment.OSVersion.Version.Major < 10)
            {
                launchOptions.WebSocketFactory = CreateWebSocketTask;  // support for windows-7
            }
            var browser = await Puppeteer.LaunchAsync(launchOptions);

            return(browser);
        }
Esempio n. 27
0
        /// <summary>
        /// Downloads the browser.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <exception cref="TimeoutException">Timeout waiting for exclusive access.</exception>
        internal static void DownloadBrowser(ILogger logger)
        {
            string mutexId = $@"Global\{Directory.GetCurrentDirectory().Replace('\\', '_')}";

            var allowEveryoneRule =
                new MutexAccessRule(
                    new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                    MutexRights.FullControl,
                    AccessControlType.Allow);
            var securitySettings = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);

            using (var mutex = new Mutex(false, mutexId, out bool createdNew, securitySettings))
            {
                var hasHandle = mutex.WaitOne(Timeout.Infinite, false);
                if (hasHandle == false)
                {
                    throw new TimeoutException("Timeout waiting for exclusive access");
                }

                try
                {
                    BrowserFetcher browserFetcher = new BrowserFetcher();
                    if (browserFetcher.LocalRevisions().Any(x => x == BrowserFetcher.DefaultChromiumRevision))
                    {
                        // local revision already exists
                        return;
                    }

                    logger.LogDebug("Downloading browser...");
                    Task <RevisionInfo> task = browserFetcher.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);
                    task.Wait();

                    RevisionInfo revisionInfo = task.Result;
                    if (!revisionInfo.Downloaded)
                    {
                        throw new Exception($"Browser could not be downlaoded from URL \"{revisionInfo.Url}\".");
                    }

                    logger.LogDebug($"Browser downloaded to \"{revisionInfo.FolderPath}\".");
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }
        }
Esempio n. 28
0
        private async Task InitBrowser()
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var downloadPath     = Path.Combine(currentDirectory, "ChromeRuntime");

            if (!Directory.Exists(downloadPath))
            {
                Directory.CreateDirectory(downloadPath);
            }

            var browserFetcherOptions = new BrowserFetcherOptions {
                Path = downloadPath
            };
            var browserFetcher = new BrowserFetcher(browserFetcherOptions);
            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            var executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);

            if (string.IsNullOrEmpty(executablePath))
            {
                throw new Exception("Failed to initialize browser.");
            }

            List <string> args = new List <string> {
                "--no-sandbox",
                "--disable-setuid-sandbox",
                "--disable-infobars",
                "--window-position=0,0",
                "--ignore-certifcate-errors",
                "--ignore-certifcate-errors-spki-list",
                "--user-agent=\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\""
            };

            if (!m_Proxy.Equals("NONE"))
            {
                args.Add(string.Format("--proxy-server={0}", m_Proxy));
            }

            var options = new LaunchOptions {
                Headless          = true,
                IgnoreHTTPSErrors = true,
                ExecutablePath    = executablePath,
                Args = args.ToArray()
            };

            m_Browser = await Puppeteer.LaunchAsync(options);
        }
Esempio n. 29
0
        static async Task Main(string[] args)
        {
            var example = "basicWithJs";

            Console.WriteLine($"run example '{example}'");

            string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..", "..", "..", "..", "js-dependency", "examples", example, "index.html");

            var fether = new BrowserFetcher();

            var pb = new ProgressBar(100);

            void downloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
            {
                pb.Refresh(e.ProgressPercentage, $"downloading Puppeteer {BrowserFetcher.DefaultChromiumRevision}");
            }

            fether.DownloadProgressChanged += downloadProgressChanged;

            await fether.DownloadAsync();

            pb.Refresh(100, "finished");

            Console.WriteLine($"convert html to pdf");
            var puppeteer = new PuppeteerReport();
            await puppeteer.PDF(filePath,
                                "Result.pdf", new PdfOptions
            {
                Format            = PuppeteerSharp.Media.PaperFormat.A4,
                PreferCSSPageSize = true,
                MarginOptions     = new PuppeteerSharp.Media.MarginOptions
                {
                    Top    = "10mm",
                    Left   = "10mm",
                    Right  = "10mm",
                    Bottom = "10mm"
                }
            });

            Console.WriteLine("finished");

            string resultPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Report.pdf");

            Console.WriteLine(resultPath);
            Console.ReadLine();
        }
        public static async Task <Page> OpenChromiumPage()
        {
            var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions
            {
                Path = "D:\\Chromium" //You can replace with custom path.
            });

            var revision = await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless       = true,
                Timeout        = 0,
                ExecutablePath = revision.ExecutablePath
            });

            return(await browser.NewPageAsync());
        }