} // End Function ConnectToChrome

        public static async System.Threading.Tasks.Task ConvertDataAsync(ConversionData conversionData)
        {
#if false
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
#endif

            MasterDevs.ChromeDevTools.IChromeSessionFactory chromeSessionFactory = new MasterDevs.ChromeDevTools.ChromeSessionFactory();

            using (ConnectionInfo connectionInfo = await ConnectToChrome(conversionData.ChromePath, conversionData.RemoteDebuggingUri))
            {
                MasterDevs.ChromeDevTools.IChromeSession chromeSession = chromeSessionFactory.Create(connectionInfo.SessionInfo.WebSocketDebuggerUrl);

                // STEP 3 - Send a command
                //
                // Here we are sending a commands to tell chrome to set the viewport size
                // and navigate to the specified URL
                await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                {
                    Width  = conversionData.ViewPortWidth,
                    Height = conversionData.ViewPortHeight,
                    Scale  = 1
                });

                MasterDevs.ChromeDevTools.CommandResponse <NavigateCommandResponse> navigateResponse =
                    await chromeSession.SendAsync(new NavigateCommand
                {
                    // Url = "http://www.google.com"
                    Url = "about:blank"
                });

                System.Console.WriteLine("NavigateResponse: " + navigateResponse.Id);

                MasterDevs.ChromeDevTools.CommandResponse <SetDocumentContentCommandResponse> setContentResponse =
                    await chromeSession.SendAsync(new SetDocumentContentCommand()
                {
                    FrameId = navigateResponse.Result.FrameId,
                    Html    = conversionData.Html
                }
                                                  );



                // private static double cm2inch(double centimeters) { return centimeters * 0.0393701; }
                UnitConversion_t cm2inch = delegate(double centimeters) { return(centimeters * 0.393701); };
                // private static double mm2inch(double milimeters) { return milimeters * 0.0393701; }
                UnitConversion_t mm2inch = delegate(double milimeters) { return(milimeters * 0.0393701); };


                PrintToPDFCommand printCommand2 = new PrintToPDFCommand()
                {
                    Scale           = 1,
                    MarginTop       = 0,
                    MarginLeft      = 0,
                    MarginRight     = 0,
                    MarginBottom    = 0,
                    PrintBackground = true,
                    Landscape       = false,
                    // PaperWidth = cm2inch(21),
                    // PaperHeight = cm2inch(29.7),

                    // PaperWidth = cm2inch(conversionData.PageWidth),
                    // PaperHeight = cm2inch(conversionData.PageHeight)

                    PaperWidth  = mm2inch(conversionData.PageWidth),
                    PaperHeight = mm2inch(conversionData.PageHeight)
                };

                // await System.Threading.Tasks.Task2.Delay(300);


                if (conversionData.ChromiumActions.HasFlag(ChromiumActions_t.GetVersion))
                {
                    try
                    {
                        System.Diagnostics.Debug.WriteLine("Getting browser-version");

                        MasterDevs.ChromeDevTools.CommandResponse <GetVersionCommandResponse> version =
                            await chromeSession.SendAsync(new GetVersionCommand());

                        System.Diagnostics.Debug.WriteLine("Got browser-version");

                        conversionData.Version = version.Result;
                    }
                    catch (System.Exception ex)
                    {
                        conversionData.Exception = ex;
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                } // End if (conversionData.ChromiumActions.HasFlag(ChromiumActions_t.GetVersion))



                if (conversionData.ChromiumActions.HasFlag(ChromiumActions_t.ConvertToImage))
                {
                    try
                    {
                        System.Diagnostics.Debug.WriteLine("Taking screenshot");

                        MasterDevs.ChromeDevTools.CommandResponse <CaptureScreenshotCommandResponse> screenshot =
                            await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" });

                        System.Diagnostics.Debug.WriteLine("Screenshot taken.");

                        conversionData.PngData = System.Convert.FromBase64String(screenshot.Result.Data);
                    }
                    catch (System.Exception ex)
                    {
                        conversionData.Exception = ex;
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                } // End if (conversionData.ChromiumActions.HasFlag(ChromiumActions_t.ConvertToImage))


                if (conversionData.ChromiumActions.HasFlag(ChromiumActions_t.ConvertToPdf))
                {
                    try
                    {
                        System.Diagnostics.Debug.WriteLine("Printing PDF");

                        MasterDevs.ChromeDevTools.CommandResponse <PrintToPDFCommandResponse> pdf =
                            await chromeSession.SendAsync(printCommand2);

                        System.Diagnostics.Debug.WriteLine("PDF printed.");

                        conversionData.PdfData = System.Convert.FromBase64String(pdf.Result.Data);
                    }
                    catch (System.Exception ex)
                    {
                        conversionData.Exception = ex;
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                } // End if (conversionData.ChromiumActions.HasFlag(ChromiumActions_t.ConvertToPdf))


                System.Console.WriteLine("Closing page");
                await ClosePage(chromeSession, navigateResponse.Result.FrameId, true);

                System.Console.WriteLine("Page closed");
            } // End Using connectionInfo
        }     // End Sub ConvertDataAsync
예제 #2
0
        } // End Sub KillHeadless

        private static void Main(string[] args)
        {
            KillHeadless();

            Task.Run(async() =>
            {
                // synchronization
                System.Threading.ManualResetEventSlim screenshotDone = new System.Threading.ManualResetEventSlim();

                // STEP 1 - Run Chrome
                IChromeProcessFactory chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
                using (IChromeProcess chromeProcess = chromeProcessFactory.Create(9222, true))
                {
                    // STEP 2 - Create a debugging session
                    //ChromeSessionInfo sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault();
                    ChromeSessionInfo[] sessionInfos = await chromeProcess.GetSessionInfo();
                    ChromeSessionInfo sessionInfo    = (sessionInfos != null && sessionInfos.Length > 0) ?
                                                       sessionInfos[sessionInfos.Length - 1]
                        : new ChromeSessionInfo();

                    IChromeSessionFactory chromeSessionFactory = new ChromeSessionFactory();
                    IChromeSession chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);

                    // STEP 3 - Send a command
                    //
                    // Here we are sending a commands to tell chrome to set the viewport size
                    // and navigate to the specified URL
                    await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                    {
                        Width  = ViewPortWidth,
                        Height = ViewPortHeight,
                        Scale  = 1
                    });

                    var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                    {
                        Url = "http://www.google.com"
                    });
                    System.Console.WriteLine("NavigateResponse: " + navigateResponse.Id);

                    // STEP 4 - Register for events (in this case, "Page" domain events)
                    // send an command to tell chrome to send us all Page events
                    // but we only subscribe to certain events in this session
                    ICommandResponse pageEnableResult = await chromeSession.SendAsync <Protocol.Chrome.Page.EnableCommand>();
                    System.Console.WriteLine("PageEnable: " + pageEnableResult.Id);

                    chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired =>
                    {
                        // we cannot block in event handler, hence the task
                        Task.Run(async() =>
                        {
                            System.Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp);

                            long documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId;
                            long bodyNodeId     =
                                (await chromeSession.SendAsync(new QuerySelectorCommand
                            {
                                NodeId = documentNodeId,
                                Selector = "body"
                            })).Result.NodeId;

                            long height = (await chromeSession.SendAsync(new GetBoxModelCommand {
                                NodeId = bodyNodeId
                            })).Result.Model.Height;

                            await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                            {
                                Width  = ViewPortWidth,
                                Height = height,
                                Scale  = 1
                            });

                            System.Console.WriteLine("Taking screenshot");
                            var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                                Format = "png"
                            });

                            byte[] data = System.Convert.FromBase64String(screenshot.Result.Data);
                            System.IO.File.WriteAllBytes("output.png", data);
                            System.Console.WriteLine("Screenshot stored");


                            PrintToPDFCommand printCommand = new PrintToPDFCommand()
                            {
                                Scale           = 1,
                                MarginTop       = 0,
                                MarginLeft      = 0,
                                MarginRight     = 0,
                                MarginBottom    = 0,
                                PrintBackground = true,
                                Landscape       = false,
                                PaperWidth      = cm2inch(21),
                                PaperHeight     = cm2inch(29.7)
                            };


                            System.Console.WriteLine("Printing PDF");
                            CommandResponse <PrintToPDFCommandResponse> pdf = await chromeSession.SendAsync(printCommand);
                            System.Console.WriteLine("PDF printed.");

                            byte[] pdfData = System.Convert.FromBase64String(pdf.Result.Data);
                            System.IO.File.WriteAllBytes("output.pdf", pdfData);
                            System.Console.WriteLine("PDF stored");


                            // tell the main thread we are done
                            screenshotDone.Set();
                        });
                    });

                    // wait for screenshoting thread to (start and) finish
                    System.Console.WriteLine("Exiting ..");
                    screenshotDone.Wait();
                }
            }).Wait();
        }