private static Task WriteFileAsync(ActionContext context, FileContentResult result) { var response = context.HttpContext.Response; var bufferingFeature = response.HttpContext.Features.Get<IHttpBufferingFeature>(); bufferingFeature?.DisableResponseBuffering(); return response.Body.WriteAsync(result.FileContents, offset: 0, count: result.FileContents.Length); }
public void ConstructorSetsFileContentsProperty() { // Arrange byte[] fileContents = new byte[0]; // Act FileContentResult result = new FileContentResult(fileContents, "contentType"); // Assert Assert.Same(fileContents, result.FileContents); }
public FileContentResult ReadFileContent(string path) { FileContentResult result = new FileContentResult { IsContentRead = true }; try { result.Content = _fileSystem.ReadAllText(path); result.Name = _fileSystem.GetFileNameWithoutExtension(path); } catch (Exception) { result.IsContentRead = false; } return result; }
public FileContentResult DownloadOrganisationAddresses() { List <Organisation> organisationAddresses = dataRepository.GetAll <Organisation>() .Where(org => org.Status == OrganisationStatuses.Active) .Include(org => org.OrganisationAddresses) // This .ToList() materialises the collection (i.e. runs the SQL query) .ToList() // We only want organisations with valid addresses // The following filter only works in code (cannot be converted to SQL) so must be done after the first .ToList() .Where(org => org.GetLatestAddress() != null) .ToList(); var records = organisationAddresses.Select( org => { OrganisationAddress address = org.GetLatestAddress(); return(new { org.OrganisationId, org.OrganisationName, address.PoBox, address.Address1, address.Address2, address.Address3, address.TownCity, address.County, address.Country, address.PostCode, }); }) .ToList(); string fileDownloadName = $"Gpg-OrganisationAddresses-{VirtualDateTime.Now:yyyy-MM-dd HH:mm}.csv"; FileContentResult fileContentResult = DownloadHelper.CreateCsvDownload(records, fileDownloadName); return(fileContentResult); }
public async Task <IActionResult> Index() { await Playwright.InstallAsync(); using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(new LaunchOptions { Headless = true }); var page = await browser.NewPageAsync(); var htmlContent = await System.IO.File.ReadAllTextAsync("wwwroot/testPage.html"); await page.SetContentAsync(htmlContent, LifecycleEvent.Load); var headerTemplate = @"<!DOCTYPE html> <html> <head> <title>FooterTemplate</title> <style>bodye { font-size: 16px; color: lightblue;}</style> </head> <body> <div>Test header template</div> </body> </html>"; var bytesResponse = await page.GetPdfAsync(null, 1, true, headerTemplate, "<div>Test footer template</div>", true, false, "", null, null, null, new Margin { Bottom = "1in", Top = "2in" }, false); FileResult fileResult = new FileContentResult(bytesResponse, "application/pdf"); fileResult.FileDownloadName = "test.pdf"; return(fileResult); }
private Task DrawImageAsync(HttpContext httpContext, string text, string rndDate, string foreColor = "#1B0172", string backColor = "", float fontSize = 12, string fontName = "Tahoma") { if (string.IsNullOrWhiteSpace(text)) { httpContext.Response.StatusCode = 400; return(Task.CompletedTask); } var decryptedText = _captchaProtectionProvider.Decrypt(text); if (decryptedText == null) { httpContext.Response.StatusCode = 400; return(Task.CompletedTask); } byte[] image; try { image = _captchaImageProvider.DrawCaptcha(decryptedText, foreColor, backColor, fontSize, fontName); } catch (Exception ex) { _logger.LogCritical(1001, ex, "DrawCaptcha error."); httpContext.Response.StatusCode = 400; return(Task.CompletedTask); } FileContentResult result = new FileContentResult(_captchaImageProvider.DrawCaptcha(decryptedText, foreColor, backColor, fontSize, fontName), "image/png"); HttpResponse response = httpContext.Response; response.ContentType = result.ContentType; int length = result.FileContents.Length; response.ContentLength = length; response.StatusCode = 200; return(response.Body.WriteAsync(result.FileContents, 0, length)); }
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { string flipDirection = req.Query["direction"].ToString().ToLower(); if (flipDirection == "horizontal" || flipDirection == "vertical") { try { using (Image <Rgba32> img = Image.Load(new StreamReader(req.Body).BaseStream)) { var flipmode = flipDirection == "horizontal" ? FlipMode.Horizontal : FlipMode.Vertical; using (var img2 = img.Clone(ctx => ctx.Flip(flipmode))) { using (MemoryStream memoryStream = new MemoryStream()) { memoryStream.Position = 0; img2.SaveAsPng(memoryStream); var b = new FileContentResult(memoryStream.ToArray(), "image/png"); //var result = new OkObjectResult(System.Convert.ToBase64String(memoryStream.ToArray())); return((ActionResult)b); } } } } catch (Exception ex) { log.Error(ex.Message, ex); return((ActionResult) new BadRequestObjectResult("{\"error\" : \"Error processing image\"}")); } } else { return((ActionResult) new BadRequestObjectResult(new ErrorData("Invalid direction specified. 'direction' param must be vertical or horizontal.").ToJson)); } }
public async Task <IActionResult> Download(int id) { var bll_g = groupBusiness; var user = HttpContext.Items["EndUser"] as EF.EndUser; var res = from r in await groupCategoryBusiness.Members(id) join genders in (await lookUpBusiness.GetByGroup("Gender")).Select(x => new { Label = x.Name, Value = int.Parse(x.Value) }) on r.Gender equals genders.Value into e from e1 in e.DefaultIfEmpty() join civilStatuses in (await lookUpBusiness.GetByGroup("Civil Status")).Select(x => new { Label = x.Name, Value = int.Parse(x.Value) }) on r.CivilStatus equals civilStatuses.Value into f from f1 in f.DefaultIfEmpty() join m in memberBusiness.Find(new EF.Member { CommunityId = user.Member.CommunityId }) on r.InvitedBy equals m.Id into g from m1 in g.DefaultIfEmpty() select new { r.Id, r.Name, r.NickName, r.Address, r.Mobile, r.Email, r.BirthDate, r.Remarks, r.CivilStatus, r.Gender, InvitedByMemberName = m1 == null ? "" : m1.Name, r.IsActive }; var bytes = Encoding.ASCII.GetBytes(res.ToList().ExportToCsv().ToString()); var result = new FileContentResult(bytes, "text/csv"); result.FileDownloadName = "my-csv-file.csv"; return(result); }
public static FileContentResult GeneratePdf(TextReader reportDefinitionStream, Action <ReportDataSourceCollection> action, string fileName, object parameters = null) { var reportViewer = new ReportViewer(); reportViewer.LocalReport.LoadReportDefinition(reportDefinitionStream); reportDefinitionStream.Close(); reportViewer.LocalReport.EnableExternalImages = true; if (parameters != null) { reportViewer.LocalReport.SetParameters(parameters.ToReportParamenters()); } action(reportViewer.LocalReport.DataSources); reportViewer.LocalReport.Refresh(); Warning[] warnings; string[] streamids; string mimeType; string encoding; string filenameExtension; string deviceInfo = "<DeviceInfo>" + " <EmbedFonts>None</EmbedFonts>" + "</DeviceInfo>"; byte[] bytes = reportViewer.LocalReport.Render("PDF" /* PDF / EXCEL */, deviceInfo, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); var file = new FileContentResult(bytes, mimeType); file.FileDownloadName = $"{fileName}.pdf"; return(file); }
public FileResult Export(int dictionaryId) { var dictionary = DictionariesRepository.GetById(dictionaryId); if (dictionary.IsPublic) { AccessGuardian(Roles.AccessUser); } else { AccessGuardian(Roles.AccessUser, dictionary.UserId); } var stream = DataExchangeService.ExportDictionary(dictionaryId); /* * var result = new HttpResponseMessage(HttpStatusCode.OK) * { * Content = new ByteArrayContent(stream.ToArray()) * }; * result.Content.Headers.ContentDisposition = * new ContentDispositionHeaderValue("attachment") * { * FileName = $"slownik_{dictionaryId}_{DateTime.Today}.csv" * }; * result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); * * return result;*/ Context.Response.ContentType = "application/octet-stream"; var result = new FileContentResult(stream.ToArray(), "application/octet-stream") { FileDownloadName = $"eksport_slownik_{dictionaryId}_{DateTime.Now:dd-MM-yyyy}.csv" }; return(result); }
public async Task <ActionResult> OnGetAsync() { string imageId = RouteData.Values["imageId"].ToString(); ImageWithMetadata imageWithMetadata = await DataAccessLayer.Dal.LookupById <ImageWithMetadata>(ImageWithMetadata.GetMongoDbCollectionName(), imageId); if (imageWithMetadata == null) { return(RedirectToPage("./Error")); } Image image = await DataAccessLayer.Dal.LookupById <Image>("images", imageWithMetadata.ImageId); string contentType; switch (imageWithMetadata.Filetype) { case ImageFormat.GIF: contentType = "image/gif"; break; case ImageFormat.PNG: contentType = "image/png"; break; case ImageFormat.JPEG: case ImageFormat.Unknown: default: contentType = "image/jpeg"; break; } var result = new FileContentResult(image.Content, contentType); return(result); }
public async Task <ActionResult <StateDocumentModel> > GetSingleState(StateDocumentModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { ActivityStateDocument stateDocument = await _mediator.Send(new GetActivityStateQuery() { StateId = model.StateId, ActivityId = model.ActivityId, Agent = model.Agent, Registration = model.Registration }); if (stateDocument == null) { return(NotFound()); } if (HttpMethods.IsHead(Request.Method)) { return(NoContent()); } var content = new FileContentResult(stateDocument.Content, stateDocument.ContentType.ToString()); content.LastModified = stateDocument.LastModified; content.EntityTag = new Microsoft.Net.Http.Headers.EntityTagHeaderValue(stateDocument.Tag); return(content); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task<FileContentResult> GetHiRes(int id) { using (SAEONLogs.MethodCall(GetType(), new MethodCallParameters { { nameof(id), id } })) { try { var image = await dbContext.Images.FirstOrDefaultAsync(i => i.Id == id); //Guard.IsNotNull(image, nameof(image)); if (image == null) { throw new ArgumentOutOfRangeException(nameof(id)); } if (string.IsNullOrWhiteSpace(image.LinkHiRes)) { throw new ArgumentOutOfRangeException(nameof(image.LinkHiRes)); } var fileName = Path.Combine(environment.ContentRootPath, image.LinkHiRes.RemoveStartingBackSlash().RemoveStartingForwardSlash()); using (MemoryStream outStream = new MemoryStream()) using (var jpgImage = await SixLabors.ImageSharp.Image.LoadAsync(fileName)) { await jpgImage.SaveAsJpegAsync(outStream); var imageBytes = outStream.ToArray(); var result = new FileContentResult(imageBytes, MediaTypeNames.Image.Jpeg); var contentDisposition = new ContentDispositionHeaderValue("inline"); contentDisposition.FileName = Path.GetFileName(fileName); Response.Headers[HeaderNames.ContentDisposition] = contentDisposition.ToString(); await RequestLogger.LogAsync(dbContext, Request, $"{image.Name}|{image.Link}"); return result; } } catch (Exception ex) { SAEONLogs.Exception(ex); throw; } } }
public static async Task <FileContentResult> getChartImage(string accessToken) { FileContentResult returnValue = null; using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://graph.microsoft.com/testexcel/me/drive/items/" + fileId + "/workbook/worksheets('Summary')/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); string chartId = null; //Take the first chart off the charts collection, since we know there is only one HttpResponseMessage chartsResponse = await client.GetAsync("charts"); var responseContent = await chartsResponse.Content.ReadAsStringAsync(); var parsedResponse = JObject.Parse(responseContent); chartId = (string)parsedResponse["value"][0]["id"]; HttpResponseMessage response = await client.GetAsync("charts('" + chartId + "')/Image(width=0,height=0,fittingMode='fit')"); if (response.IsSuccessStatusCode) { string resultString = await response.Content.ReadAsStringAsync(); dynamic x = JsonConvert.DeserializeObject(resultString); JToken y = x.Last; Bitmap imageBitmap = StringToBitmap(x["value"].ToString()); ImageConverter converter = new ImageConverter(); byte[] bytes = (byte[])converter.ConvertTo(imageBitmap, typeof(byte[])); returnValue = new FileContentResult(bytes, "image/bmp"); } return(returnValue); } }
public FileContentResult Export() { //bikin file baru ExcelPackage pck = new ExcelPackage(); //sumber data List <Context.JnsTols> dbitems = RepoJnsTol.FindAll(); //bikin worksheet worksheet ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet 1"); //bikin header cell[baris,kolom] , nama kolom sesuaikan dengan template ws.Cells[1, 1].Value = "Nama Area"; ws.Cells[1, 2].Value = "Golongan 1"; ws.Cells[1, 3].Value = "Golongan 2"; ws.Cells[1, 4].Value = "Golongan 3"; ws.Cells[1, 5].Value = "Golongan 4"; ws.Cells[1, 6].Value = "Keterangan"; ws.Cells[1, 7].Value = "Id Database"; // Inserts Data for (int i = 0; i < dbitems.Count(); i++) { ws.Cells[i + 2, 1].Value = dbitems[i].NamaTol; ws.Cells[i + 2, 2].Value = dbitems[i].GolonganTol1; ws.Cells[i + 2, 3].Value = dbitems[i].GolonganTol2; ws.Cells[i + 2, 4].Value = dbitems[i].GolonganTol3; ws.Cells[i + 2, 5].Value = dbitems[i].GolonganTol4; ws.Cells[i + 2, 6].Value = dbitems[i].Keterangan; ws.Cells[i + 2, 7].Value = dbitems[i].Id; } var fsr = new FileContentResult(pck.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); fsr.FileDownloadName = "Jenis Tol.xls"; return(fsr); }
public FileContentResult Export() { //bikin file baru ExcelPackage pck = new ExcelPackage(); //sumber data List <Context.Atm> dbitems = RepoAtm.FindAll(); //bikin worksheet worksheet ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet 1"); //bikin header cell[baris,kolom] , nama kolom sesuaikan dengan template ws.Cells[1, 1].Value = "No Kartu"; ws.Cells[1, 2].Value = "Nama Bank"; ws.Cells[1, 3].Value = "No Rekening"; ws.Cells[1, 4].Value = "Atas Nama"; ws.Cells[1, 5].Value = "Driver"; ws.Cells[1, 6].Value = "Id Database"; // Inserts Data int idx = 0; for (int i = 0; i < dbitems.Count(); i++) { ws.Cells[i + 2, 1].Value = dbitems[i].NoKartu; ws.Cells[i + 2, 2].Value = dbitems[i].LookupCodeBank.Nama; ws.Cells[i + 2, 3].Value = dbitems[i].NoRekening; ws.Cells[i + 2, 4].Value = dbitems[i].AtasNama; ws.Cells[i + 2, 5].Value = dbitems[i].Driver.KodeDriver; ws.Cells[i + 2, 6].Value = dbitems[i].Id; } var fsr = new FileContentResult(pck.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); fsr.FileDownloadName = "Atm.xls"; return(fsr); }
public FileContentResult Export(string application, [FromUri] ApplicationMetadataSchemaKey key, [FromUri] PaginatedSearchRequestDto searchDTO, string module) { searchDTO.PageSize = searchDTO.TotalCount + 1; if (module != null) { _contextLookuper.LookupContext().Module = module; } var before = Stopwatch.StartNew(); var before2 = Stopwatch.StartNew(); var user = SecurityFacade.CurrentUser(); var applicationMetadata = MetadataProvider .Application(application) .ApplyPolicies(key, user, ClientPlatform.Web); var dataResponse = _dataController.Get(application, new DataRequestAdapter { Key = key, SearchDTO = searchDTO }); Log.Debug(LoggingUtil.BaseDurationMessageFormat(before, "finished gathering export excel data")); var excelBytes = _excelUtil.ConvertGridToExcel(user, applicationMetadata.Schema, ((ApplicationListResult)dataResponse).ResultObject); Log.Info(LoggingUtil.BaseDurationMessageFormat(before2, "finished export excel data")); var fileName = GetFileName(application, key.SchemaId) + ".xls"; var result = new FileContentResult(excelBytes, System.Net.Mime.MediaTypeNames.Application.Octet) { FileDownloadName = (string)StringUtil.FirstLetterToUpper(fileName) }; return(result); }
public async Task <IActionResult> IssueCertificate([FromRoute] string studentId) { var student = await Student.Get(studentId); if (student.CertIssued) { return(BadRequest("Certificate already issued")); } student.CertIssued = true; student.CertIssueDate = DateTime.Now.ToLongDateString(); var certificate = new Certificate($"{student.FirstName} {student.LastName}", student.Program, student.AvgGrade, student.CertIssueDate); using (var certificateStream = certificate.GenerateCert()) { await _mantleKeeper.KeeperFilesPostAsync(FolderId, certificateStream, student.Id, Accuracy); await student.Update(); FileResult fileResult = new FileContentResult(certificateStream.ToArray(), "image/png"); return(Ok(fileResult)); } }
public override void ExecuteResult(ControllerContext context) { using (var pck = new ExcelPackage()) { var ws = pck.Workbook.Worksheets.Add(WorksheetName); if (ColumnDefinitions == null) { ws.Cells["A1"].LoadFromCollection(_records, true, TableStyles.None); } else { ws.Cells["A1"].LoadFromCollection(_records, true, TableStyles.None, BindingFlags.Default, ColumnDefinitions.Select(x => x.MemberInfo).ToArray()); Format(ws, ColumnDefinitions); } const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; var fileContentResult = new FileContentResult(pck.GetAsByteArray(), contentType) { FileDownloadName = FileDownloadName }; fileContentResult.ExecuteResult(context); } }
public FileContentResult DownloadOrphanOrganisations() { DateTime pinExpiresDate = VirtualDateTime.Now.AddDays(0 - Global.PinInPostExpiryDays); List <Organisation> orphanOrganisations = dataRepository.GetAll <Organisation>() .Where(org => org.Status == OrganisationStatuses.Active) .Where(org => org.OrganisationScopes.OrderByDescending(s => s.SnapshotDate).FirstOrDefault(s => s.Status == ScopeRowStatuses.Active) == null || org.OrganisationScopes.OrderByDescending(s => s.SnapshotDate).FirstOrDefault(s => s.Status == ScopeRowStatuses.Active).ScopeStatus == ScopeStatuses.InScope || org.OrganisationScopes.OrderByDescending(s => s.SnapshotDate).FirstOrDefault(s => s.Status == ScopeRowStatuses.Active).ScopeStatus == ScopeStatuses.PresumedInScope) // We need the AsEnumerable here because EF gets upset about method calls - so we get the list at this point and then can filter it using a method call .AsEnumerable() .Where(org => org.UserOrganisations == null || !org.UserOrganisations.Any(uo => uo.HasBeenActivated() || // Registration complete uo.Method == RegistrationMethods.Manual || // Manual registration (uo.Method == RegistrationMethods.PinInPost && // PITP registration in progress uo.PINSentDate.HasValue && uo.PINSentDate.Value > pinExpiresDate))) .ToList(); var records = orphanOrganisations.Select( org => new { org.OrganisationId, org.OrganisationName, Address = org.GetLatestAddress()?.GetAddressString(), Sector = org.SectorType, ReportingDeadline = ReportingYearsHelper.GetDeadlineForAccountingDate(org.SectorType.GetAccountingStartDate()), }) .ToList(); string fileDownloadName = $"Gpg-OrphanOrganisations-{new GDSDateFormatter(VirtualDateTime.Now).FullStartDateTime}.csv"; FileContentResult fileContentResult = DownloadHelper.CreateCsvDownload(records, fileDownloadName); return(fileContentResult); }
public FileResult ExportGoCardless(List <int> ids) { var statements = statementService .GetCustomerStatementsByStatus(CustomerStatementStatus.PartiallyPaid, CustomerStatementStatus.SentToCustomer, CustomerStatementStatus.FailedPayment) .Where(x => x.Agreement.PaymentProvider == PaymentProvider.GoCardless && ids.Contains(x.ID)) .ToList(); var statementData = new DataTable("GoCardless Payments"); statementData.Columns.Add("Statement Ref"); statementData.Columns.Add("Statement Date"); statementData.Columns.Add("Payer ID"); statementData.Columns.Add("Payer Name"); statementData.Columns.Add("Amount").DataType = typeof(Decimal); statements.ForEach(statement => { var row = statementData.NewRow(); row["Statement Ref"] = statement.Reference; row["Statement Date"] = statement.StatementDate.ToShortDateString(); row["Payer ID"] = statement.PayerID.ToString(); row["Payer Name"] = statement.Agreement.Payer.FormattedName; row["Amount"] = statement.AmountOutstanding; statementData.Rows.Add(row); }); var documentContent = renderingService.RenderExcel(statementData); var mimeType = Utilities.GetMimeType(".xlsx"); var file = new FileContentResult(documentContent, mimeType) { FileDownloadName = "Export.xlsx" }; return(file); }
public ActionResult Contact() { ViewBag.Message = "Your contact page."; string wordContent = string.Empty; IView view = ViewEngines.Engines.FindPartialView(ControllerContext, "Index").View; using (var writer = new StringWriter()) { var viewContext = new ViewContext(ControllerContext, view, ViewData, TempData, writer); viewContext.View.Render(viewContext, writer); wordContent = writer.ToString(); writer.Close(); writer.Dispose(); } HtmlToPdf htmlToPdfConverter = new HtmlToPdf(); byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(wordContent, null); FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf"); fileResult.FileDownloadName = "index.pdf"; return(fileResult); return(View()); }
public async Task <ActionResult> GetFileById(int?id) { FileContentResult fileResult = null; if (id == null) { return(Redirect(this.Request.UrlReferrer?.AbsoluteUri ?? "/")); } try { var file = await this._fileManager.GetFileByIdAsync((int)id); string mimeType = MimeMapping.GetMimeMapping(file.FileType); fileResult = new FileContentResult(file.Content, mimeType); } catch (Exception) { return(Redirect(this.Request.UrlReferrer?.AbsoluteUri ?? "/")); } return(fileResult); }
public IActionResult get_pic(Int32 id, String random_stuff) { string path = get_letter(id).image_path; if (!System.IO.File.Exists(path)) { return(StatusCode(404, "File not found")); } byte[] data; try { data = System.IO.File.ReadAllBytes(path); } catch (Exception) { return(StatusCode(204, "File not found")); } var tmp = new FileContentResult(data, "application/octet-stream"); string[] splitted_path = path.Split(Path.DirectorySeparatorChar); tmp.FileDownloadName = splitted_path[splitted_path.Length - 1]; return(tmp); }
public async Task <ActionResult> CreatePageList(long cookieToReturn) { PageList sm = new PageList(); string list = await sm.CreateAsync(); #if MVC6 Response.Headers.Remove("Cookie"); Response.Cookies.Append(Basics.CookieDone, cookieToReturn.ToString(), new Microsoft.AspNetCore.Http.CookieOptions { HttpOnly = false, Path = "/" }); #else HttpCookie cookie = new HttpCookie(Basics.CookieDone, cookieToReturn.ToString()); Response.Cookies.Remove(Basics.CookieDone); Response.SetCookie(cookie); #endif string contentType = "application/octet-stream"; byte[] btes = Encoding.UTF8.GetBytes(list); FileContentResult result = new FileContentResult(btes, contentType); result.FileDownloadName = "FileList.txt"; return(result); }
private static FileResult GenerarReportePdfFileResult( string nombreReporte, string titulo, IEnumerable datos, Dictionary <string, string> parametrosAdicionales = null) { var reportViewer = new ReportViewer(); reportViewer.LocalReport.ReportPath = ObtenerPathReporte(nombreReporte); reportViewer.LocalReport.EnableExternalImages = true; reportViewer.LocalReport.DataSources.Add(new ReportDataSource("Datos", datos)); var parametros = new List <ReportParameter> { new ReportParameter("Titulo", titulo), new ReportParameter("ColorPrincipal", Configuracion.Configuracion.ColorPrincipal), new ReportParameter("LogoURL", Configuracion.Configuracion.LogoURL), new ReportParameter("MutualNombre", Configuracion.Configuracion.MutualNombre), new ReportParameter("MutualDireccion", Configuracion.Configuracion.MutualDireccion.Replace(@"\n", Environment.NewLine)) }; if (parametrosAdicionales != null) { foreach (var parametro in parametrosAdicionales) { parametros.Add(new ReportParameter(parametro.Key, parametro.Value)); } } reportViewer.LocalReport.SetParameters(parametros); var resultado = new FileContentResult(reportViewer.LocalReport.Render("PDF"), "application/pdf"); resultado.FileDownloadName = String.Format("{0}-{1:ddMMyyyyHHmm}.pdf", Formato.FormatoSlug(titulo), DateTime.Now); return(resultado); }
public ActionResult ConvertHtmlToPdf(IFormCollection collection) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Set the PDF file to be inserted before conversion result string pdfFileBefore = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/PDF_Files/Merge_Before_Conversion.pdf"; htmlToPdfConverter.PdfDocumentOptions.AddStartDocument(pdfFileBefore); // Set the PDF file to be added after conversion result string pdfFileAfter = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/PDF_Files/Merge_After_Conversion.pdf"; htmlToPdfConverter.PdfDocumentOptions.AddEndDocument(pdfFileAfter); // The URL to convert string url = collection["urlTextBox"]; // Convert the HTML page to a PDF document and add the external PDF documents byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); // Send the PDF file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Merge_HTML_with_Existing_PDF.pdf"; return(fileResult); }
public static IActionResult ToHttpResponseMessage(FlatReportDto flatReport) { using (var stringWriter = new StringWriter()) { stringWriter.NewLine = "\r\n"; if (flatReport != null) { stringWriter.WriteLine(string.Join <string>(",", new[] { "DeviceId", "Name", "Time", }.Union(flatReport.Properties.Select(Escaped)))); var properties = flatReport.Properties; int propertyCount = properties.Count(); foreach (var row in flatReport.Rows) { var valueLine = Escaped(row.DeviceId) + "," + Escaped(row.Name) + "," + Escaped(row.Timestamp.ToString(CultureInfo.InvariantCulture)) + (propertyCount > 0 ? "," : ""); for (var p = 0; p < propertyCount; p++) { var prop = properties[p]; var field = row.Fields.SingleOrDefault(f => f.Key == prop); var escaped = Escaped(field != null ? field.Value : null); valueLine = string.Concat(valueLine, escaped, p < propertyCount - 1 ? "," : ""); } stringWriter.WriteLine(valueLine); } } var fileContentResult = new FileContentResult(Encoding.UTF8.GetBytes(stringWriter.ToString()), "text/csv"); fileContentResult.FileDownloadName = "telemetry.csv"; return(fileContentResult); } }
public ActionResult SubmitAction(FormCollection collection) { // instantiate a html to pdf converter object HtmlToPdf converter = new HtmlToPdf(); // set css media type converter.Options.CssMediaType = (HtmlToPdfCssMediaType)Enum.Parse( typeof(HtmlToPdfCssMediaType), collection["DdlCssMediaType"], true); // create a new pdf document converting an url PdfDocument doc = converter.ConvertUrl(collection["TxtUrl"]); // save pdf document byte[] pdf = doc.Save(); // close pdf document doc.Close(); // return resulted pdf document FileResult fileResult = new FileContentResult(pdf, "application/pdf"); fileResult.FileDownloadName = "Document.pdf"; return(fileResult); }
public async Task <ActionResult> DownloadFile(int id, string fileType) { var filePaymentType = ""; if (fileType == "atm") { filePaymentType = PaymentTypeConst.ATM; } if (fileType == "bank") { filePaymentType = PaymentTypeConst.Bank; } if (fileType == "order") { filePaymentType = PaymentTypeConst.PaymentOrder; } if (fileType == "personalpost") { filePaymentType = PaymentTypeConst.PersonalPost; } if (fileType == "post") { filePaymentType = PaymentTypeConst.InternalPost; } var result = await DownloadFileMethod(id, filePaymentType); // var file = File (result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "PrintTemplate"); var s = new FileContentResult(await System.IO.File.ReadAllBytesAsync(result), new MediaTypeHeaderValue("application/xls").MediaType) { FileDownloadName = "Report.xls" }; return(s); }
public ActionResult TestRamsellXMLExport(int?formResultId = null) { // find an ADAP assessment to export if (formResultId == null) { int formId = formsRepo.GetFormByIdentifier("ADAP").formId; formResultId = formsRepo.GetFormResultsByFormId(formId).First().formResultId; } Debug.WriteLine("* * * TestRamsellXmlExport formResultId: " + formResultId.ToString()); XmlDocument outputXmlDoc = RamsellExport.BuildRamsellXmlDocForFormResult(formResultId.Value, formsRepo); // stream result xml with line breaks and indents StringBuilder sbOut = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sbOut, Utilities.xmlWriterSettings)) { outputXmlDoc.Save(writer); } FileContentResult fcr = File(Encoding.ASCII.GetBytes(sbOut.ToString()), "text/plain", "result.xml"); return(fcr); }
public ActionResult ConvertThisPageToPdf(string page) { // get the HTML code of this view // the base URL to resolve relative images and css String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri; String baseUrl = thisPageUrl.Substring(0, thisPageUrl.Length - "Evaluations/ConvertThisPageToPdf".Length); //// instantiate the HiQPdf HTML to PDF converter //HtmlToPdf htmlToPdfConverter = new HtmlToPdf(); //// hide the button in the created PDF //htmlToPdfConverter.HiddenHtmlElements = new string[] { "#convertThisPageButtonDiv" }; //// render the HTML code as PDF in memory //byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl); // send the PDF file to browser FileResult fileResult = new FileContentResult(new byte[0], "application/pdf"); fileResult.FileDownloadName = "ThisMvcViewToPdf.pdf"; return(fileResult); }
//controller function to generate image //returns image file (through url.action in img src attribute) public ActionResult GetCaptcha(string prefix, bool noisy = true) { var rand = new Random((int)DateTime.Now.Ticks); //generate new question int a = rand.Next(10, 99); int b = rand.Next(0, 9); var captcha = string.Format("{0} + {1} = ?", a, b); //store answer Session["Captcha" + prefix] = a + b; //image stream FileContentResult img = null; try { img = this.File(CaptchaHelper.GenerateCaptchaImg(captcha, true), "image/Jpeg"); } catch { } return(img); }
public static FileContentResult Create(byte[] data, string downloadName) { var result = new FileContentResult(data, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); result.FileDownloadName = downloadName ?? ("report" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"); return result; }
public Task ExecuteAsync(ActionContext context, FileContentResult result) { SetHeadersAndLog(context, result); return WriteFileAsync(context, result); }