コード例 #1
0
ファイル: OrderItem.cs プロジェクト: aurigma/PhotoKiosk
        public void SetCrop(PaperFormat format)
        {
            Rect crop = new Rect(_photoItem.ImageSize);

            if (!format.IsFree && (ExecutionEngine.Context[Constants.OrderContextName] as Order).CropMode == Constants.CropToFillModeName)
            {
                double ratio = (double)format.Width / (double)format.Height;
                if (_photoItem.ImageSize.Height > _photoItem.ImageSize.Width)
                {
                    ratio = 1 / ratio;
                }

                crop.Height = _photoItem.ImageSize.Height;
                crop.Width  = _photoItem.ImageSize.Height * ratio;
                if (crop.Width > _photoItem.ImageSize.Width)
                {
                    crop.Width  = _photoItem.ImageSize.Width;
                    crop.Height = _photoItem.ImageSize.Width / ratio;
                }

                crop.X = (_photoItem.ImageSize.Width - crop.Width) / 2;
                crop.Y = (_photoItem.ImageSize.Height - crop.Height) / 2;
            }

            _photoCrops[format] = crop;
        }
コード例 #2
0
        internal async Task <string> GetPdfAsync(
            decimal scale,
            bool displayHeaderFooter,
            string headerTemplate,
            string footerTemplate,
            bool printBackground,
            bool landscape,
            string pageRanges,
            PaperFormat format,
            string width,
            string height,
            Margin margin,
            bool preferCSSPageSize)
        {
            var args = new Dictionary <string, object>
            {
                ["scale"] = scale,
                ["displayHeaderFooter"] = displayHeaderFooter,
                ["printBackground"]     = printBackground,
                ["landscape"]           = landscape,
                ["preferCSSPageSize"]   = preferCSSPageSize,
            };

            if (pageRanges != null)
            {
                args["pageRanges"] = pageRanges;
            }

            if (headerTemplate != null)
            {
                args["headerTemplate"] = headerTemplate;
            }

            if (footerTemplate != null)
            {
                args["footerTemplate"] = footerTemplate;
            }

            if (margin != null)
            {
                args["margin"] = margin;
            }

            if (!string.IsNullOrEmpty(width))
            {
                args["width"] = width;
            }

            if (format != null)
            {
                args["format"] = format;
            }

            if (!string.IsNullOrEmpty(height))
            {
                args["height"] = height;
            }

            return((await Connection.SendMessageToServer(Guid, "pdf", args).ConfigureAwait(false))?.GetProperty("pdf").ToString());
        }
コード例 #3
0
 public PaperSizeFilter(PaperFormat paperFormat)
 {
     if (paperFormat != null && ExecutionEngine.Instance.PaperFormats.Contains(paperFormat))
     {
         _paperFormat = paperFormat;
     }
 }
コード例 #4
0
 public CalculateTimeInput(long?iterations, PaperFormat paperFormat, long?amount, double?speed)
 {
     Iterations  = iterations;
     PaperFormat = paperFormat;
     Amount      = amount;
     Speed       = speed;
 }
コード例 #5
0
        private ViPaper(double widthMM, double heightMM, PaperFormat paperFormat)
        {
            this._PageWidthMM  = widthMM;
            this._PageHeightMM = heightMM;

            this._PaperFormat = paperFormat;
        }
コード例 #6
0
        private void _formatsView_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            PaperFormat format = e.Row.Tag as PaperFormat;

            PriceManager.RemovePaperFormat(format);

            ValidateCells(null);
        }
コード例 #7
0
        /// <summary>
        /// Initializes a new instance of the Bytescout.PDF.Page class.
        /// </summary>
        /// <param name="format">The page size.</param>
        /// <param name="orientation">The paper orientation.</param>
        public Page(PaperFormat format, PaperOrientation orientation)
        {
            _dictionary = new PDFDictionary();
            _dictionary.AddItem("Type", new PDFName("Page"));
            _dictionary.AddItem("MediaBox", createBox(PaperSizes.GetRect(format, orientation)));

            Watermarks = new WatermarkCollection();
        }
コード例 #8
0
        /// <summary>
        /// 创建指定尺寸的 Scale 参数信息。
        /// </summary>
        /// <param name="widthMM">纸张宽度(毫米)</param>
        /// <param name="heightMM">纸张高度(毫米)</param>
        /// <returns>指定尺寸的纸张信息。</returns>
        public static ViPaper Create(double widthMM, double heightMM, PaperFormat paperFormat, PageOrientation orientation)
        {
            ViPaper paper = new ViPaper(widthMM, heightMM, paperFormat);

            paper.Orientation = orientation;

            return(paper);
        }
コード例 #9
0
ファイル: OrderItem.cs プロジェクト: aurigma/PhotoKiosk
        public void SetCrop(PaperFormat format, Rect crop)
        {
            var rect = new Rect(_photoItem.ImageSize);

            if (!format.IsFree && !rect.Contains(crop))
            {
                crop.Intersect(rect);
            }

            _photoCrops[format] = crop;
        }
コード例 #10
0
ファイル: Order.cs プロジェクト: aurigma/PhotoKiosk
        public int GetItemCount(PaperFormat format)
        {
            int itemsCount = 0;

            foreach (OrderItem item in _items)
            {
                itemsCount += item.GetCount(format);
            }

            return(itemsCount);
        }
コード例 #11
0
        private void _contextMenuItem_Click(object sender, EventArgs args)
        {
            int rowIndex = _mouseLocation.RowIndex;

            if (rowIndex >= 0 && rowIndex < _formatsView.Rows.Count)
            {
                PaperFormat format = _formatsView.Rows[rowIndex].Tag as PaperFormat;
                if (format != null)
                {
                    CropManager.AddCropFormat(format.Name, format.Width, format.Height, true);
                }
            }
        }
コード例 #12
0
ファイル: BookPrinting.cs プロジェクト: cfrpg/Publish
 /// <summary>
 /// 属性赋值构造函数
 /// </summary>
 /// <param name="bindingtype">装订规格</param>
 /// <param name="size">开本大小</param>
 /// <param name="count">册数</param>
 /// <param name="papertype">正文用纸</param>
 /// <param name="iscolorful">是否彩印</param>
 public _BookPrinting(
     int words,
     Binding bindingtype, 
     BookSizeFormat size,
     BookNumer count,
     PaperFormat papertype,
     bool iscolorful
 )
 {
     WordCount = words;
     BookBinding = bindingtype;
     BookSize = size;
     BookCount = count;
     PaperUsing = papertype;
     IsColorful = iscolorful;
     buildRawData();
 }
コード例 #13
0
 /// <summary>
 /// 属性赋值构造函数
 /// </summary>
 /// <param name="bindingtype">装订规格</param>
 /// <param name="size">开本大小</param>
 /// <param name="count">册数</param>
 /// <param name="papertype">正文用纸</param>
 /// <param name="iscolorful">是否彩印</param>
 public _BookPrinting(
     int words,
     Binding bindingtype,
     BookSizeFormat size,
     BookNumer count,
     PaperFormat papertype,
     bool iscolorful
     )
 {
     WordCount   = words;
     BookBinding = bindingtype;
     BookSize    = size;
     BookCount   = count;
     PaperUsing  = papertype;
     IsColorful  = iscolorful;
     buildRawData();
 }
コード例 #14
0
        private void _formatsView_DragDrop(object sender, DragEventArgs e)
        {
            var newFormats = new PaperFormat[PriceManager.PaperFormats.Count];

            for (int i = 0; i < _formatsView.Rows.Count; i++)
            {
                PaperFormat type = _formatsView.Rows[i].Tag as PaperFormat;
                if (type != null)
                {
                    newFormats[i] = type;
                }
            }

            PriceManager.UpdatePaperFormats(newFormats);

            ValidateCells(null);
        }
コード例 #15
0
ファイル: ThumbnailItem.cs プロジェクト: aurigma/PhotoKiosk
        private bool LowQualityIndicatorNeeded()
        {
            PaperFormat curFormat = ExecutionEngine.Instance.SelectedPaperFormat;

            if (curFormat != null && !curFormat.IsFree && _photo.ImageSize.Width > 0 && _photo.ImageSize.Height > 0)
            {
                double curPixPerInch = Math.Max(_photo.ImageSize.Width / curFormat.Width, _photo.ImageSize.Height / curFormat.Height);
                if (ExecutionEngine.Config.PaperSizeUnits.Value == Constants.MmUnits)
                {
                    curPixPerInch *= 25.4;
                }

                return(curPixPerInch < curFormat.Dpi);
            }
            else
            {
                return(false);
            }
        }
コード例 #16
0
ファイル: OrderItem.cs プロジェクト: aurigma/PhotoKiosk
        public string GetCropString(PaperFormat format)
        {
            Rect rect = GetCrop(format);

            int angle = _photoItem.ExifAngle;

            if (angle > 0)
            {
                double tmp;
                switch (angle)
                {
                case 270:
                    tmp         = SourcePhotoItem.ImageSize.Height - rect.Height - rect.Y;
                    rect.Y      = rect.X;
                    rect.X      = tmp;
                    tmp         = rect.Width;
                    rect.Width  = rect.Height;
                    rect.Height = tmp;
                    break;

                case 180:
                    rect.X = SourcePhotoItem.ImageSize.Width - rect.Width - rect.X;
                    rect.Y = SourcePhotoItem.ImageSize.Height - rect.Height - rect.Y;
                    break;

                case 90:
                    tmp         = SourcePhotoItem.ImageSize.Width - rect.Width - rect.X;
                    rect.X      = rect.Y;
                    rect.Y      = tmp;
                    tmp         = rect.Width;
                    rect.Width  = rect.Height;
                    rect.Height = tmp;
                    break;

                default:
                    throw new NotSupportedException();
                }
            }

            return(string.Format("{0}, {1}, {2}, {3}", (int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height));
        }
コード例 #17
0
        private void _formatsView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (_isLoaded && e.RowIndex >= 0)
            {
                PaperFormat format  = _formatsView.Rows[e.RowIndex].Tag as PaperFormat;
                string      newName = _formatsView["NameColumn", e.RowIndex].Value != null ? _formatsView["NameColumn", e.RowIndex].Value.ToString() : string.Empty;

                float newWidth = 0.0f;
                if (_formatsView["WidthColumn", e.RowIndex].Value != null)
                {
                    float.TryParse(_formatsView["WidthColumn", e.RowIndex].Value.ToString(), out newWidth);
                }

                float newHeight = 0.0f;
                if (_formatsView["HeightColumn", e.RowIndex].Value != null)
                {
                    float.TryParse(_formatsView["HeightColumn", e.RowIndex].Value.ToString(), out newHeight);
                }

                int newDpi = 0;
                if (_formatsView["DpiColumn", e.RowIndex].Value != null)
                {
                    int.TryParse(_formatsView["DpiColumn", e.RowIndex].Value.ToString(), out newDpi);
                }

                if (format != null)
                {
                    format.Name   = newName;
                    format.Width  = newWidth;
                    format.Height = newHeight;
                    format.Dpi    = newDpi;
                }
                else
                {
                    format = PriceManager.AddPaperFormat(newName, newWidth, newHeight, newDpi);
                    _formatsView.Rows[e.RowIndex].Tag = format;
                }

                ValidateCells(null);
            }
        }
コード例 #18
0
        private void _contextMenu_DropDownOpened(object sender, CancelEventArgs args)
        {
            int rowIndex = _mouseLocation.RowIndex;

            if (rowIndex >= 0 && rowIndex < _formatsView.Rows.Count)
            {
                PaperFormat format = _formatsView.Rows[rowIndex].Tag as PaperFormat;
                if (format != null)
                {
                    _contextMenuItem.Enabled = !CropManager.ContainsCrop(format.Name, format.Width, format.Height) && CropManager.CropFormats.Count < Constants.MaxCropsCount;
                }
                else
                {
                    args.Cancel = true;
                }
            }
            else
            {
                args.Cancel = true;
            }
        }
コード例 #19
0
ファイル: OrderItem.cs プロジェクト: aurigma/PhotoKiosk
 public int GetCount(PaperFormat format)
 {
     return(_photoCounts[format]);
 }
コード例 #20
0
        /// <summary>
        /// Set the given <paramref name="paperFormat"/>
        /// </summary>
        /// <param name="paperFormat"><see cref="PaperFormat"/></param>
        private void SetPaperFormat(PaperFormat paperFormat)
        {
            switch (paperFormat)
            {
            case PaperFormat.Letter:
                PaperWidth  = 8.5;
                PaperHeight = 11;
                break;

            case PaperFormat.Legal:
                PaperWidth  = 8.5;
                PaperHeight = 14;
                break;

            case PaperFormat.Tabloid:
                PaperWidth  = 11;
                PaperHeight = 17;
                break;

            case PaperFormat.Ledger:
                PaperWidth  = 17;
                PaperHeight = 11;
                break;

            case PaperFormat.A0:
                PaperWidth  = 33.1;
                PaperHeight = 46.8;
                break;

            case PaperFormat.A1:
                PaperWidth  = 23.4;
                PaperHeight = 33.1;
                break;

            case PaperFormat.A2:
                PaperWidth  = 16.5;
                PaperHeight = 23.4;
                break;

            case PaperFormat.A3:
                PaperWidth  = 11.7;
                PaperHeight = 16.5;
                break;

            case PaperFormat.A4:
                PaperWidth  = 8.27;
                PaperHeight = 11.7;
                break;

            case PaperFormat.A5:
                PaperWidth  = 5.83;
                PaperHeight = 8.27;
                break;

            case PaperFormat.A6:
                PaperWidth  = 4.13;
                PaperHeight = 5.83;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(paperFormat), paperFormat, null);
            }
        }
コード例 #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="urls"></param>
        /// <param name="path"></param>
        /// <param name="changeCountry">选择切换的国家</param>
        /// <param name="randomCity">随机切换城市</param>
        /// <param name="addText">添加页眉/页脚内容</param>
        /// <returns></returns>
        private async Task BulidPdfAsync(Uri[] urls, string path, string changeCountry, bool randomCity, string addText, bool saveHis, PaperFormat paperFormat)
        {
            try
            {
                await new BrowserFetcher(new BrowserFetcherOptions()
                {
                    Host = "http://cdn.npm.taobao.org/dist"
                }).DownloadAsync(BrowserFetcher.DefaultRevision);

                var option = new LaunchOptions
                {
                    UserDataDir     = $"{System.IO.Directory.GetCurrentDirectory()}/UserData",
                    Headless        = true,
                    DefaultViewport = null,
                    Args            = new[] {
                        "--no-sandbox",
                        "--disable-setuid-sandbox",
                        "--lang=en-US,en",
                        "--start-maximized",
                        //    "--disable-dev-shm-usage",
                        //   "--disable-extensions",
                        //  "--disable-gpu",
                        // "--disable-infobars",
                        //"--disable-local-storage",
                        // "--no-zygote",
                        // "--disable-bundled-ppapi-flash"
                        //$"--user-agent={_userAgent}"
                    },
                    IgnoreHTTPSErrors = true,
                };
                using (var browser = await Puppeteer.LaunchAsync(option))
                {
                    BrowserContext browserContext = browser.DefaultContext;
                    //if (saveHis)
                    //{
                    //    browserContext = await browser.CreateIncognitoBrowserContextAsync();

                    //}

                    var page = await browserContext.NewPageAsync();

                    await page.SetUserAgentAsync(_userAgent);

                    await page.SetViewportAsync(new ViewPortOptions
                    {
                        Width  = Screen.PrimaryScreen.WorkingArea.Width,
                        Height = Screen.PrimaryScreen.WorkingArea.Height
                    });


                    if (!changeCountry.Contains("请选择") && _CountryModels.Any())
                    {
                        OnShowTooltipInfo("初始化首页内容,开始切换国家");
                        //var zips = Properties.Resources.zip.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        //var zip = zips.OrderBy(m => Guid.NewGuid()).First();

                        await page.GoToAsync("https://www.amazon.com/");

                        var pagetitle = await page.GetTitleAsync();

                        try
                        {
                            var docid = _CountryModels.Find(m => m.Text.Contains(changeCountry));
                            if (docid != null)
                            {
                                await page.EvaluateFunctionAsync(Properties.Resources.oChange2, docid.Id);
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("访问网址受限,自动切换地区失败,\r\n请等待亚马逊解封或切换新ip后再尝试\r\n" + ex.Message, pagetitle);
                            return;
                        }
                        await Task.Delay(8000);
                    }
                    else if (randomCity)//没有选择国家的情况,选择地区切换地区
                    {
                        OnShowTooltipInfo("初始化首页内容,开始切换地区");


                        var zips = Properties.Resources.zip.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        var zip  = zips.OrderBy(m => Guid.NewGuid()).First();
                        await page.GoToAsync("https://www.amazon.com/");

                        var pagetitle = await page.GetTitleAsync();

                        try
                        {
                            await InputMatchCaptch(page);

                            await page.EvaluateFunctionAsync(Properties.Resources.oChange, zip);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("访问网址受限,自动切换地区失败,\r\n请等待亚马逊解封或切换新ip后再尝试", pagetitle);
                            throw ex;
                        }
                        await Task.Delay(10000);
                    }


                    int index = 0;
                    int max   = urls.Length;

                    var prelist  = Properties.Resources.preload.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    var maxwidth = Screen.PrimaryScreen.WorkingArea.Width;
                    foreach (var item in urls)
                    {
                        index += 1;
                        var ht = $"<div style=\"top:0px;font-size:10px;margin-left:10px;width:{maxwidth}px;\" ><span style=\"margin-left: 20px;\">{item}</span><span style=\"margin-left: 25%;\"></span><span style=\"margin-left:25%;\">{addText}</span></div>";
                        var ft = $"<div style=\"top:0px;font-size:10px;margin-left: 10px;width:{maxwidth}px;\"><span style=\"margin-left: 20px;\">{item}</span><span style=\"margin-left: 25%;\"></span><span style=\"margin-left:25%;\">{addText}</span></div>";

                        try
                        {
                            OnShowTooltipInfo($"开始加载页面{item}");
                            // progressBar.PerformStep();


                            //搜索记录
                            if (saveHis)
                            {
                                var preurl = prelist.OrderBy(m => Guid.NewGuid()).Take(6).ToList();
                                for (int i = 0; i < preurl.Count; i++)
                                {
                                    await InputMatchCaptch(page);

                                    var url = preurl[i];
                                    OnShowTooltipInfo($"增加浏览记录 {(i + 1)}/{preurl.Count}");

                                    await page.GoToAsync(url);
                                }
                            }
                            OnShowTooltipInfo("打开目标页面 " + item.ToString());
                            //目标页面
                            await page.GoToAsync(item.ToString());

                            await page.EvaluateFunctionAsync <string>("()=>{try{document.querySelector('#productTitle').click(); document.querySelector('.nav-signin-tt.nav-flyout').remove();return 1;}catch(ex){return 0;}}");

                            if (saveHis)
                            {
                                OnShowTooltipInfo("展示浏览记录");

                                var result = await page.EvaluateFunctionAsync <string>("()=>{try{window.scrollBy(0,document.querySelector('.navFooterBackToTopText').getBoundingClientRect().top-600);return 1;}catch(ex){console.log(ex);return 0;}}");

                                await Task.Delay(3000);

                                result = await page.EvaluateFunctionAsync <string>(Properties.Resources.oRandom);

                                await Task.Delay(5000);
                            }
                            var file = Path.Combine(path, item.AbsolutePath.Replace("/dp/", "").Replace("/", "") + ".pdf");
                            OnShowTooltipInfo("开始生成PDF " + file);

                            if (option.Headless)
                            {
                                await page.PdfAsync(file, new PdfOptions()
                                {
                                    PrintBackground     = true,
                                    DisplayHeaderFooter = !string.IsNullOrEmpty(addText),
                                    HeaderTemplate      = ht,
                                    FooterTemplate      = ft,
                                    MarginOptions       = new PuppeteerSharp.Media.MarginOptions()
                                    {
                                        Top    = "40",
                                        Bottom = "40",
                                        Left   = "30",
                                        Right  = "30"
                                    },
                                    Format = paperFormat
                                });
                            }

                            OnSetProcessValue(index);
                        }
                        catch (Exception ex)
                        {
                            OnShowTooltipInfo(ex.Message + "操作失败 " + item);
                            continue;
                            // throw;
                        }
                    }

                    //if (saveHis)
                    //{
                    //    var ck = await page.GetCookiesAsync("https://www.amazon.com");
                    //    await page.DeleteCookieAsync(ck);
                    //}

                    OnShowTooltipInfo($"操作完成 {index}/{urls.Length}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
                //throw;
            }
        }
コード例 #22
0
ファイル: PdfPrinter.cs プロジェクト: icnocop/HtmlToPdf
        /// <summary>
        /// Prints as PDF asynchronously.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="options">The options.</param>
        /// <param name="variables">The variables.</param>
        /// <param name="createLinksForHeadings">if set to <c>true</c> creates links for headings.</param>
        /// <returns>
        /// A task with the PDF file path as a result.
        /// </returns>
        /// <exception cref="System.IO.FileNotFoundException">File not found: {fullPath}.</exception>
        internal async Task <string> PrintAsPdfAsync(
            string input,
            HtmlToPdfOptions options,
            Dictionary <string, string> variables,
            bool createLinksForHeadings = true)
        {
            string fullPath = Path.GetFullPath(input);

            if (!File.Exists(fullPath))
            {
                throw new FileNotFoundException($"File not found: {fullPath}", fullPath);
            }

            string tempPdfFilePath = TempPdfFile.Create();

            NavigationOptions navigationOptions = new NavigationOptions
            {
                WaitUntil = new[] { WaitUntilNavigation.Networkidle0 },
                Timeout   = 0,
            };

            AddTagOptions addTagOptions = null;

            if (!string.IsNullOrEmpty(options.StyleSheet))
            {
                if (File.Exists(options.StyleSheet))
                {
                    addTagOptions = new AddTagOptions
                    {
                        Type = "text/css",
                        Path = options.StyleSheet,
                    };
                }
                else
                {
                    this.logger.LogWarning($"File not found: {options.StyleSheet}");
                }
            }

            // the paper format takes priority over width and height
            // if a page width or height is set, unset the paper format
            PaperFormat paperFormat = options.PaperFormat;
            string      width       = options.Width;
            string      height      = options.Height;

            if ((!string.IsNullOrEmpty(width)) ||
                (!string.IsNullOrEmpty(height)))
            {
                paperFormat = null;
            }

            using (TempCopyHtmlFile tempHtmlFile = new TempCopyHtmlFile(fullPath))
            {
                this.PrependEmptyPages(tempHtmlFile.FilePath, options.PageOffset + options.PageNumberOffset);

                // TODO: do not create links for headings if not generating an outline
                if (createLinksForHeadings)
                {
                    this.CreateLinksForHeadings(tempHtmlFile.FilePath);
                }

                string pageRanges = string.Empty;
                if ((options.PageOffset + options.PageNumberOffset) > 0)
                {
                    int fromPage = options.PageOffset + options.PageNumberOffset + 1;
                    int toPage   = options.PageOffset + options.PageNumberOffset + options.NumberOfPages;

                    pageRanges = $"{fromPage}-";
                    if (options.NumberOfPages != 0)
                    {
                        pageRanges += $"{toPage}";
                    }

                    this.logger.LogDebug($"Printing pages {pageRanges} of page '{fullPath}'.");
                }

                // page variables
                Dictionary <string, string> pageVariables = new Dictionary <string, string>();
                if (variables != null)
                {
                    foreach (KeyValuePair <string, string> keyValuePair in variables)
                    {
                        pageVariables.Add(keyValuePair.Key, keyValuePair.Value);
                    }
                }

                pageVariables.Add("webpage", fullPath);

                string footerTemplate = string.Empty;
                bool   displayFooter  = options.FooterTemplateBuilder.DisplayTemplate;
                if (displayFooter)
                {
                    footerTemplate = options.FooterTemplateBuilder.Build(pageVariables);
                }

                string headerTemplate = string.Empty;
                bool   displayHeader  = options.HeaderTemplateBuilder.DisplayTemplate;
                if (displayHeader)
                {
                    headerTemplate = options.HeaderTemplateBuilder.Build(pageVariables);
                }

                PdfOptions pdfOptions = new PdfOptions
                {
                    DisplayHeaderFooter = displayHeader || displayFooter,
                    FooterTemplate      = footerTemplate,
                    Format            = paperFormat,
                    HeaderTemplate    = headerTemplate,
                    Height            = height,
                    Landscape         = options.Landscape,
                    MarginOptions     = options.MarginOptions,
                    PreferCSSPageSize = false,
                    PageRanges        = pageRanges,
                    PrintBackground   = options.PrintBackground,
                    Scale             = 1,
                    Width             = width,
                };

                PolicyResult policyResult = await Policy
                                            .Handle <TargetClosedException>()
                                            .Or <Exception>()
                                            .RetryAsync(2, onRetry: (ex, retryCount, context) =>
                {
                    // executed before each retry
                    // ex. PuppeteerSharp.TargetClosedException: Protocol error(IO.read): Target closed. (Page failed to process Inspector.targetCrashed. Exception of type 'PuppeteerSharp.TargetCrashedException' was thrown..    at PuppeteerSharp.Page.OnTargetCrashed()
                    //     at PuppeteerSharp.Page.<Client_MessageReceived>d__230.MoveNext())
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    //     at PuppeteerSharp.CDPSession.<SendAsync>d__30.MoveNext()
                    //     --- End of stack trace from previous location where exception was thrown ---
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    //     at PuppeteerSharp.CDPSession.<SendAsync>d__29`1.MoveNext()
                    //     --- End of stack trace from previous location where exception was thrown ---
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at PuppeteerSharp.Helpers.ProtocolStreamReader.<ReadProtocolStreamByteAsync>d__1.MoveNext()
                    //     --- End of stack trace from previous location where exception was thrown ---
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    //     at PuppeteerSharp.Page.<PdfInternalAsync>d__171.MoveNext()
                    //     --- End of stack trace from previous location where exception was thrown ---
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    //     at PuppeteerSharp.Page.<PdfAsync>d__166.MoveNext()
                    //      --- End of stack trace from previous location where exception was thrown ---
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    //     at HtmlToPdf.PdfPrinter.<PrintAsPdfAsync>d__3.MoveNext() in D:\a\HtmlToPdf\HtmlToPdf\src\HtmlToPdf\PdfPrinter.cs:line 167
                    //     --- End of inner exception stack trace ---
                    //     at HtmlToPdf.PdfPrinter.<PrintAsPdfAsync>d__3.MoveNext() in D:\a\HtmlToPdf\HtmlToPdf\src\HtmlToPdf\PdfPrinter.cs:line 171
                    //     --- End of stack trace from previous location where exception was thrown ---
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    //     at HtmlToPdf.HtmlToPdfProcessor.<>c__DisplayClass0_1.<<ProcessAsync>b__6>d.MoveNext() in D:\a\HtmlToPdf\HtmlToPdf\src\HtmlToPdf\HtmlToPdfProcessor.cs:line 183
                    //     --- End of stack trace from previous location where exception was thrown ---
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at HtmlToPdf.HtmlToPdfProcessor.<ProcessAsync>d__0.MoveNext() in D:\a\HtmlToPdf\HtmlToPdf\src\HtmlToPdf\HtmlToPdfProcessor.cs:line 206
                    //     --- End of stack trace from previous location where exception was thrown ---
                    //     Verbose:[PdfCommand.PDF.wkhtmltopdf]got ... HtmlToPdf.Console.exe output 0Bytes
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at HtmlToPdf.HtmlToPdfProcessor.<ProcessAsync>d__0.MoveNext() in D:\a\HtmlToPdf\HtmlToPdf\src\HtmlToPdf\HtmlToPdfProcessor.cs:line 294
                    //     --- End of stack trace from previous location where exception was thrown ---
                    //     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
                    //     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                    //     at HtmlToPdf.Console.Program.<RunAsync>d__7.MoveNext() in D:\a\HtmlToPdf\HtmlToPdf\src\HtmlToPdf.Console\Program.cs:line 216
                    //     Error:[PdfCommand.PDF]Error happen when converting articles/toc.json to Pdf. Details: iTextSharp.text.exceptions.InvalidPdfException: PDF header signature not found.
                    //     at iTextSharp.text.pdf.PdfReader..ctor(ReaderProperties properties, IRandomAccessSource byteSource)
                    //     at Microsoft.DocAsCode.HtmlToPdf.HtmlToPdfConverter.SaveCore(Stream stream)
                    //     at Microsoft.DocAsCode.HtmlToPdf.HtmlToPdfConverter.Save(String outputFileName)
                    //     at Microsoft.DocAsCode.HtmlToPdf.ConvertWrapper.<>c__DisplayClass7_0.<ConvertCore>b__1(ManifestItem tocFile)
                    this.logger.LogWarning(ex.ToString());
                    Thread.Sleep(1000);
                })
                                            .ExecuteAndCaptureAsync(async() =>
                {
                    using (Page page = await this.browser.NewPageAsync())
                    {
                        // disable navigation timeout
                        // otherwise, the following exception occurs:
                        // PuppeteerSharp.NavigationException: Timeout of 30000 ms exceeded ---> System.TimeoutException: Timeout of 30000 ms exceeded
                        page.DefaultNavigationTimeout = 0;
                        page.DefaultTimeout           = 0;

                        await page.GoToAsync(tempHtmlFile.FilePath, navigationOptions);

                        if (addTagOptions != null)
                        {
                            await page.AddStyleTagAsync(addTagOptions);
                        }

                        await page.WaitForTimeoutAsync(options.JavascriptDelayInMilliseconds);

                        try
                        {
                            await page.PdfAsync(tempPdfFilePath, pdfOptions);
                        }
                        finally
                        {
                            await page.CloseAsync();
                        }
                    }
                });

                if (policyResult.Outcome == OutcomeType.Failure)
                {
                    if (policyResult.FinalException is TargetClosedException)
                    {
                        throw policyResult.FinalException;
                    }
                    else
                    {
                        throw new PrintToPdfException(fullPath, policyResult.FinalException);
                    }
                }
            }

            return(tempPdfFilePath);
        }
コード例 #23
0
        public static RectangleF GetRect(PaperFormat format, PaperOrientation orientation)
        {
            RectangleF rect = new RectangleF();

            switch (format)
            {
            case PaperFormat.A0:
                rect.Size = new SizeF(2383.94f, 3370.39f);
                break;

            case PaperFormat.A1:
                rect.Size = new SizeF(1683.78f, 2383.94f);
                break;

            case PaperFormat.A2:
                rect.Size = new SizeF(1190.55f, 1683.78f);
                break;

            case PaperFormat.A3:
                rect.Size = new SizeF(841.89f, 1190.55f);
                break;

            case PaperFormat.A4:
                rect.Size = new SizeF(595.28f, 841.89f);
                break;

            case PaperFormat.A5:
                rect.Size = new SizeF(419.53f, 595.28f);
                break;

            case PaperFormat.A6:
                rect.Size = new SizeF(297.64f, 419.53f);
                break;

            case PaperFormat.B4:
                rect.Size = new SizeF(708.66f, 1000.63f);
                break;

            case PaperFormat.B4Envelope:
                rect.Size = new SizeF(708.66f, 1000.63f);
                break;

            case PaperFormat.B5:
                rect.Size = new SizeF(498.9f, 708.66f);
                break;

            case PaperFormat.B5Envelope:
                rect.Size = new SizeF(498.9f, 708.66f);
                break;

            case PaperFormat.C6Envelope:
                rect.Size = new SizeF(323.15f, 459.21f);
                break;

            case PaperFormat.DLEnvelope:
                rect.Size = new SizeF(311.81f, 623.62f);
                break;

            case PaperFormat.Executive:
                rect.Size = new SizeF(522, 756);
                break;

            case PaperFormat.Folio:
                rect.Size = new SizeF(612, 936);
                break;

            case PaperFormat.Legal:
                rect.Size = new SizeF(612, 1008);
                break;

            case PaperFormat.Letter:
                rect.Size = new SizeF(612, 792);
                break;

            case PaperFormat.MonarchEnvelope:
                rect.Size = new SizeF(279, 540);
                break;

            case PaperFormat.Statement:
                rect.Size = new SizeF(396, 612);
                break;
            }

            if (orientation == PaperOrientation.Landscape)
            {
                rect.Size = new SizeF(rect.Height, rect.Width);
            }

            return(rect);
        }
コード例 #24
0
 /// <summary> </summary>
 public Page CreatePage2(PaperFormat paperFormat, PaperOrientation paperOrientation)
 {
     return(new Page(paperFormat, paperOrientation));
 }
コード例 #25
0
 /// <summary> </summary>
 public Page CreatePage(PaperFormat paperFormat)
 {
     return(new Page(paperFormat));
 }
コード例 #26
0
ファイル: OrderItem.cs プロジェクト: aurigma/PhotoKiosk
 public void SetCount(PaperFormat format, int count)
 {
     _photoCounts[format] = count;
 }
コード例 #27
0
 /// <summary>
 /// Makes this object and sets all the settings to it's default values
 /// </summary>
 /// <remarks>
 /// Default paper settings are set to <see cref="Enums.PaperFormat.A4"/>
 /// </remarks>
 /// <param name="paperFormat"></param>
 public PageSettings(PaperFormat paperFormat)
 {
     ResetToDefaultSettings();
     PaperFormat = paperFormat;
     SetPaperFormat(paperFormat);
 }
コード例 #28
0
 /// <summary>
 /// Initializes a new instance of the Bytescout.PDF.Page class.
 /// </summary>
 /// <param name="format">The page size.</param>
 public Page(PaperFormat format) : this(format, (PaperOrientation)PaperOrientation.Portrait)
 {
 }
コード例 #29
0
ファイル: OrderItem.cs プロジェクト: aurigma/PhotoKiosk
 public void ClearCrop(PaperFormat format)
 {
     _photoCrops[format] = new Rect();
 }
コード例 #30
0
        /// <summary>
        /// Set the given <paramref name="paperFormat"/>
        /// </summary>
        /// <param name="paperFormat"><see cref="PaperFormat"/></param>
        public void SetPaperFormat(PaperFormat paperFormat)
        {
            PaperFormat = paperFormat;

            switch (paperFormat)
            {
            case PaperFormat.Letter:
                PaperWidth  = 8.5;
                PaperHeight = 11;
                break;

            case PaperFormat.Legal:
                PaperWidth  = 8.5;
                PaperHeight = 14;
                break;

            case PaperFormat.Tabloid:
                PaperWidth  = 11;
                PaperHeight = 17;
                break;

            case PaperFormat.Ledger:
                PaperWidth  = 17;
                PaperHeight = 11;
                break;

            case PaperFormat.A0:
                PaperWidth  = 33.1;
                PaperHeight = 46.8;
                break;

            case PaperFormat.A1:
                PaperWidth  = 23.4;
                PaperHeight = 33.1;
                break;

            case PaperFormat.A2:
                PaperWidth  = 16.5;
                PaperHeight = 23.4;
                break;

            case PaperFormat.A3:
                PaperWidth  = 11.7;
                PaperHeight = 16.5;
                break;

            case PaperFormat.A4:
                PaperWidth  = 8.3;
                PaperHeight = 11.7;
                break;

            case PaperFormat.A5:
                PaperWidth  = 5.8;
                PaperHeight = 8.3;
                break;

            case PaperFormat.A6:
                PaperWidth  = 4.1;
                PaperHeight = 5.8;
                break;

            case PaperFormat.FitPageToContent:
                PreferCSSPageSize = true;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(paperFormat), paperFormat, null);
            }
        }
コード例 #31
0
ファイル: Order.cs プロジェクト: aurigma/PhotoKiosk
 public float GetCost(PaperFormat format)
 {
     return(ExecutionEngine.PriceManager.GetTotalPrice(format, _paperType, ExecutionEngine.Instance.Instant, GetItemCount(format)));
 }