Ejemplo n.º 1
0
        public async Task <string> ConvertToPdfAsync(string content)
        {
            return(await Task.Run(() =>
            {
                var headerUrl = $@"{_hostingEnvironment.ContentRootPath}\Reports\Default\header.html";

                var footerUrl = $@"{_hostingEnvironment.ContentRootPath}\Reports\Default\footer.html";
                var config = new PdfConversionSettings
                {
                    Title = "Workflow auto-generated report",
                    Content = content,
                    PageHeaderUrl = headerUrl,
                    PageFooterUrl = footerUrl,
                    Margins = new PdfPageMargins {
                        Left = 10, Top = 17 + 20, Right = 10, Bottom = 20
                    },
                    OutputPath = $@"{_hostingEnvironment.ContentRootPath}\Reports\AutoGeneratedReport\{Guid.NewGuid()}.pdf",
                    CustomWkHtmlHeaderArgs = "--header-spacing 10",
                    CustomWkHtmlFooterArgs = "--footer-spacing 10",
                    PdfToolPath = $@"{_hostingEnvironment.ContentRootPath}\Utilities\wkhtmltopdf.exe"
                };

                PdfConvert.Convert(config);

                return config.OutputPath;
            }));
        }
Ejemplo n.º 2
0
        void Test_Sample3()
        {
            context["Sample 3: Use Input and Output Streams"] = () =>
            {
                beforeEach = () =>
                {
                    PdfConversionSettings config = new PdfConversionSettings
                    {
                        Title = "Streaming my HTML to PDF"
                    };

                    using (var fileStream = new FileStream(@"C:\temp\sample3.pdf", FileMode.Create))
                    {
                        var task = new System.Net.Http.HttpClient().GetStreamAsync("http://www.google.com");
                        task.Wait();

                        using (var inputStream = task.Result)
                        {
                            PdfConvert.Convert(config, fileStream, inputStream);
                        }
                    }
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample3.pdf").ShouldBeTrue();
            };
        }
Ejemplo n.º 3
0
        void Test_Sample4()
        {
            context["Sample 4: Output Streams and Specify URL for Input and Cover with Table of Contents"] = () =>
            {
                beforeEach = () =>
                {
                    PdfConversionSettings config = new PdfConversionSettings
                    {
                        Title          = "A little bit of Everything",
                        GenerateToc    = true,
                        TocHeaderText  = "Table of MY Contents",
                        PageCoverUrl   = "https://www.google.com/?q=cover%20page",
                        ContentUrl     = "https://www.google.com/?q=content%20page",
                        PageHeaderHtml = @"
        <!DOCTYPE html>
        <html><body>
        <div style=""background-color: red; color: white; text-align: center; width: 100vw;"">SECRET SAUCE</div>
        </body></html>"
                    };

                    using (var fileStream = new FileStream(@"C:\temp\sample4.pdf", FileMode.Create))
                    {
                        PdfConvert.Convert(config, fileStream);
                    }
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample4.pdf").ShouldBeTrue();
            };
        }
Ejemplo n.º 4
0
        void Test_Sample5()
        {
            context["Sample 5: Static Cover, Header, Footer, and Content"] = () =>
            {
                beforeEach = () =>
                {
                    PdfConvert.Convert(new PdfConversionSettings
                    {
                        Title          = "My Static Content",
                        PageCoverHtml  = @"<!DOCTYPE html>
<html>
<head></head>
<body>
<div style=""height: 100vh; text-align: center;""><h1>Cover Page</h1></div>
</body></html>",
                        PageHeaderHtml = @"<!DOCTYPE html>
<html>
<head></head>
<body>
<h5>HEADER</h5>
</body></html>",
                        PageFooterHtml = @"<!DOCTYPE html>
<html>
<head></head>
<body>
<h5>FOOTER</h5>
</body></html>",
                        Content        = @"<h1>Lorem ipsum dolor sit amet consectetuer adipiscing elit I SHOULD BE RED BY JAVASCRIPT</h1><script>document.querySelector('h1').style.color = 'rgb(128,0,0)';</script>",
                        OutputPath     = @"C:\temp\sample5.pdf"
                    });
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample5.pdf").ShouldBeTrue();
            };
        }
Ejemplo n.º 5
0
        //generate PDF from HTML - thanks wkhtmltopdf and the shark.pdfconvert C# wapper
        private void generatePDF(string out_folder, string html_stream, string pdf_out, string error_file)
        {
            System.IO.Directory.CreateDirectory(out_folder);

            try
            {
                PdfConvert.Convert(new PdfConversionSettings
                {
                    Title      = "My Static Content",
                    Content    = html_stream,
                    OutputPath = pdf_out
                });
            }
            catch (Exception ex)
            {
                //File.AppendAllText(log_file, ex);
                using (StreamWriter writer = new StreamWriter(error_file, true))
                {
                    writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                                     "" + Environment.NewLine + "Date :" + DateTime.Now.ToString() + Environment.NewLine + pdf_out);
                    writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
                }
                Exception_Count++;
                PropertyChanged(this, new PropertyChangedEventArgs("Exception_Count"));
            }
        }
Ejemplo n.º 6
0
        public async Task <FileContentResult> GeneratePDFAsync()
        {
            //nuget install - Shark.PdfConvert ver 1.0.3
            //Note: https://github.com/cp79shark/Shark.PdfConvert
            //install https://wkhtmltopdf.org/downloads.html
            //https://www.c-sharpcorner.com/article/Asp-Net-mvc-file-upload-and-download/
            // and install Microsoft.Net.Http.Headers from nuget package , if the running project is class library like this.


            PdfConversionSettings config = new PdfConversionSettings
            {
                Title   = "My Static Content",
                Size    = PdfPageSize.A4,
                Content = @"<h3>PDf generated from dot net core!!!</h3>
		                <script>document.querySelector('h1').style.color = 'rgb(128,0,0)';</script>"
                          //   OutputPath = @"C:\GeneratedPDF\test.pdf"
            };
            var memoryStream = new MemoryStream();

            await Task.Run(() => PdfConvert.Convert(config, memoryStream));

            var fileName = "myfileName.pdf";
            var mimeType = "application/pdf";

            return(new FileContentResult(memoryStream.ToArray(), mimeType)
            {
                FileDownloadName = fileName
            });
        }
Ejemplo n.º 7
0
        void Given_a_sample_conversion_settings_with_streamed_content_and_output()
        {
            context["When performing the PDF Conversion of the provided HTML from and to a stream"] = () =>
            {
                beforeEach = () =>
                {
                    PdfConversionSettings config = new PdfConversionSettings
                    {
                        Title = "Streaming my HTML to PDF"
                    };

                    using (var fileStream = new FileStream(@"C:\temp\www.google.com.pdf", FileMode.Create))
                    {
                        var task = new System.Net.Http.HttpClient().GetStreamAsync("http://www.google.com");
                        task.Wait();

                        using (var inputStream = task.Result)
                        {
                            PdfConvert.Convert(config, fileStream, inputStream);
                        }
                    }
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\www.google.com.pdf").ShouldBeTrue();
            };
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var templateFile     = File.ReadAllText($"{currentDirectory}/basetemplate.html");
            var pets             = new List <Pet>
            {
                new Pet
                {
                    Name = "Kira"
                },
                new Pet
                {
                    Name = "Kaiser"
                },
                new Pet
                {
                    Name = "Keitty"
                }
            };
            var template = Template.Parse(templateFile);
            var result   = template.Render(new { Pets = pets }).ToString();

            PdfConvert.Convert(new PdfConversionSettings
            {
                Title      = "My Static Content",
                Content    = result,
                OutputPath = @"E:\Desktop\temp.pdf"
            });
            Console.WriteLine(result);
        }
Ejemplo n.º 9
0
        void Given_a_sample_conversion_settings_with_http_based_content()
        {
            context["When performing the PDF Conversion of the provided HTML from http://www.lipsum.com"] = () =>
            {
                beforeEach = () =>
                {
                    PdfConvert.Convert(new PdfConversionSettings
                    {
                        Title      = "My Static Content from URL",
                        ContentUrl = "http://www.lipsum.com/",
                        OutputPath = @"C:\temp\temp-url.pdf"
                    });
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\temp-url.pdf").ShouldBeTrue();
            };
        }
Ejemplo n.º 10
0
        void Given_a_sample_conversion_settings_with_static_content()
        {
            context["When performing the PDF Conversion of the provided HTML"] = () =>
            {
                beforeEach = () =>
                {
                    PdfConvert.Convert(new PdfConversionSettings
                    {
                        Title      = "My Static Content",
                        Content    = @"<h1>Lorem ipsum dolor sit amet consectetuer adipiscing elit I SHOULD BE RED BY JAVASCRIPT</h1><script>document.querySelector('h1').style.color = 'rgb(128,0,0)';</script>",
                        OutputPath = @"C:\temp\temp.pdf"
                    });
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\temp.pdf").ShouldBeTrue();
            };
        }
Ejemplo n.º 11
0
        void Test_Sample2()
        {
            context["Sample 2: HTML from URL"] = () =>
            {
                beforeEach = () =>
                {
                    PdfConvert.Convert(new PdfConversionSettings
                    {
                        Title      = "My Static Content",
                        Content    = @"<h1>Lorem ipsum dolor sit amet consectetuer adipiscing elit 
	    I SHOULD BE RED BY JAVASCRIPT</h1>
		<script>document.querySelector('h1').style.color = 'rgb(128,0,0)';</script>"        ,
                        OutputPath = @"C:\temp\sample2.pdf"
                    });
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample2.pdf").ShouldBeTrue();
            };
        }
Ejemplo n.º 12
0
        public bool HTMLToPDF()
        {
            bool res = false;

            try
            {
                PdfConvert.Convert(new PdfConversionSettings
                {
                    Title      = "My Static Content from URL",
                    ContentUrl = "C:/Users/lsamaniego/Documents/Sprint Backlog.html",
                    OutputPath = @"C:/Users/lsamaniego/Documents/aaa.pdf"
                });
            }
            catch (Exception ex)
            {
                throw;
            }
            return(res);
        }
Ejemplo n.º 13
0
        void Test_Sample6()
        {
            context["Sample 6: Multiple Content URLs"] = () =>
            {
                beforeEach = () =>
                {
                    var settings = new PdfConversionSettings
                    {
                        Title      = "My Static Content from URL",
                        OutputPath = @"C:\temp\sample6.pdf"
                    };

                    settings.ContentUrls.Add("https://www.google.com");
                    settings.ContentUrls.Add("https://www.google.com/?q=another");

                    PdfConvert.Convert(settings);
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample6.pdf").ShouldBeTrue();
            };
        }
Ejemplo n.º 14
0
        void Test_Sample7()
        {
            context["Sample 7: Altering Zoom and Page Size"] = () =>
            {
                beforeEach = () =>
                {
                    PdfConvert.Convert(new PdfConversionSettings
                    {
                        Title      = "Converted by Shark.PdfConvert",
                        LowQuality = false,
                        Margins    = new PdfPageMargins()
                        {
                            Bottom = 10, Left = 10, Right = 10, Top = 10
                        },
                        Size       = PdfPageSize.A3,
                        Zoom       = 3.2f,
                        Content    = @"<h1>Lorem ipsum dolor sit amet consectetuer adipiscing elit I SHOULD BE RED BY JAVASCRIPT</h1><script>document.querySelector('h1').style.color = 'rgb(128,0,0)';</script>",
                        OutputPath = @"C:\temp\sample7.pdf"
                    });
                };

                it["Should have created a PDF document in the Temp folder"] = () => File.Exists(@"C:\temp\sample7.pdf").ShouldBeTrue();
            };
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Attempting to create a PDF using Shark.PdfConvert");
            Console.WriteLine("What is the name for your pdf?");
            string fileName = Console.ReadLine();
            string filePath = @"t:\temp\" + fileName + ".pdf";

            Console.WriteLine("Enter the text for the paragraph tag");
            string paragraphText = Console.ReadLine();

            Console.WriteLine("Enter the text for the h1 tag");
            string h1Text = Console.ReadLine();

            string content = @"<!DOCTYPE html><html><body><h1>" + h1Text +
                             @"</h1><p>" + paragraphText + @"</p></body></html>";

            try
            {
                PdfConvert.Convert(new Shark.PdfConvert.PdfConversionSettings
                {
                    Title      = "My First Attempt At Using Shark.PdfConvert",
                    Content    = content,
                    OutputPath = filePath
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                // throw;
            }



            Console.WriteLine("Converted successfully and PDF is at " + filePath);
            Console.ReadLine();
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> Filtered(List model, string query, string export, string nickname, bool employer, bool grad, bool abitur, bool student, bool employee, bool neutral, bool negative, bool positive, bool uncertain, string data1, string data2, string key)
        {
            ViewBag.Logout    = "Выйти";
            ViewBag.Us        = "Пользователи";
            ViewBag.Uns       = "Университеты";
            ViewBag.Negative  = "Отрицательные";
            ViewBag.Neutral   = "Нейтральные";
            ViewBag.Positive  = "Положительные";
            ViewBag.Undefined = "Неопределённые";
            ViewBag.Export    = "Сохранить";
            ViewBag.Startover = "Начать заново";
            ViewBag.Filters   = "Фильтры";
            ViewBag.Target    = "Целевая аудитория";
            ViewBag.Emp1      = "Работники";
            ViewBag.Emp2      = "Работодатели";
            ViewBag.Stu       = "Студенты";
            ViewBag.Ab        = "Абитуриенты";
            ViewBag.Grad      = "Выпускники";
            ViewBag.Nick      = "Имя пользователя";
            ViewBag.Em        = "Эмоциональная окраска";
            ViewBag.Key       = "Ключевые слова";
            ViewBag.Time      = "Временной промежуток";
            ViewBag.From      = "От";
            ViewBag.To        = "До";
            ViewBag.Accept    = "Принять";


            if (export != null)
            {
                export = this.parsingService.getstr(export);
                var res = "<!DOCTYPE html> <html lang=\"ru\"> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/> </head> " + "<div class=\"bg-blue\">";
                res += "<div>" + model.Query + "</div>";
                res += "<div> Целевая аудитория:";
                if (model.employee)
                {
                    res += "Работники ";
                }
                if (model.student && model.employee)
                {
                    res += ",Студенты ";
                }
                else if (student)
                {
                    res += "Students ";
                }
                if (abitur && (student || employee))
                {
                    res += ",Абитуриенты ";
                }
                else if (abitur)
                {
                    res += "Abiturients ";
                }
                if (grad && (abitur || student || employee))
                {
                    res += ",Выпускники ";
                }
                else if (grad)
                {
                    res += "Graduates ";
                }
                if (employer && (grad || abitur || student || employee))
                {
                    res += ",Работодатели ";
                }
                else if (employer)
                {
                    res += "Работодатели ";
                }
                res += "</div>";
                res += "<div> Эмоциональная окраска:";

                if (positive)
                {
                    res += "Положительные  ";
                }
                if (negative && positive)
                {
                    res += ",Отрицательные  ";
                }
                else if (negative)
                {
                    res += "Отрицательные  ";
                }
                if (neutral && (negative || positive))
                {
                    res += ",Нейтральные  ";
                }
                else if (neutral)
                {
                    res += "Нейтральные  ";
                }
                if (uncertain && (neutral || negative || positive))
                {
                    res += ",Неопределённые  ";
                }
                else if (uncertain)
                {
                    res += "Неопределённые  ";
                }
                res += "</div>";


                res += "<div> Ключевые слова - " + key + "</div>";

                if (data1 != "01.01.0001")
                {
                    res += "<div> От - " + data1 + " До - " + data2 + "</div>";
                }


                res += export + "</div></html>";

                var convertSettings = new PdfConversionSettings()
                {
                    PdfToolPath = Path.Combine(Directory.GetCurrentDirectory(),
                                               "wkhtmltopdf.exe"),
                    Title   = "Salg",
                    Content = res
                };
                using (var memoryStream = new MemoryStream())
                {
                    PdfConvert.Convert(convertSettings, memoryStream);
                    return(File(memoryStream.ToArray(), "application/pdf"));
                }
            }



            int         Count         = 0;
            double      vkc           = 0;
            double      gazetac       = 0;
            double      vestic        = 0;
            double      profc         = 0;
            double      regnumc       = 0;
            double      riac          = 0;
            double      twitc         = 0;
            double      newsc         = 0;
            double      positivec     = 0;
            double      negativec     = 0;
            double      neutralc      = 0;
            double      uncertainc    = 0;
            List <Post> Filt          = new List <Post>();
            var         Poststofilter = await this.context.Posts.ToListAsync();

            foreach (var item in Poststofilter)
            {
                if (model.positive || model.negative || model.neutral || model.uncertain)
                {
                    switch (item.emo)
                    {
                    case 0:
                        if (!model.positive)
                        {
                            item.pass = false;
                        }
                        break;

                    case 1:
                        if (!model.negative)
                        {
                            item.pass = false;
                        }
                        break;

                    case 2:
                        if (!model.neutral)
                        {
                            item.pass = false;
                        }
                        break;

                    case 3:
                        if (!model.uncertain)
                        {
                            item.pass = false;
                        }
                        break;
                    }
                }

                if (!item.source.Equals("regnum") && model.data1 >= DateTime.Now.AddDays(-21) && model.data2 <= DateTime.Now)
                {
                    if (DateTime.Parse(item.date) < model.data1 || DateTime.Parse(item.date) > model.data2)
                    {
                        item.pass = false;
                    }
                }
                if (model.nickname != null)
                {
                    if (string.Compare(item.ownersName, model.nickname) != 0)
                    {
                        item.pass = false;
                    }
                }
                if (model.key != null)
                {
                    if (!item.text.Contains(model.key))
                    {
                        item.pass = false;
                    }
                }
                List <string> check = new List <string>();
                if (model.abitur)
                {
                    check.Add("vk"); check.Add("prof");
                }
                if (model.student)
                {
                    check.Add("vk");
                }
                if (model.employee)
                {
                    check.Add("regnum"); check.Add("vesti");
                }
                if (model.employer)
                {
                    check.Add("regnum"); check.Add("vesti"); check.Add("vk"); check.Add("prof"); check.Add("gazeta");
                }
                if (model.grad)
                {
                    check.Add("regnum"); check.Add("vesti"); check.Add("vk"); check.Add("prof");
                }
                if (!check.Contains(item.source) && check.Count > 0)
                {
                    item.pass = false;
                }



                if (item.pass)
                {
                    Count++;

                    switch (item.source)
                    {
                    case "vk":
                        vkc++;
                        break;

                    case "gazeta":
                        gazetac++;
                        break;

                    case "vesti":
                        vestic++;
                        break;

                    case "prof":
                        profc++;
                        break;

                    case "regnum":
                        regnumc++;
                        break;

                    case "news.ru":
                        newsc++;
                        break;

                    case "twitter":
                        twitc++;
                        break;

                    case "ria":
                        riac++;
                        break;
                    }
                    switch (item.emo)
                    {
                    case 0:
                        positivec++;
                        break;

                    case 1:
                        negativec++;
                        break;

                    case 2:
                        neutralc++;
                        break;

                    case 3:
                        uncertainc++;
                        break;
                    }
                    Filt.Add(item);
                }
            }
            this.ViewBag.vkc        = vkc;
            this.ViewBag.newsc      = newsc;
            this.ViewBag.riac       = riac;
            this.ViewBag.twitc      = twitc;
            this.ViewBag.gazetac    = gazetac;
            this.ViewBag.vestic     = vestic;
            this.ViewBag.profc      = profc;
            this.ViewBag.regnumc    = regnumc;
            this.ViewBag.positivec  = positivec;
            this.ViewBag.negativec  = negativec;
            this.ViewBag.neutralc   = neutralc;
            this.ViewBag.uncertainc = uncertainc;
            if (vkc > 0)
            {
                ViewBag.vkp = (int)(vkc / Count * 100);
            }
            else
            {
                ViewBag.vkp = 0;
            }
            if (riac > 0)
            {
                ViewBag.riap = (int)(riac / Count * 100);
            }
            else
            {
                ViewBag.riap = 0;
            }
            if (newsc > 0)
            {
                ViewBag.newsp = (int)(newsc / Count * 100);
            }
            else
            {
                ViewBag.newsp = 0;
            }
            if (twitc > 0)
            {
                ViewBag.twitp = (int)(twitc / Count * 100);
            }
            else
            {
                ViewBag.twitp = 0;
            }
            if (gazetac > 0)
            {
                ViewBag.gazetap = (int)(gazetac / Count * 100);
            }
            else
            {
                ViewBag.gazetap = 0;
            }
            if (vestic > 0)
            {
                ViewBag.vestip = (int)(vestic / Count * 100);
            }
            else
            {
                ViewBag.vestip = 0;
            }
            if (profc > 0)
            {
                ViewBag.profp = (int)(profc / Count * 100);
            }
            else
            {
                ViewBag.profp = 0;
            }
            if (regnumc > 0)
            {
                ViewBag.regnump = (int)(regnumc / Count * 100);
            }
            else
            {
                ViewBag.regnump = 0;
            }
            if (positivec > 0)
            {
                ViewBag.positivep = (int)(positivec / Count * 100);
            }
            else
            {
                ViewBag.positivep = 0;
            }
            if (negativec > 0)
            {
                ViewBag.negativep = (int)(negativec / Count * 100);
            }
            else
            {
                ViewBag.negativep = 0;
            }
            if (neutralc > 0)
            {
                ViewBag.neutralp = (int)(neutralc / Count * 100);
            }
            else
            {
                ViewBag.neutralp = 0;
            }
            if (uncertainc > 0)
            {
                ViewBag.uncertainp = (int)(uncertainc / Count * 100);
            }
            else
            {
                ViewBag.uncertainp = 0;
            }

            return(this.View("List", new List
            {
                filtered = true,
                employee = model.employee,
                student = model.student,
                abitur = model.abitur,
                employer = model.employer,
                grad = model.grad,
                nickname = model.nickname,
                key = key,
                positive = model.positive,
                negative = model.negative,
                neutral = model.neutral,
                uncertain = model.uncertain,
                data1 = model.data1,
                data2 = model.data2,
                Posts = (ICollection <Post>)Filt,
                Query = model.Query
            }));
        }