protected HtmlToPdfDocument Document(params ObjectSettings[] objects)
        {
            var doc = new HtmlToPdfDocument();
            doc.Objects.AddRange(objects);

            return doc;
        }
Example #2
0
        public ActionResult PdfTest()
        {
            var doc = new HtmlToPdfDocument();
            doc.Objects.Add(new ObjectSettings { PageUrl = "www.google.com " });
       
            for (var i = 0; i < 5; i++)
            {
                var result = converter.Convert(doc);
                var path = Path.Combine(Path.GetTempPath(), String.Format("{0}.pdf", i));

                System.IO.File.WriteAllBytes(path, result);
            }

            return this.View();
        }
Example #3
0
        public void ConvertsAfterAppDomainRecycles()
        {
            // arrange
            var domain1 = this.GetAppDomain("testing_unload_1");
            byte[] result1 = null;
            var domain2 = this.GetAppDomain("testing_unload_2");
            byte[] result2 = null;
            CrossAppDomainDelegate callback = () =>
            {
                var dllPath = AppDomain.CurrentDomain.GetData("dllpath") as string;

                var converter =
                    new ThreadSafeConverter(
                        new RemotingToolset<PdfToolset>(
                            new StaticDeployment(dllPath)));

                var document = new HtmlToPdfDocument 
                { 
                    Objects = 
                    { 
                        new ObjectSettings { PageUrl = "www.google.com" } 
                    } 
                };

                AppDomain.CurrentDomain.SetData("result", converter.Convert(document));
            };

            // act
            domain1.SetData("dllpath", GetDeploymentPath());
            domain1.DoCallBack(callback);
            result1 = domain1.GetData("result") as byte[];
            AppDomain.Unload(domain1);

            domain2.SetData("dllpath", GetDeploymentPath());
            domain2.DoCallBack(callback);
            result2 = domain2.GetData("result") as byte[];
            AppDomain.Unload(domain2);

            // assert
            Assert.IsNotNull(result1);
            Assert.IsNotNull(result2);
        }
Example #4
0
        public FileResult ScratchPad()
        {
            var doc = new HtmlToPdfDocument();
            var obj = new ObjectSettings();

            obj.PageUrl = Url.Action("PostAnything", "Home", routeValues: null, protocol: Request.Url.Scheme);
            obj.LoadSettings.CustomHeaders.Add("X-MY-HEADER", "my value");
            obj.LoadSettings.Cookies.Add("my_awesome_cookie", "cookie value");
            obj.LoadSettings.PostItems.Add(new PostItem 
            { 
                Name = "my_special_value", 
                Value = "is an amazing value" 
            });

            doc.Objects.Add(obj);

            var result = anotherConverter.Convert(doc);

            return File(result, "application/pdf");
        }
Example #5
0
        public IActionResult CreatePDF(string url)
        {
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10, Left = 25, Right = 25
                },
                DocumentTitle = "PDF Report",
                //Out = @"D:\PDFCreator\Employee_Report.pdf"  USE THIS PROPERTY TO SAVE PDF TO A PROVIDED LOCATION
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount = true,
                //HtmlContent = TemplateGenerator.GetHTMLString(),
                Page           = url, //USE THIS PROPERTY TO GENERATE PDF CONTENT FROM AN HTML PAGE
                WebSettings    = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
                HeaderSettings = { FontName = "Arial", FontSize = 12, Right = "Page [page] of [toPage]", Line = true },
                FooterSettings = { FontName = "Arial", FontSize = 12, Line = true, Center = "Report Footer" }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            //_converter.Convert(pdf); IF WE USE Out PROPERTY IN THE GlobalSettings CLASS, THIS IS ENOUGH FOR CONVERSION



            var file = _converter.Convert(pdf);

            //return Ok("Successfully created PDF document.");
            //return File(file, "application/pdf", "EmployeeReport.pdf");
            return(File(file, "application/pdf"));
        }
Example #6
0
        public async Task <string> CreatePdfAsync()
        {
            try
            {
                /// Cài đặt hiển thị cho pdf khi được generate
                var globalSetting = new GlobalSettings
                {
                    ColorMode   = ColorMode.Color,      //Tạo file màu hoặc đen trắng: Color: màu giống như html, Gray: đen trắng
                    Orientation = Orientation.Portrait, // Chiều đặt của giấy: Portrait: dọc, Landscape: ngang
                    PaperSize   = PaperKind.A4,         //Kiểu giấy
                    Margins     = new MarginSettings {
                        Top = 1, Left = 1, Unit = Unit.Millimeters
                    },                                                   // Căn lề
                    DocumentTitle = @"Pdf minh họa",                     // Title file
                    Out           = @"D:\PDFCreator\Employee_Report.pdf" // Out ra file - cần tạo ra file chứa trước
                };


                /// Lấy dữ liệu - html của website cần chuyển sang pdf
                var ObjectSettings = new ObjectSettings
                {
                    PagesCount  = true,
                    HtmlContent = await getWebsiteContent(@"https://www.youtube.com/watch?v=tt-blq_YuwE&list=RDyJytt8T2naw&index=15")
                };

                var doc = new HtmlToPdfDocument
                {
                    GlobalSettings = globalSetting,
                    Objects        = { ObjectSettings }
                };

                this._converter.Convert(doc);

                return("Tạo pdf thành công");
            }
            catch (Exception ex)
            {
                return("Có lỗi xảy ra: " + ex);
            }
        }
Example #7
0
        // GET: Orders/DownloadInvoice
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        // Action -> print or donwload
        public async Task <IActionResult> DownloadInvoice(string invoiceAction)
        {
            Cart cart = await _helper.GetFullCartData(SessionNames.INVOICE);

            ViewBag.Action = invoiceAction;

            if (invoiceAction == "print")
            {
                return(View("InvoiceToPrint", cart));
            }

            string body = await RazorTemplateEngine.RenderAsync(@"~/Views/Orders/InvoiceToPrint.cshtml", cart);


            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10, Bottom = 10
                },
                DocumentTitle = "Invoice"
            };
            var objectSettings = new ObjectSettings
            {
                PagesCount     = true,
                HtmlContent    = body,
                FooterSettings = { FontName = "Arial", FontSize = 10, Left = "DMS-OShopping", Line = true, Right = "Page [page] of [toPage]" }
            };
            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf", "Invoice.pdf"));
        }
Example #8
0
        public IActionResult createPDF(int orderId)
        {
            PdfInvoiceTemplateGenerator pdfGenerator = new PdfInvoiceTemplateGenerator(_iorder, _config);

            try
            {
                var globalSettings = new GlobalSettings
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize   = PaperKind.A4,
                    Margins     = new MarginSettings {
                        Top = 10
                    },
                    DocumentTitle = "PDF Report",
                    Out           = _config["PdfPath"] + orderId + ".pdf"
                };
                var objectSettings = new ObjectSettings
                {
                    PagesCount  = true,
                    HtmlContent = pdfGenerator.GetHTMLString(orderId),
                    // WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "Assets", "styles.css") },
                    WebSettings    = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(_config["PdfPath"], "Assets", "styles.css") },
                    HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                    FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Visit   http://dollaritem.co.nz/ecom/terms-and-conditions   for full return terms and conditions." }
                };
                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects        = { objectSettings }
                };
                _converter.Convert(pdf);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }

            return(Ok("Successfully created PDF document."));
        }
Example #9
0
        public IActionResult IssuePDF()
        {
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10
                },
                DocumentTitle = "Good Issue Report"
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount  = true,
                HtmlContent = InvoiceGeneratePDF.GetIssueHTMLString(),
                WebSettings =
                {
                    DefaultEncoding = "utf-8",
                    UserStyleSheet  = Path.Combine(
                        Directory.GetCurrentDirectory(), "assets", "styles.css")
                },
                HeaderSettings =
                {
                    FontName = "Arial",                 FontSize = 9,
                    Right    = "Trang [page]/[toPage]", Line     = true
                }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf"));
        }
        public async Task <IActionResult> CreatePDF(int id)
        {
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10
                },
                DocumentTitle = "Zamówienie z TesarStudio",
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount  = true,
                HtmlContent = await _orderPdfService.GetHtmlString(new GetOrderQuery
                {
                    Id = id
                }),
                Page        = "https://localhost:5000/api/PdfCreator",
                WebSettings =
                {
                    DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "style.css")
                },
                HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Strona [page] z [toPage]", Line = true },
                FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Wygenerowano za pomocą systemu Tesar Studio" }
            };


            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf", "Zamowienie.pdf"));
        }
Example #11
0
        public async Task <IActionResult> GetInvoicePdf(string orderNumber)
        {
            var searchCriteria = AbstractTypeFactory <CustomerOrderSearchCriteria> .TryCreateInstance();

            searchCriteria.Number = orderNumber;
            searchCriteria.Take   = 1;

            var orders = await _searchService.SearchCustomerOrdersAsync(searchCriteria);

            var order = orders.Results.FirstOrDefault();

            if (order == null)
            {
                throw new InvalidOperationException($"Cannot find order with number {orderNumber}");
            }

            var notification = new InvoiceEmailNotification {
                CustomerOrder = order
            };
            await _notificationSender.SendNotificationAsync(notification, order.LanguageCode);

            var message = AbstractTypeFactory <NotificationMessage> .TryCreateInstance($"{notification.Kind}Message");

            message.LanguageCode = order.LanguageCode;
            var emailNotificationMessage = (EmailNotificationMessage)notification.ToMessage(message, _notificationTemplateRenderer);

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = { ColorMode = ColorMode.Color, Orientation = Orientation.Landscape, PaperSize = PaperKind.A4Plus },
                Objects        = { new ObjectSettings {
                                       PagesCount = true, HtmlContent = emailNotificationMessage.Body
                                   } }
            };
            var    converter = new SynchronizedConverter(new PdfTools());
            var    byteArray = converter.Convert(pdf);
            Stream stream    = new MemoryStream(byteArray);

            return(new FileStreamResult(stream, "application/pdf"));
        }
Example #12
0
        //todo:Jogar esta parte na camada de dominios
        private IActionResult ExecutaRelatorio(RelatorioDTO dto, IRelatorioTemplate rel, Orientation orientacao)
        {
            var cabecalho = new CabecalhoTemplate(
                rel.GerarHtml(dto),
                rel.Titulo,
                rel.Descricao,
                new ParametroService(new ParametroRepository(_context)),
                new EmpresaService(new EmpresaRepository(_context)),
                new UsuarioService(new UsuarioRepository(_context)));

            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = orientacao,
                    PaperSize   = PaperKind.A4,
                    //Out = @"C:\DinkToPdf\src\DinkToPdf.TestThreadSafe\test.pdf", imforam caso queira salva ro documento
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PagesCount  = true,
                        HtmlContent = cabecalho.GerarHtml(dto),
                        WebSettings ={ DefaultEncoding                   = "utf-8" },
                        //WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet =  Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") }, para carregar um css externo
                        HeaderSettings ={ Spacing                           =       3 },
                        FooterSettings ={ FontSize                          =7, Spacing = 3, Left = "Usuário: " + cabecalho.GetUsuarioLogin(), Center = "Pagina [page] de [toPage]", Right = "Data hora: " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"), Line = true, },
                    }
                }
            };

            var file = _converter.Convert(doc);

            var nomeFile = cabecalho.GetNomeArquivo();

            return(File(file, "application/pdf", nomeFile));
        }
Example #13
0
        public async Task <ActionResult> GetInvoiceByUserInvoiceId(string invoiceId)
        {
            string UserId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            try
            {
                string userTableName = await _singleton.userRepository.GetUserOrdersTableName(UserId);

                var invoiceHtml = await _singleton.orderRepository.DownLoadInvoiceByUserInvoiceId(invoiceId, UserId, userTableName);

                var globalSettings = new GlobalSettings {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    Margins     = new MarginSettings {
                        Top = 10
                    },
                    PaperSize = PaperKind.A4,
                };
                var objectSettings = new ObjectSettings()
                {
                    PagesCount     = true,
                    HtmlContent    = invoiceHtml,
                    HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 },
                    FooterSettings = { FontName = "Arial", FontSize = 9, Center = "Report Header" }
                };

                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects        = { objectSettings }
                };
                var file = _converter.Convert(pdf);
                return(File(file, "applicatio/pdf", "Invoice.pdf"));
            }
            catch (Exception e)
            {
                throw;
            }
        }
        public byte[] Convert(string htmlContent, PechkinPaperSize paperSize)
        {
            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize   = paperSize,
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        HtmlContent = htmlContent,
                        WebSettings ={ DefaultEncoding                   = "utf-8" }
                    }
                }
            };

            return(_pdfConverter.Convert(doc));
        }
        public IActionResult PdfSource([FromBody] HtmlSource htmlSource) //string htmlContent
        {
            //var converter = new BasicConverter(new PdfTools());
            CustomAssemblyLoadContext context = new CustomAssemblyLoadContext();

            context.LoadUnmanagedLibrary(@"C:\Users\stani\Desktop\storemanagementsystemweb\StoreSystem.Web\libwkhtmltox.dll");

            var converter = new SynchronizedConverter(new PdfTools());


            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize   = PaperKind.A4,
                    Margins     = new MarginSettings()
                    {
                        Top     =         10
                    },
                    Out         = @"D:\test.pdf",
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PagesCount     = true,
                        HtmlContent    = htmlSource.Source,
                        WebSettings    = { DefaultEncoding = "utf-8" },
                        HeaderSettings ={ FontSize                             =9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
                    }
                }
            };


            converter.Convert(doc);
            return(StatusCode(200, "success"));
        }
Example #16
0
        public IActionResult createPDF(int invoice_number, string gst)
        {
            PdfInvoiceTemplateGenerator pdfGenerator = new PdfInvoiceTemplateGenerator(_invoice);

            try
            {
                var globalSettings = new GlobalSettings
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize   = PaperKind.A4,
                    Margins     = new MarginSettings {
                        Top = 10
                    },
                    DocumentTitle = "PDF Report",
                    Out           = _config["PdfPath"] + invoice_number + ".pdf"
                };
                var objectSettings = new ObjectSettings
                {
                    PagesCount     = true,
                    HtmlContent    = pdfGenerator.GetHTMLString(invoice_number),
                    WebSettings    = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(_config["PdfPath"], "Assets", "styles.css") },
                    HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                    FooterSettings = { FontName = "Arial", FontSize = 9, Line = true }
                };
                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects        = { objectSettings }
                };
                _converter.Convert(pdf);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }

            return(Ok("Successfully created PDF document."));
        }
Example #17
0
        private string CreatePdf(string html, PdfGeneratorSettings settings, string uri = null)
        {
            var globalSettings = MapSettings(settings);

            var objectSettings = uri == null
                ? new ObjectSettings {
                HtmlContent = html
            }
                : new ObjectSettings {
                Page = uri
            };

            var doc = new HtmlToPdfDocument
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            _synchronizedConverter.Convert(doc);

            return(globalSettings.Out);
        }
Example #18
0
        /// <summary>
        /// 创建PDF
        /// </summary>
        /// <param name="htmlContent">传入html字符串</param>
        /// <returns></returns>
        public byte[] CreatePDF(string htmlContent)
        {
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                //Margins = new MarginSettings
                //{
                //    Top = 10,
                //    Left = 0,
                //    Right = 0,
                //},
                DocumentTitle = "PDF Report",
            };

            var objectSettings = new ObjectSettings
            {
                PagesCount  = true,
                HtmlContent = htmlContent,
                // Page = "www.baidu.com", //USE THIS PROPERTY TO GENERATE PDF CONTENT FROM AN HTML PAGE  这里是用现有的网页生成PDF
                //WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
                WebSettings = { DefaultEncoding = "utf-8" },
                //HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                //FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            //return File(file, "application/pdf");

            return(file);
        }
Example #19
0
        /// <summary>
        /// 將 Html 文字 輸出到 PDF 檔裡
        /// </summary>
        /// <param name="htmlText"></param>
        /// <returns></returns>
        public static byte[] ConvertHtmlTextToPDF(string htmlText)
        {
            if (string.IsNullOrEmpty(htmlText))
            {
                return(null);
            }

            var document = new HtmlToPdfDocument
            {
                GlobalSettings = { },
                Objects        =
                {
                    new ObjectSettings {
                        HtmlText = htmlText
                    }
                }
            };

            var result = converter.Convert(document);

            return(result);
        }
        private void ConvertHTMLToPDF(string html)
        {
            Log("Converting HTML to PDF");
            Log("Ignore errors like 'Qt: Could not initialize OLE (error 80010106)'", LogLevel.Warning);
            var converter = new BasicConverter(new PdfTools());

            var output = _options.Output;

            if (output == null)
            {
                output = Path.Combine(Directory.GetCurrentDirectory(), "export.pdf");
            }

            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Portrait,
                    PaperSize   = PaperKind.A4,
                    Out         = output,
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PagesCount     = true,
                        HtmlContent    = html,
                        WebSettings    = { DefaultEncoding = "utf-8"              },
                        HeaderSettings ={ FontSize                             =9, Left = _options.HeaderLeft, Center = _options.HeaderCenter, Right = _options.HeaderRight, Line = true, Spacing = 2.812 },
                        FooterSettings ={ Left                                 = _options.FooterLeft, Center = _options.FooterCenter, Right = _options.FooterRight},
                        UseLocalLinks  = true
                    }
                }
            };

            converter.Convert(doc);
            Log($"PDF created at: {output}");
        }
        public async Task <byte[]> CreatePdfDocument(IPdfBuildModel buildModel, IPdfPageSpecification pdfPageSpecification)
        {
            try
            {
                if (!buildModel.IsValid())
                {
                    throw new ArgumentNullException(nameof(buildModel));
                }

                GlobalSettings globalSettings = await GetGlobalSettings(buildModel, pdfPageSpecification);

                ObjectSettings objectSettings = await GetDefaultObjectSettings(buildModel, pdfPageSpecification);

                HtmlToPdfDocument pdfDocument = await ConvertToPdf(globalSettings, objectSettings);

                return(_converter.Convert(pdfDocument));
            }
            catch (Exception ex)
            {
                throw new ArgumentException(nameof(CreatePdfDocument), ex);
            }
        }
Example #22
0
        public byte[] GeneratePDF(string ReportType, IQueryCollection Data)
        {
            var html = this.htmlService.GenerateHtml(ReportType, Data);


            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings = new GlobalSettings()
                {
                    Margins = new MarginSettings(0, 0, 0, 0)
                }
            };

            doc.Objects.Add(new ObjectSettings()
            {
                HtmlContent = html,
            });

            var pdf = converter.Convert(doc);

            return(pdf);
        }
Example #23
0
        /// <summary>
        /// A stub that copies the invoice_sample pdf. This file should be removed
        /// from the project when this stub is replaced with "real" code
        /// </summary>
        /// <param name="InvoiceNumber">The invoice to create</param>
        /// <returns>The filename/path of the generated pdf</returns>
        private string CreatePdf(string InvoiceNumber)
        {
            try
            {
                DeletePdf(InvoiceNumber);

                var doc = new HtmlToPdfDocument()
                {
                    GlobalSettings =
                    {
                        ColorMode   = ColorMode.Color,
                        Orientation = Orientation.Portrait,
                        PaperSize   = PaperKind.A4,
                        Margins     = new MarginSettings()
                        {
                            Top     = 10
                        }
                    },
                    Objects =
                    {
                        new ObjectSettings()
                        {
                            HtmlContent = @"<html><body><div>Hello</div></body></html>",
                        }
                    }
                };

                byte[] pdf = converter.Convert(doc);

                var destination = GetDestination(InvoiceNumber);
                File.WriteAllBytes(destination, pdf);

                return(destination);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Example #24
0
        public IActionResult Imprimir([FromBody] FiltroConselhoCommands command)
        {
            //var conselhos = _conselhoHandler.Handle(command);
            var conselho = new List <ListarConselhoResults>();

            //switch (command.TipoFiltro)
            //{
            //    case "Série":
            conselho = _conselhoRepositorio.FiltrarPorSerie(command);
            //break;
            //case "Aluno":
            //    return conselho = _conselhoRepositorio.FiltrarPorAluno(command);

            //case "Data":
            //    return conselho = _conselhoRepositorio.FiltrarTodosPorData(command);

            //    default:
            //        return null;
            //}

            var obj = TemplateGenerator.ListarConselho(conselho);


            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = ConfiguracaoPdf._GlobalSettings(Orientation.Landscape),
                Objects        = { ConfiguracaoPdf._ObjectSettings(obj, "assets", "bootstrap.min.css") }
            };

            //_converter.Convert(pdf); IF WE USE Out PROPERTY IN THE GlobalSettings CLASS, THIS IS ENOUGH FOR CONVERSION

            var file = _converter.Convert(pdf);

            //return Ok("Successfully created PDF document.");
            //return File(file, "application/pdf", "EmployeeReport.pdf"); USE THIS RETURN STATEMENT TO DOWNLOAD GENERATED PDF DOCUMENT
            return(File(file, "application/pdf"));

            //return conselhos;
        }
Example #25
0
        private void CreatePdfFile(List <Match> matches, string relativeFilePath)
        {
            var fullPath = Path.GetFullPath(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\.."), relativeFilePath));

            var converter = new BasicConverter(new PdfTools());

            var doc = new HtmlToPdfDocument()
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Landscape,
                    PaperSize   = PaperKind.A4,
                },
                Objects =
                {
                    new ObjectSettings()
                    {
                        PagesCount     = true,
                        HtmlContent    = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In consectetur mauris eget ultrices iaculis. Ut et odio viverra, molestie lectus nec, venenatis turpis. Nulla quis euismod nisl. Duis scelerisque eros nec dui facilisis, sit amet porta odio varius. Praesent vitae sollicitudin leo. Sed vitae quam in massa eleifend porta. Aliquam pulvinar orci dapibus porta laoreet. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed commodo tortor eget dolor hendrerit dapibus.
                                        Vivamus lorem diam, vulputate at ultrices quis, tristique eu nunc. Sed bibendum hendrerit leo. Nulla nec risus turpis. Vivamus at tortor felis. Donec eget posuere libero. Pellentesque erat nunc, molestie eget gravida vitae, eleifend a eros. Integer in tortor sed elit aliquam vehicula eget a erat. Vivamus nisi augue, venenatis ut commodo vel, congue id neque. Curabitur convallis dictum semper. Nulla accumsan urna aliquet, mattis dolor molestie, fermentum metus. Quisque at nisi non augue tempor commodo et pretium orci.
                                        Quisque blandit libero ut laoreet venenatis. Morbi sit amet quam varius, euismod dui et, volutpat felis. Sed nec ante vel est convallis placerat. Morbi mollis pretium tempor. Aliquam luctus eu justo vitae tristique. Sed in elit et elit sagittis pharetra sed vitae velit. Proin eget mi facilisis, scelerisque justo in, ornare urna. Aenean auctor ante ex, eget mattis neque pretium id. Aliquam ut risus leo. Vivamus ullamcorper et mauris in vehicula. Maecenas tristique interdum tempus. Etiam mattis lorem eget odio faucibus, in rhoncus nisi ultrices. Etiam at convallis nibh. Suspendisse tincidunt velit arcu, a volutpat nulla euismod sed.
                                        Aliquam mollis placerat blandit. Morbi in nibh urna. Donec nisl enim, tristique id tincidunt sed, pharetra non mi. Morbi viverra arcu vulputate risus dignissim efficitur. Vivamus dolor eros, finibus et porttitor a, pellentesque a lectus. Integer pellentesque maximus velit sit amet sollicitudin. Nulla a elit eget augue pretium luctus quis eu metus. Aenean nec dui id nibh tempor dapibus. Pellentesque dignissim ullamcorper mauris, vitae pharetra turpis sodales sit amet. Etiam et bibendum neque.
                                        Nulla gravida sit amet velit eu aliquet. Etiam sit amet elit leo. Sed nec arcu tincidunt, placerat turpis quis, laoreet nulla. Aenean neque est, fringilla non nulla in, laoreet vehicula nunc. Etiam vel nisl sit amet lectus pellentesque eleifend. Etiam sed nisi dolor. Mauris quis tincidunt ex. Aliquam porta mattis tempor. Maecenas fringilla bibendum elementum. Vestibulum quis tempus libero, vitae cursus neque. Suspendisse lectus risus, lacinia consectetur enim quis, ullamcorper porta tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
                        WebSettings    = { DefaultEncoding = "utf-8"                   },
                        HeaderSettings ={ FontSize                             =9, Right = "Page [page] of [toPage]", Line = true },
                        FooterSettings ={ FontSize                             =9, Right = "Page [page] of [toPage]" }
                    }
                }
            };

            byte[] pdf = converter.Convert(doc);

            using (FileStream stream = new FileStream(fullPath, FileMode.Create))
            {
                stream.Write(pdf, 0, pdf.Length);
            }
        }
        public IActionResult CreatePDF()
        {
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10
                },
                DocumentTitle = "PDF Report",
                //Print pdf in local stroge
                //Out = @"C:\Users\User\Desktop\Pdfconvertor\Employee_Report.pdf"
            };
            var objectSettings = new ObjectSettings
            {
                PagesCount     = true,
                HtmlContent    = TemplateGenerator.GetHTMLString(),
                WebSettings    = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "styles.css") },
                HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
            };
            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            //print pdf local stroge
            //_converter.Convert(pdf);
            //return Ok("Successfully created PDF document.");

            //print to Browser
            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf"));
            //print to Browser
        }
        public IActionResult CreatePDF(int id)
        {
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "pdfs",
                                        "CareGiverTestList" + DateTime.Now.ToString("dd/MM/yyyy-hh-mm-ss") + ".pdf");

            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Landscape,
                PaperSize   = PaperKind.A4Plus,
                Margins     = new MarginSettings {
                    Top = 10
                },
                DocumentTitle = "PDF Report",
                // Out = filePath
            };
            TestUtility _testUtility = new TestUtility(_appSettings, _dbContext);
            var         userTests    = _testUtility.GetEmployeeTests(id);
            TemplateGeneratorUtility _templateGeneratorUtility = new TemplateGeneratorUtility(_appSettings, _dbContext);

            var objectSettings = new ObjectSettings
            {
                PagesCount     = true,
                HtmlContent    = _templateGeneratorUtility.GetHTMLString(userTests),
                WebSettings    = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "css", "pdfstyles.css") },
                HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "" }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };
            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf", "EmployeeReport.pdf"));
        }
Example #28
0
        /// <summary>
        ///    根据模板导出列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <param name="dataItems"></param>
        /// <param name="htmlTemplate"></param>
        /// <returns></returns>
        public async Task <TemplateFileInfo> ExportListByTemplate <T>(string fileName, ICollection <T> dataItems, string htmlTemplate = null) where T : class
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentException("文件名必须填写!", nameof(fileName));
            }

            var exporter   = new HtmlExporter();
            var htmlString = await exporter.ExportListByTemplate(dataItems, htmlTemplate);

            var converter = new BasicConverter(new PdfTools());
            var doc       = new HtmlToPdfDocument
            {
                GlobalSettings =
                {
                    ColorMode   = ColorMode.Color,
                    Orientation = Orientation.Landscape,
                    PaperSize   = PaperKind.A4,
                    Out         = fileName,
                },
                Objects =
                {
                    new ObjectSettings
                    {
                        PagesCount     = true,
                        HtmlContent    = htmlString,
                        WebSettings    = { DefaultEncoding = "utf-8" },
                        HeaderSettings ={ FontSize                             =9, Right = "[page]/[toPage]", Line = true, Spacing = 2.812 },
                        Encoding       = System.Text.Encoding.UTF8
                    }
                }
            };

            converter.Convert(doc);
            var fileInfo = new TemplateFileInfo(fileName, "application/pdf");

            return(fileInfo);
        }
Example #29
0
        public async Task <Dictionary <string, byte[]> > GetBillsBinary(List <Bill> requestedBills)
        {
            var apartments = await this.apartmentRepository.GetAllAsync();

            Dictionary <string, byte[]> billsData = new Dictionary <string, byte[]>();

            for (int i = 0; i < requestedBills.Count(); i++)
            {
                var apartmentNo = requestedBills.ElementAt(i).Apartment;
                var apartment   = await this.apartmentRepository.GetByNumber(apartmentNo);

                Bill bill = await billRepository.GetBillById(requestedBills.ElementAt(i).BillId);

                double debt = await billRepository.GetDebtAsync(apartmentNo); //change this to Apartment as well

                var objectSettings = new ObjectSettings
                {
                    PagesCount  = true,
                    HtmlContent = HTMLGenerator.GetBillAsHtmlString(apartment, bill, debt),
                    WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "Assets", "bills.scss") },
                };

                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = globalSettings,
                    Objects        = { objectSettings }
                };

                //billAsBinaryData[i] = this.converter.Convert(pdf);

                var bin         = this.converter.Convert(pdf);
                var pdfFileName = "arve-2020-" + bill.MonthToPayFor + "-korter" + bill.Apartment.ToString();

                billsData.Add(pdfFileName, bin);
            }

            return(billsData);
        }
Example #30
0
    public static byte[] ToPdf(string htmlText)
    {
        // https://github.com/tuespetre/TuesPechkin/blob/develop/TuesPechkin/Document/GlobalSettings.cs
        var document = new HtmlToPdfDocument
        {
            GlobalSettings =
            {
                DPI            =               300,
                ProduceOutline = true,
                DocumentTitle  = "Pretty Websites",
                PaperSize      = PaperKind.A4,    // Implicit conversion to PechkinPaperSize
                Margins        =
                {
                    All  =             1.375,
                    Unit = Unit.Centimeters
                }
            },
            Objects =
            {
                new ObjectSettings
                {
                    HtmlText    = htmlText,
                    WebSettings = new WebSettings()
                    {
                        EnableJavascript           = false,
                        PrintMediaType             = true,
                        EnableIntelligentShrinking = true
                    }
                },
                //new ObjectSettings { PageUrl = pageUrl }
            }
        };

        byte[] result = convertidor.Convert(document);
        //System.IO.File.WriteAllBytes(@"C:\Users\DRIVE_D\My Documents\_GIT_VCS\AspDotNetGabs\testpdf.pdf", result);

        return(result);
    }
Example #31
0
        public Task <byte[]> CreatePDF(GlobalSettings optionalGlobalSettings, ObjectSettings ObjectSettings)
        {
            return(Task.Run(() =>
            {
                if (optionalGlobalSettings == null)
                {
                    optionalGlobalSettings = new GlobalSettings();
                }

                if (optionalGlobalSettings.ColorMode == null)
                {
                    optionalGlobalSettings.ColorMode = ColorMode.Color;
                }

                if (optionalGlobalSettings.Orientation == null)
                {
                    optionalGlobalSettings.Orientation = Orientation.Portrait;
                }

                if (optionalGlobalSettings.PaperSize == null)
                {
                    optionalGlobalSettings.PaperSize = PaperKind.A4;
                }

                if (optionalGlobalSettings.DocumentTitle == null)
                {
                    optionalGlobalSettings.DocumentTitle = "Relatório";
                }

                var pdf = new HtmlToPdfDocument()
                {
                    GlobalSettings = optionalGlobalSettings,
                    Objects = { ObjectSettings }
                };

                return _converter.Convert(pdf);
            }));
        }
Example #32
0
        public IActionResult Get()
        {
            try
            {
                var doc = new HtmlToPdfDocument()
                {
                    GlobalSettings =
                    {
                        PaperSize   = PaperKind.A3,
                        Orientation = Orientation.Landscape,
                    },

                    Objects =
                    {
                        new ObjectSettings()
                        {
                            Page           = "http://google.com/",
                            WebSettings    = { DefaultEncoding = "utf-8" },
                            HeaderSettings ={ FontSize                             =9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }
                        },
                        // new ObjectSettings()
                        //{
                        //    Page = "https://github.com/",

                        //}
                    }
                };

                byte[] pdf = _converter.Convert(doc);

                return(File(pdf, "application/pdf", "Test.pdf"));
            }
            catch (Exception e)
            {
                _logger.LogError("Failed to generate pdf.", e);
                throw;
            }
        }
Example #33
0
        public async Task <ActionResult> ConvertHtmlToPdf()
        {
            var    postData    = AppTools.GetRequestBodyEntity <ExportModel>(HttpContext);
            string htmlContent = postData.Content;
            string title       = postData.Title;

            try
            {
                return(await Task.Run(() =>
                {
                    var doc = new HtmlToPdfDocument()
                    {
                        GlobalSettings =
                        {
                            ColorMode   = ColorMode.Color,
                            Orientation = Orientation.Portrait,
                            PaperSize   = PaperKind.A4Plus,
                        },
                        Objects =
                        {
                            new ObjectSettings()
                            {
                                PagesCount = true,
                                HtmlContent = htmlContent,
                                WebSettings ={ DefaultEncoding                   = "gb2132" },
                            }
                        }
                    };
                    byte[] pdf = PdfConverter.Convert(doc);
                    var f = File(pdf, "application/pdf", title, true);
                    return f;
                }));
            }
            catch (Exception)
            {
                return(null);
            }
        }
Example #34
0
        public IActionResult Pdf()
        {
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 10
                },
                DocumentTitle = "Pdf Export",
                // Out = @"C:\LogFolder\Report.pdf" burası calıstıgı zaman dosyanın indirileceği yeri belirtiyoruz
            };
            var objectSettings = new ObjectSettings
            {
                PagesCount  = true,
                HtmlContent = TemplateGenerator.GetHtmlString(),
                WebSettings =
                {
                    DefaultEncoding = "utf-8",
                    UserStyleSheet  = Path.Combine(Directory.GetCurrentDirectory(), "assets", "style.css")
                },
                HeaderSettings = { FontName = "arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
                FooterSettings = { FontName = "arial", FontSize = 9, Line = true, Center = "Report Footer" }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf", "Info.pdf")); // pdf indirilir
            // return File(file, "application/pdf"); pdf indirilmesin sadece tarayıcı icerisinde göreyim dersen burası
            //return Ok("successfully created pdf, exported LogFolder"); Out özelliğini set edersek burasını acalım
        }
Example #35
0
        public void UnloadsWkhtmltoxWhenAppDomainUnloads()
        {
            // arrange
            var domain = GetAppDomain("testing_unload");

            // act
            domain.DoCallBack(() =>
            {
                var converter =
                    new ThreadSafeConverter(
                        new RemotingToolset<PdfToolset>(
                            new Win32EmbeddedDeployment(
                                new StaticDeployment(Path.GetTempPath()))));

                var document = new HtmlToPdfDocument("<p>some html</p>");

                converter.Convert(document);
            });
            AppDomain.Unload(domain);

            // assert
            Assert.IsFalse(Process
                .GetCurrentProcess()
                .Modules
                .Cast<ProcessModule>()
                .Any(m => m.ModuleName == "wkhtmltox.dll"));
        }
Example #36
0
        public void ReturnsResultFromString()
        {
            var document = new HtmlToPdfDocument("<p>some html</p>");

            var result = converter.Convert(document);

            Assert.IsNotNull(result);
        }