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(); }; }
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; })); }
/// <summary> /// Convert Html page at a given URL to a PDF file using open-source tool wkhtml2pdf /// </summary> // ReSharper disable once InconsistentNaming public static void ConvertURLToPDF(Uri url, FileInfo outputFile, PdfConversionSettings settings) { Check.RequireNotNull(settings); var exeInfo = new FileInfo(SitkaConfiguration.GetRequiredAppSetting(settings.AppKeyExecPath)); Check.RequireFileExists(exeInfo); Check.RequireDirectoryExists(outputFile.DirectoryName); var commandLineArguments = settings.BuildCommandSwitches(); commandLineArguments.Add(url.ToString()); commandLineArguments.Add(outputFile.FullName); var result = ProcessUtility.ShellAndWaitImpl(exeInfo.DirectoryName, exeInfo.FullName, commandLineArguments, true, Convert.ToInt32(settings.ExecutionTimeout.TotalMilliseconds)); var retCode = result.ReturnCode; var argumentsAsString = String.Join(" ", commandLineArguments.Select(ProcessUtility.EncodeArgumentForCommandLine).ToList()); var fullProcessAndArguments = $"{ProcessUtility.EncodeArgumentForCommandLine(exeInfo.FullName)} {argumentsAsString}"; Check.Ensure(retCode == 0, $"Process {exeInfo.Name} returned with exit code {retCode}, expected exit code 0.\r\nProcess Command Line:\r\n{fullProcessAndArguments}\r\nProcess Working Directory: {exeInfo.DirectoryName}\r\nStdErr and StdOut:\r\n{result.StdOutAndStdErr}"); }
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(); }; }
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(); }; }
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 }); }
/// <summary> /// Convert Html page at a given URL to a PDF file using open-source tool wkhtml2pdf /// </summary> // ReSharper disable once InconsistentNaming public static byte[] ConvertURLToByteArray(Uri url, PdfConversionSettings settings) { var tempFolder = new DirectoryInfo(SitkaConfiguration.GetRequiredAppSetting("TempFolder")); Check.RequireDirectoryExists(tempFolder); var tempFile = new FileInfo($"{tempFolder.FullName}\\{Guid.NewGuid()}.pdf"); ConvertURLToPDF(url, tempFile, settings); using (var fs = new FileStream(tempFile.FullName, FileMode.Open, FileAccess.Read)) { var result = new byte[fs.Length]; fs.Read(result, 0, result.Length); fs.Close(); tempFile.Delete(); return(result); } }
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(); }; }
/// <summary> /// Initializes a new instance of the <see cref="ConvertToPdfRequest"/> class. /// </summary> /// <param name="settings">The settings.</param> /// <param name="outPath">outPath: path to output document on file storage</param> public ConvertToPdfRequest(PdfConversionSettings settings = null, string outPath = null) { this.Settings = settings; this.OutPath = outPath; }
/// <summary> /// Initializes a new instance of the <see cref="ConvertToPdfStreamRequest"/> class. /// </summary> /// <param name="settings">The settings.</param> public ConvertToPdfStreamRequest(PdfConversionSettings settings = null) { this.Settings = settings; }
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 })); }