public PuppeteerBrowser(ViewPortOptions viewPortOptions = null) { _vpOpts = viewPortOptions ?? new ViewPortOptions { Width = 1920, Height = 1080 }; }
public async Task <IActionResult> Post(PostHtmlToImageDTO dto) { _logger.LogInformation("C# HTTP trigger function processed a request."); if (dto is null) { throw new ArgumentNullException(nameof(dto)); } #if true == DEBUG await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); #endif ViewPortOptions defaultViewport = null; if (dto.Width.HasValue && dto.Height.HasValue) { defaultViewport = new ViewPortOptions { Width = dto.Width.Value, Height = dto.Height.Value } } ; using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Args = new[] { "--no-sandbox" }, DefaultViewport = defaultViewport })) using (var page = await browser.NewPageAsync()) { string text = null; if (!string.IsNullOrWhiteSpace(dto.HtmlBase64)) { var buff = Convert.FromBase64String(dto.HtmlBase64); text = UTF8Encoding.UTF8.GetString(buff); } else if (!string.IsNullOrWhiteSpace(dto.Html)) { text = dto.Html; } await page.SetContentAsync(text); var image = await page.ScreenshotDataAsync(); return(new FileContentResult(image, "image/png")); } } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "htmlToImage")] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var dto = JsonConvert.DeserializeObject <PostHtmlToImageDTO>(requestBody); //#if true == DEBUG // await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); //#endif ViewPortOptions defaultViewport = null; if (dto.Width.HasValue && dto.Height.HasValue) { defaultViewport = new ViewPortOptions { Width = dto.Width.Value, Height = dto.Height.Value } } ; using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true, Args = new[] { "--no-sandbox" }, DefaultViewport = defaultViewport })) using (var page = await browser.NewPageAsync()) { var buff = Convert.FromBase64String(dto.HtmlBase64); var text = UTF8Encoding.UTF8.GetString(buff); await page.SetContentAsync(text); var image = await page.ScreenshotDataAsync(); return(new FileContentResult(image, "image/png")); } } }
public static async Task PuppeteerSetViewport(BotData data, int width, int height, bool isMobile = false, bool isLandscape = false, float scaleFactor = 1f) { data.Logger.LogHeader(); var page = GetPage(data); var options = new ViewPortOptions { Width = width, Height = height, IsMobile = isMobile, IsLandscape = isLandscape, DeviceScaleFactor = scaleFactor }; await page.SetViewportAsync(options); data.Logger.Log($"Set the viewport size to {width}x{height}", LogColors.DarkSalmon); }
public async Task <byte[]> PrintPDF(string url, IEnumerable <CookieParam> cookies, ViewPortOptions viewport, PdfOptions options, RevisionInfo revision) { LaunchOptions launchOptions = new LaunchOptions() { ExecutablePath = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", Args = BrowserArgs, Headless = true, DefaultViewport = viewport, Timeout = 0 }; browser = await Puppeteer.LaunchAsync(launchOptions); try { var page = await browser.NewPageAsync(); try { WaitUntilNavigation[] waitUntilNavigations = { WaitUntilNavigation.Networkidle0 }; NavigationOptions navigationOptions = new NavigationOptions() { Timeout = 0, WaitUntil = waitUntilNavigations }; string originalUserAgent = await browser.GetUserAgentAsync(); await page.SetUserAgentAsync($"{originalUserAgent} {USER_AGENT_SUFFIX}"); if (cookies.Any()) { await page.SetCookieAsync(cookies.ToArray()); } await page.GoToAsync(url, navigationOptions); await InjectCustomStylesAsync(page, ref options); bool hasPageNumbers = await page.EvaluateFunctionAsync <bool>("(window.UltimatePDF? window.UltimatePDF.hasPageNumbers : function() { return false; })"); if (hasPageNumbers) { /* * When the layout has page numbers, we first retrieve a * first blank pdf to calculate the number of pages. * Then, knowing how many pages, we can layout the headers and footers, * and retrieve the final pdf. */ byte[] blankContents = await page.PdfDataAsync(options); using (var blankPdf = new PDFUtils(blankContents)) { await page.EvaluateFunctionAsync("window.UltimatePDF.layoutPages", blankPdf.Pages); return(await page.PdfDataAsync(options)); } } else { return(await page.PdfDataAsync(options)); } } finally { await Cleanup(page); } } finally { Cleanup(browser); } }
public async Task <byte[]> ScreenshotPNG(string url, IEnumerable <CookieParam> cookies, ViewPortOptions viewport, ScreenshotOptions options, RevisionInfo revision) { LaunchOptions launchOptions = new LaunchOptions() { ExecutablePath = revision.ExecutablePath, Args = BrowserArgs, Headless = true, DefaultViewport = viewport, Timeout = 0 }; browser = await Puppeteer.LaunchAsync(launchOptions); try { var page = await browser.NewPageAsync(); try { NavigationOptions navigationOptions = new NavigationOptions() { Timeout = 0 }; string originalUserAgent = await browser.GetUserAgentAsync(); await page.SetUserAgentAsync($"{originalUserAgent} {USER_AGENT_SUFFIX}"); if (cookies.Any()) { await page.SetCookieAsync(cookies.ToArray()); } await page.GoToAsync(url, navigationOptions); return(await page.ScreenshotDataAsync(options)); } finally { await Cleanup(page); } } finally { Cleanup(browser); } }
public async Task <Browser> ProfileStart(string chromiumPath, string profilesPath) { if (_browser != null) { return(_browser); } _fingerprint = GetFingerprint(profilesPath); var args = new List <string>(); if (!string.IsNullOrEmpty(UserAgent)) { args.Add($@"--user-agent=""{UserAgent}"""); } if (!string.IsNullOrEmpty(Language)) { args.Add($"--lang={Language}"); } if (RemoteDebuggingPort > 0) { args.Add($"--remote-debugging-port={RemoteDebuggingPort}"); } var proxyArg = ProxyRecord.GetProxyArg(); if (!string.IsNullOrEmpty(proxyArg)) { args.Add(proxyArg); } args.Add("--disable-webgl"); args.Add("--disable-3d-apis"); #region proxy info /* * --proxy-server=host:port * Specify the HTTP/SOCKS4/SOCKS5 proxy server to use for requests. This overrides any environment variables or settings picked via the options dialog. An individual * proxy server is specified using the format: * * [<proxy-scheme>://]<proxy-host>[:<proxy-port>] * * Where <proxy-scheme> is the protocol of the proxy server, and is one of: * * "http", "socks", "socks4", "socks5". * * If the <proxy-scheme> is omitted, it defaults to "http". Also note that "socks" is equivalent to "socks5". * * Examples: * * --proxy-server="foopy:99" * Use the HTTP proxy "foopy:99" to load all URLs. * * --proxy-server="socks://foobar:1080" * Use the SOCKS v5 proxy "foobar:1080" to load all URLs. * * --proxy-server="sock4://foobar:1080" * Use the SOCKS v4 proxy "foobar:1080" to load all URLs. * * --proxy-server="socks5://foobar:66" * Use the SOCKS v5 proxy "foobar:66" to load all URLs. * * It is also possible to specify a separate proxy server for different URL types, by prefixing the proxy server specifier with a URL specifier: * * Example: * * --proxy-server="https=proxy1:80;http=socks4://baz:1080" * Load https://* URLs using the HTTP proxy "proxy1:80". And load http://* * URLs using the SOCKS v4 proxy "baz:1080". */ #endregion var viewPortOptions = new ViewPortOptions { IsLandscape = true }; if (_fingerprint != null) { viewPortOptions = new ViewPortOptions(); viewPortOptions.Height = _fingerprint.height; viewPortOptions.Width = _fingerprint.width; viewPortOptions.DeviceScaleFactor = _fingerprint.attr.windowdevicePixelRatio; args.Add($"--window-size={_fingerprint.width},{_fingerprint.height}"); } var lanchOptions = new LaunchOptions { Headless = false, ExecutablePath = chromiumPath, DefaultViewport = viewPortOptions, IgnoreHTTPSErrors = true, SlowMo = 10, UserDataDir = Path.Combine(profilesPath, Folder), Args = args.ToArray() }; _browser = await Puppeteer.LaunchAsync(lanchOptions); _browser.TargetCreated += Browser_TargetCreated; _browser.TargetChanged += Browser_TargetChanged; _webSocketEndpoint = _browser.WebSocketEndpoint; //await Puppeteer.ConnectAsync(new ConnectOptions()); _browser.Disconnected += Browser_Disconnected; _browser.Closed += Browser_Closed; var page = (await _browser.PagesAsync())[0]; //await page.SetRequestInterceptionAsync(true); //page.Console += Page_Console; //await page.SetViewportAsync(); //await page.SetRequestInterceptionAsync(true); //page.Request += Page_Request; //var headers = new Dictionary<string, string>(); //headers["RtttU"] = " you site"; //headers["Accept"] = "text/html"; //await page.SetExtraHttpHeadersAsync(headers); if (!string.IsNullOrEmpty(proxyArg) && !string.IsNullOrEmpty(ProxyRecord.Username) && !string.IsNullOrEmpty(ProxyRecord.Password)) { await page.AuthenticateAsync(new Credentials { Username = ProxyRecord.Username, Password = ProxyRecord.Password }); } if (!string.IsNullOrEmpty(Timezone)) { await page.EmulateTimezoneAsync(Timezone); } RunScriptOnPage(page); if (!string.IsNullOrEmpty(StartUrl)) { await page.GoToAsync(StartUrl, _navigationOptions); } //var session = await page.Target.CreateCDPSessionAsync(); //await session.SendAsync("Emulation.setPageScaleFactor", new { pageScaleFactor= 4 }); return(_browser); }
public void MssPrintPDF(string ssURL, int ssBrowserRevision, bool ssReuseSession, out byte[] ssPDF) { using (var puppeteer = new BrowserUtils()) { RevisionInfo revision = BrowserUtils.RevisionInfo(ssBrowserRevision); ViewPortOptions viewport = new ViewPortOptions() { Width = 1366, Height = 768 }; PdfOptions options = new PdfOptions() { PrintBackground = true, PreferCSSPageSize = true }; bool ssUseCustomPaper = false; decimal ssWidth = 0; decimal ssHeight = 0; bool ssUseCustomMargins = false; decimal ssMarginTop = 0; decimal ssMarginRight = 0; decimal ssMarginBottom = 0; decimal ssMarginLeft = 0; if (ssUseCustomPaper && ssWidth > 0 && ssHeight > 0) { options.Width = $"{ssWidth}cm"; options.Height = $"{ssHeight}cm"; options.PreferCSSPageSize = false; } if (ssUseCustomMargins && ssMarginTop >= 0 && ssMarginRight >= 0 && ssMarginBottom >= 0 && ssMarginLeft >= 0) { options.MarginOptions.Top = $"{ssMarginTop}cm"; options.MarginOptions.Right = $"{ssMarginRight}cm"; options.MarginOptions.Bottom = $"{ssMarginBottom}cm"; options.MarginOptions.Left = $"{ssMarginLeft}cm"; } List <CookieParam> cookies = new List <CookieParam>(); if (ssReuseSession) { var sessionUtils = new SessionUtils(); foreach (var sessionReactiveCookie in sessionUtils.SessionCookies) { cookies.AddRange(sessionReactiveCookie.Select(cookie => new CookieParam() { Name = cookie.Name, Value = cookie.Value, Path = cookie.Path, Domain = new Uri(ssURL).Host, HttpOnly = cookie.HttpOnly })); } } //GenericExtendedActions.LogMessage(AppInfo.GetAppInfo().OsContext, "Log successful", "PrintPDF"); ssPDF = RunAsync(() => puppeteer.PrintPDF(ssURL, cookies, viewport, options, revision)); } }