Exemplo n.º 1
0
        /// <summary>
        /// Create PDF using PdfSharp project, save to file and open that file.
        /// </summary>
        private void OnGeneratePdf_Click(object sender, EventArgs e)
        {
            string outPDFPath = @"C:\Users\tmi\Downloads\obnova_kulturnych_pamiatok.1.0 (2)TMI (2).pdf";
            string htmlstring = generateHtml();

            if (!string.IsNullOrEmpty(htmlstring))
            {
                PdfGenerateConfig x = new PdfGenerateConfig();
                x.EnablePageNumbering        = true;
                x.PageNumbersFont            = new XFont("Times New Roman", 11);
                x.PageNumbersPattern         = "{0}/{1}";
                x.PageNumberLocation         = PageNumberLocation.Middle;
                x.PageNumbersMarginBottom    = 20;
                x.PageNumbersLeftRightMargin = 10;
                x.PageSize = PageSize.A4;
                x.SetMargins(30);
                var pdf = PdfGenerator.GeneratePdf(htmlstring, x, null, null, null);

                using (FileStream fs = new FileStream(outPDFPath, FileMode.Create))
                {
                    pdf.Save(fs, true);
                }

                System.Diagnostics.Process.Start(outPDFPath);
            }
        }
Exemplo n.º 2
0
        private void tsb_Print_Click(object sender, EventArgs e)
        {
            PrintDialog pdlg = new PrintDialog();

            pdlg.Document = pd;
            DialogResult dlgRes = pdlg.ShowDialog();

            if (dlgRes == DialogResult.OK)
            {
                config.PageSize = PageSize.A4;
                config.SetMargins(20);
                XSize orgPageSize = PageSizeConverter.ToSize(config.PageSize);
                orgPageSize = new Size(Convert.ToInt32(orgPageSize.Width), Convert.ToInt32(orgPageSize.Height));
                pageSize    = new Size(Convert.ToInt32(orgPageSize.Width - config.MarginLeft - config.MarginRight), Convert.ToInt32(orgPageSize.Height - config.MarginTop - config.MarginBottom));
                hc.SetHtml(_mainControl._htmlPanel.Text);
                hc.Location = new PointF(config.MarginLeft, config.MarginTop);
                hc.MaxSize  = new Size(Convert.ToInt32(pageSize.Width), 0);
                hc.SetHtml(_mainControl._htmlPanel.Text);

                scrollOffset = 0;

                hc.UseGdiPlusTextRendering = true;

                //SizeF szf = new SizeF(pd.DefaultPageSettings.PaperSize.Width, pd.DefaultPageSettings.PaperSize.Height);
                //hc.MaxSize = szf;
                iPage = 0;
                bFirstPagePrinting = true;
                pd.Print();
            }
        }
Exemplo n.º 3
0
        public void GeneratePdf_ValidHtmlContent_ReturnPdfDocument()
        {
            const string htmlContent = @"
                <!DOCTYPE html>
                <html lang=""en"">
                <head>
                    <meta charset=""UTF-8"">
                    <link rel=""Stylesheet"" href=""StyleSheet"" />
                    <title>F#</title>
                </head>
                <body>
                    <h1>F Sharp (programming language) ภาษา F#</h1>
                    <p>
                        F# is a mature, open source, cross-platform, functional-first programming language. 
                        It empowers users and organizations to tackle complex computing problems with simple, 
                        maintainable and robust code.
                    </p>
                </body>
                </html>";

            /*
             * By default, A runtime throws a NotSupportedException
             * "No data is available for encoding 1252." on .NET Core.
             * To fix, add a dependency to the package System.Text.Encoding.CodePages
             * and then add code to register the code page provider during application initialization (f.ex in Startup.cs):
             *
             * System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
             * This is required to parse strings in binary BIFF2-5 Excel documents encoded with DOS-era code pages.
             * These encodings are registered by default in the full .NET Framework, but not on .NET Core.
             */
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var config = new PdfGenerateConfig {
                PageSize = PageSize.A4
            };

            config.SetMargins(20);

            var document = PdfGenerator.GeneratePdf(
                htmlContent,
                config,
                null,
                OnStylesheetLoad,
                OnImageLoadPdfSharp
                );

            var tempFile = Path.GetFileNameWithoutExtension(
                $"{Path.GetTempFileName()}.pdf"
                );

            document.Save(tempFile);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Create PDF using PdfSharp project, save to file and open that file.
        /// </summary>
        private void OnGeneratePdf_Click(object sender, EventArgs e)
        {
            PdfGenerateConfig config = new PdfGenerateConfig();

            config.PageSize = PageSize.A4;
            config.SetMargins(20);

            var doc     = PdfGenerator.GeneratePdf(_mainControl.GetHtml(), config, null, DemoUtils.OnStylesheetLoad, HtmlRenderingHelper.OnImageLoadPdfSharp);
            var tmpFile = Path.GetTempFileName();

            tmpFile = Path.GetFileNameWithoutExtension(tmpFile) + ".pdf";
            doc.Save(tmpFile);
            Process.Start(tmpFile);
        }
Exemplo n.º 5
0
 public static Byte[] PdfSharpConvert(String html)
 {
     Byte[] res = null;
     using (MemoryStream ms = new MemoryStream())
     {
         PdfGenerateConfig config = new PdfGenerateConfig();
         config.PageSize = PageSize.A4;
         config.SetMargins(20);
         var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, config, null, PdfUtils.OnStylesheetLoad);
         pdf.Save(ms);
         res = ms.ToArray();
     }
     return(res);
 }
Exemplo n.º 6
0
        public static Stream ToPDF(this HtmlAgilityPack.HtmlDocument htmlDocument)
        {
            var config = new PdfGenerateConfig
            {
                PageSize = PdfSharp.PageSize.A4
            };

            config.SetMargins(20);

            PdfDocument doc    = PdfGenerator.GeneratePdf(htmlDocument.ParsedText, config);
            var         output = new MemoryStream();

            doc.Save(output);
            return(output);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Create PDF using PdfSharp project, save to file and open that file.
        /// </summary>
        private async Task OnGeneratePdf_Click(object sender, EventArgs e)
        {
            PdfGenerateConfig config = new PdfGenerateConfig();

            config.PageSize = PageSize.A4;
            config.SetMargins(20);

            var doc = await PdfGenerator.GeneratePdf(_resourceServer, config);

            var tmpFile = Path.GetTempFileName();

            tmpFile = Path.GetFileNameWithoutExtension(tmpFile) + ".pdf";
            doc.Save(tmpFile);
            Process.Start(tmpFile);
        }
Exemplo n.º 8
0
        public Stream CreateFromHtmlString(string HtmlString)
        {
            var config = new PdfGenerateConfig
            {
                PageSize        = PageSize.A4,
                PageOrientation = PageOrientation.Portrait
            };

            config.SetMargins(16);
            var pdfDoc = PdfGenerator.GeneratePdf(HtmlString, config);

            var stream = new MemoryStream();

            pdfDoc.Save(stream, false);
            pdfDoc.Dispose();

            return(stream);
        }
Exemplo n.º 9
0
        public static void GenerarPDF(DataTable dtPDF)
        {
            try
            {
                string            pathPDF = "PDF/Reporte_Alumnos_" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ".pdf";
                StringBuilder     htmlPDF = new StringBuilder();
                PdfGenerateConfig config  = new PdfGenerateConfig();
                config.PageSize       = PageSize.Undefined;
                config.ManualPageSize = new XSize(1191, 842);
                //config.PageOrientation = PageOrientation.Portrait;
                config.SetMargins(20);

                //AGREGAR TITULO
                htmlPDF.AppendLine("<div style='font-family: arial; position: relative;'>");
                //EL TITULO DEL PDF
                htmlPDF.AppendLine("<center><h2>Reporte de Alumnos</h2></center>");
                htmlPDF.AppendLine("<br />");
                htmlPDF.AppendLine("<center>");
                htmlPDF.AppendLine("<table border='0' cellspacing='0' cellpadding='0' style='width: 1150px; border-collapse: collapse; border-spacing: 0px; border: 0.5px solid black; font-family:arial; font-size:15px;'>");


                //AGREGAR INFORMACION DE COLUMNAS
                htmlPDF.AppendLine("<thead style='background-color:#3B89D8; font-size:13px; color:white;'>");

                htmlPDF.AppendLine("<tr>");
                foreach (DataColumn dc in dtPDF.Columns)
                {
                    htmlPDF.AppendLine("<th style='text-align:left; background-color:#3B89D8; border: 0.5px solid black;'>" + dc.ColumnName + "</th>");
                }
                htmlPDF.AppendLine("</tr>");

                htmlPDF.AppendLine("</thead>");


                htmlPDF.AppendLine("<tbody>");
                //AGREGAR INFORMACION DE REGISTROS
                int    i = 0;
                string columnStyleHtml = string.Empty;
                foreach (DataRow dr in dtPDF.Rows.Cast <DataRow>().OrderBy(n => n["num_registro"]))
                {
                    if ((i % 2) == 0)
                    {
                        columnStyleHtml = "background-color:#ffffff;";
                        htmlPDF.AppendLine("<tr style='" + columnStyleHtml + "'>");
                    }
                    else
                    {
                        columnStyleHtml = "background-color:#CEE3F6;";
                        htmlPDF.AppendLine("<tr style='" + columnStyleHtml + "'>");
                    }

                    foreach (object obj in dr.ItemArray)
                    {
                        htmlPDF.AppendLine("<td style='border: 0.5px solid black; text-align:center;'>" + obj.ToString() + "</td>");
                    }

                    htmlPDF.AppendLine("</tr>");
                }
                htmlPDF.AppendLine("</tbody>");

                htmlPDF.AppendLine("</table>");
                htmlPDF.AppendLine("</div>");

                var doc = PdfGenerator.GeneratePdf(htmlPDF.ToString(), config);

                doc.Save(pathPDF);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 10
0
        public Stream Build(IEnumerable <IContent> contents)
        {
            string            htmlContent = _htmlGenerator.GenerateHtml(contents, Descriptor.SupportedFileExtension);
            PdfGenerateConfig config      = new PdfGenerateConfig();

            config.PageSize = PdfSharp.PageSize.A4;
            config.SetMargins(20);

            //var doc = PdfGenerator.GeneratePdf(htmlContent, config, null, OnStylesheetLoad);
            var doc = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(htmlContent, config, null, OnStylesheetLoad);

            byte[] fileContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                doc.Save(stream, true);
                fileContents = stream.ToArray();
            }
            return(new MemoryStream(fileContents));

            //using (var htmlStream = new MemoryStream(Encoding.UTF8.GetBytes(_htmlGenerator.GenerateHtml(contents, Descriptor.SupportedFileExtension))))
            //using (var tmpStream = new MemoryStream())
            //{
            //    htmlStream.CopyTo(tmpStream);

            //    var apiKey = _siteService.GetSiteSettings().As<DownloadAsPdfSettingsPart>().CloudConvertApiKey;

            //    var client = new RestClient("https://api.cloudconvert.org/");
            //    var request = new RestRequest("process");
            //    request.AddParameter("apikey", apiKey);
            //    request.AddParameter("inputformat", "html");
            //    request.AddParameter("outputformat", "pdf");
            //    request.AddParameter("converter", "unoconv");
            //    var response = client.Post<InitResponse>(request);
            //    var processUrl = response.Data.Url;
            //    if (response.StatusCode != HttpStatusCode.OK) throw new OrchardException(T("PDF generation failed as the CloudConvert API returned an error when trying to open the converion process. Status code: {0}. CloudConvert error message: {1}.", response.StatusCode, response.Data.Error));

            //    var processClient = new RestClient("https:" + processUrl);

            //    var uploadRequest = new RestRequest();
            //    uploadRequest.AddFile("file", tmpStream.ToArray(), "output.html");
            //    uploadRequest.AddParameter("input", "upload");
            //    uploadRequest.AddParameter("format", "pdf");
            //    var uploadResponse = processClient.Post(uploadRequest);
            //    if (uploadResponse.StatusCode != HttpStatusCode.OK) throw new OrchardException(T("PDF generation failed as the CloudConvert API returned an error when trying to upload the HTML file. Status code: {0}.", uploadResponse.StatusCode));

            //    var processResponse = processClient.Get<ProcessResponse>(new RestRequest());
            //    var tryCount = 0;
            //    while (processResponse.Data.Step != "finished" && tryCount < 20)
            //    {
            //        Thread.Sleep(2000); // Yes, doing this like this is bad. No better idea yet.
            //        processResponse = processClient.Get<ProcessResponse>(new RestRequest());
            //        tryCount++;
            //    }
            //    if (tryCount == 20) throw new OrchardException(T("PDF generation failed as CloudConvert didn't finish the conversion after 40s."));


            //    using (var wc = new WebClient())
            //    {
            //        var fileBytes = wc.DownloadData("https:" + processResponse.Data.Output.Url);
            //        return new MemoryStream(fileBytes);
            //    }
            //}
        }