public void ConstructorSetsFileStreamProperty() { // Arrange Stream stream = new MemoryStream(); // Act FileStreamResult result = new FileStreamResult(stream, "contentType"); // Assert Assert.Same(stream, result.FileStream); }
private static async Task WriteFileAsync(ActionContext context, FileStreamResult result) { var response = context.HttpContext.Response; var outputStream = response.Body; using (result.FileStream) { var bufferingFeature = response.HttpContext.Features.Get<IHttpBufferingFeature>(); bufferingFeature?.DisableResponseBuffering(); await result.FileStream.CopyToAsync(outputStream, BufferSize); } }
public FileStreamResult ExportFormJSON() { //use session variables to pick a FormResults object from the database string formId = Request["formId"] as string; Debug.WriteLine("* * * GetFormResultsJSON formId: " + formId); int iFormId = Convert.ToInt32(formId); formsEntities db = DataContext.GetDbContext(); db.Configuration.LazyLoadingEnabled = false; // def_Forms form = db.def_Forms // .Include(fr => fr.def_FormParts // .Select(fp => fp.def_Parts) // .Select(pa => pa.def_PartSections // .Select(p => p.def_Sections) // .Select(s => s.def_SectionItems // .Select(si => si.def_SubSections)))) // .Include(fr => fr.def_FormParts // .Select(fp => fp.def_Parts) // .Select(pa => pa.def_PartSections // .Select(p => p.def_Sections) // .Select(s => s.def_SectionItems // .Select(si => si.def_Items) // .Select(i => i.def_ItemVariables)))) // .Single(f => f.formId == iFormId); def_Forms form = db.def_Forms.Where(f => f.formId == iFormId).FirstOrDefault(); List <def_FormParts> formParts = db.def_FormParts.Where(fp => fp.formId == iFormId).ToList(); List <int> partIds = formParts.Select(fp => fp.partId).ToList(); List <def_Parts> parts = db.def_Parts.Where(p => partIds.Contains(p.partId)).ToList(); partIds = parts.Select(p => p.partId).ToList(); List <def_PartSections> partSections = db.def_PartSections.Where(ps => partIds.Contains(ps.partId)).ToList(); List <int> sectionIds = partSections.Select(ps => ps.sectionId).ToList(); List <def_Sections> sections = db.def_Sections.Where(s => sectionIds.Contains(s.sectionId)).ToList(); List <def_SectionItems> sectionItems = new List <def_SectionItems>(); List <def_SubSections> subSections = new List <def_SubSections>(); List <def_Items> items = new List <def_Items>(); List <def_ItemVariables> itemVariables = new List <def_ItemVariables>(); foreach (def_Sections section in sections) { GetSectionItemsAndSubSectionsRecursive(section.sectionId, sectionItems, subSections); } foreach (def_SectionItems si in sectionItems) { if (si.subSectionId == null) { def_Items item = db.def_Items.Where(i => i.itemId == si.itemId).FirstOrDefault(); items.Add(item); List <def_ItemVariables> newItemVariables = db.def_ItemVariables.Where(iv => iv.itemId == item.itemId).ToList(); itemVariables.AddRange(newItemVariables); } } string jsonString = "{\"data\":[" + fastJSON.JSON.ToJSON(form); jsonString += "," + fastJSON.JSON.ToJSON(formParts); jsonString += "," + fastJSON.JSON.ToJSON(parts); jsonString += "," + fastJSON.JSON.ToJSON(partSections); jsonString += "," + fastJSON.JSON.ToJSON(sections); jsonString += "," + fastJSON.JSON.ToJSON(sectionItems); jsonString += "," + fastJSON.JSON.ToJSON(subSections); jsonString += "," + fastJSON.JSON.ToJSON(items); jsonString += "," + fastJSON.JSON.ToJSON(itemVariables); jsonString += "]}"; MemoryStream stream = new MemoryStream(); //write json string to file, then stream it out //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FormResultJSON)); StreamWriter streamWriter = new StreamWriter(stream); streamWriter.Write(jsonString); //streamWriter.Close(); //stream.Close(); FileStreamResult fsr = null; streamWriter.Flush(); stream.Position = 0; try { fsr = new FileStreamResult(stream, "application/json") { FileDownloadName = form.identifier + " " + DateTime.Now + ".json" }; } catch (Exception exp) { Debug.WriteLine("File write exception: " + exp.Message); string errMsg = "File write exception: " + exp.Message; return(ProcessError(errMsg)); } return(fsr); }
public async Task <IActionResult> Export(Guid id, ExportFormat format) { Repository.InitPaths(); var cardPath = ""; var mediaType = ""; switch (format) { case ExportFormat.Art: mediaType = "image/png"; cardPath = Repository.GetArtFile(id); break; case ExportFormat.Svg: cardPath = Repository.GetSvgFile(id); mediaType = "image/svg+xml"; break; case ExportFormat.Png: using (var repository = new Repository()) { var result = await repository.Context.Cards.FindByGuidAsync(id); if (!string.IsNullOrEmpty(result.PngCreationJobId)) { // still busy creating png return(NotFound()); } } mediaType = "image/png"; cardPath = Repository.GetPngFile(id); break; case ExportFormat.Jpeg: using (var repository = new Repository()) { var result = await repository.Context.Cards.FindByGuidAsync(id); if (!string.IsNullOrEmpty(result.PngCreationJobId)) { // still busy creating png return(NotFound()); } } mediaType = "image/jpeg"; cardPath = Repository.GetJpegFile(id); break; case ExportFormat.Pdf: using (var repository = new Repository()) { var result = await repository.Context.Cards.FindByGuidAsync(id); if (!string.IsNullOrEmpty(result.PngCreationJobId)) { // still busy creating png return(NotFound()); } } mediaType = "application/pdf"; cardPath = Repository.GetPdfFile(id); break; case ExportFormat.OverlaySvg: cardPath = Repository.GetOverlaySvgFile(id); mediaType = "image/svg+xml"; break; case ExportFormat.BackgroundPng: using (var repository = new Repository()) { var result = await repository.Context.Cards.FindByGuidAsync(id); await repository.Context.Entry(result).Reference(x => x.Faction).LoadAsync(); await repository.Context.Entry(result).Reference(x => x.Type).LoadAsync(); mediaType = "image/png"; cardPath = Repository.GetBackgroundPngFile(result.Faction.Name, result.Type.Name); } break; case ExportFormat.BackPng: mediaType = "image/png"; cardPath = Repository.GetBackPngFile(); break; case ExportFormat.BackJpeg: mediaType = "image/jpeg"; cardPath = Repository.GetBackJpegFile(); break; case ExportFormat.BackPdf: mediaType = "application/pdf"; cardPath = Repository.GetBackPdfFile(); break; case ExportFormat.BackSvg: cardPath = Repository.GetBackSvgFile(); mediaType = "image/svg+xml"; break; } if (!System.IO.File.Exists(cardPath)) { return(NotFound("The card with the specified id does not exist")); } var filename = Path.GetFileName(cardPath); Stream stream = new FileStream(cardPath, FileMode.Open); var contentType = new MediaTypeHeaderValue(mediaType); var response = new FileStreamResult(stream, contentType) { FileDownloadName = filename }; return(response); }
public ActionResult DigitalSignature(string Browser, string password, string Reason, string Location, string Contact, string RadioButtonList2, string NewPDF, string submit, IFormFile pdfdocument, IFormFile certificate) { string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; if (submit == "Create Sign PDF") { if (pdfdocument != null && pdfdocument.Length > 0 && certificate != null && certificate.Length > 0 && certificate.FileName.Contains(".pfx") && password != null && Location != null && Reason != null && Contact != null) { PdfLoadedDocument ldoc = new PdfLoadedDocument(pdfdocument.OpenReadStream()); PdfCertificate pdfCert = new PdfCertificate(certificate.OpenReadStream(), password); PdfPageBase page = ldoc.Pages[0]; PdfSignature signature = new PdfSignature(ldoc, page, pdfCert, "Signature"); signature.Bounds = new RectangleF(new PointF(5, 5), new SizeF(200, 200)); signature.ContactInfo = Contact; signature.LocationInfo = Location; signature.Reason = Reason; MemoryStream stream = new MemoryStream(); ldoc.Save(stream); stream.Position = 0; ldoc.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); fileStreamResult.FileDownloadName = "SignedPDF.pdf"; return(fileStreamResult); return(View()); } else { ViewBag.lab = "NOTE: Fill all fields and then create PDF"; return(View()); } } else { //Read the PFX file FileStream pfxFile = new FileStream(dataPath + "PDF.pfx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PdfDocument doc = new PdfDocument(); PdfPage page = doc.Pages.Add(); PdfSolidBrush brush = new PdfSolidBrush(Color.Black); PdfPen pen = new PdfPen(brush, 0.2f); PdfFont font = new PdfStandardFont(PdfFontFamily.Courier, 12, PdfFontStyle.Regular); PdfCertificate pdfCert = new PdfCertificate(pfxFile, "syncfusion"); PdfSignature signature = new PdfSignature(page, pdfCert, "Signature"); FileStream jpgFile = new FileStream(dataPath + "logo.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PdfBitmap bmp = new PdfBitmap(jpgFile); signature.Bounds = new RectangleF(new PointF(5, 5), page.GetClientSize()); signature.ContactInfo = "*****@*****.**"; signature.LocationInfo = "Honolulu, Hawaii"; signature.Reason = "I am author of this document."; if (RadioButtonList2 == "Standard") { signature.Certificated = true; } else { signature.Certificated = false; } PdfGraphics graphics = signature.Appearence.Normal.Graphics; string validto = "Valid To: " + signature.Certificate.ValidTo.ToString(); string validfrom = "Valid From: " + signature.Certificate.ValidFrom.ToString(); graphics.DrawImage(bmp, 0, 0); doc.Pages[0].Graphics.DrawString(validfrom, font, pen, brush, 0, 90); doc.Pages[0].Graphics.DrawString(validto, font, pen, brush, 0, 110); doc.Pages[0].Graphics.DrawString(" Protected Document. Digitally signed Document.", font, pen, brush, 0, 130); doc.Pages[0].Graphics.DrawString("* To validate Signature click on the signature on this page \n * To check Document Status \n click document status icon on the bottom left of the acrobat reader.", font, pen, brush, 0, 150); // Save the pdf document to the Stream. MemoryStream stream = new MemoryStream(); doc.Save(stream); //Close document doc.Close(); stream.Position = 0; // Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); fileStreamResult.FileDownloadName = "SignedPDF.pdf"; return(fileStreamResult); return(View()); } }
public string crear_pdf(Entities.Model.Order order, List <CartItem> carrito, Shipping ship) { MemoryStream ms = new MemoryStream(); PdfWriter pw = new PdfWriter(ms); PdfDocument pdfdocument = new PdfDocument(pw); Document doc = new Document(pdfdocument, PageSize.A4); doc.SetMargins(75, 35, 70, 35); //PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA); string pathlogo = Server.MapPath("~/Content/assets/img/core-img/logo.png"); iText.Layout.Element.Image img = new iText.Layout.Element.Image(ImageDataFactory.Create(pathlogo)); //Cabecera iText.Layout.Element.Cell separador = new iText.Layout.Element.Cell(1, 1); iText.Layout.Element.Table table = new iText.Layout.Element.Table(2).UseAllAvailableWidth() /*.SetBorder(Border.NO_BORDER)*/; iText.Layout.Element.Cell cell = new iText.Layout.Element.Cell(4, 1).SetTextAlignment(TextAlignment.LEFT).SetBorder(Border.NO_BORDER); cell.Add(img.ScaleToFit(150, 150)); table.AddCell(cell); cell = new iText.Layout.Element.Cell(2, 2).Add(new Paragraph("Factura No: 0177-" + string.Format("{0:00000000}", order.Id))) .SetTextAlignment(TextAlignment.RIGHT) .SetBorder(Border.NO_BORDER); table.AddCell(cell); cell = new iText.Layout.Element.Cell(2, 2).Add(new Paragraph("Fecha: " + DateTime.Today.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture))) .SetTextAlignment(TextAlignment.RIGHT).SetBorder(Border.NO_BORDER); table.AddCell(cell); doc.Add(table); //Datos Cliente iText.Layout.Element.Table _clienttable = new iText.Layout.Element.Table(1).UseAllAvailableWidth().SetMarginTop(20) /*.SetBorder(Border.NO_BORDER)*/; _clienttable.AddCell(separador); iText.Layout.Element.Cell _clientecell = new iText.Layout.Element.Cell(1, 1); _clientecell.Add(new Paragraph("Nombre: " + ship.FirstName + " " + ship.LastName)) .SetTextAlignment(TextAlignment.LEFT) .SetMarginBottom(10).SetBorder(Border.NO_BORDER); _clienttable.AddCell(_clientecell); _clientecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Dirección: " + ship.Address)) .SetTextAlignment(TextAlignment.LEFT).SetMarginBottom(10).SetBorder(Border.NO_BORDER); _clienttable.AddCell(_clientecell); _clientecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Ciudad: " + ship.City)) .SetTextAlignment(TextAlignment.LEFT).SetMarginBottom(10).SetBorder(Border.NO_BORDER); _clienttable.AddCell(_clientecell); _clientecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("País: " + ship.Country)) .SetTextAlignment(TextAlignment.LEFT).SetMarginBottom(10).SetBorder(Border.NO_BORDER); _clienttable.AddCell(_clientecell); _clientecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Email: " + ship.Email)) .SetTextAlignment(TextAlignment.LEFT).SetMarginBottom(10).SetBorder(Border.NO_BORDER); _clienttable.AddCell(_clientecell); _clienttable.AddCell(separador); doc.Add(_clienttable); //doc.Add(ls); //Datos Product Encabezado iText.Layout.Element.Table _prodtable = new iText.Layout.Element.Table(6).UseAllAvailableWidth().SetMarginTop(20) /*.SetBorder(Border.NO_BORDER)*/; iText.Layout.Element.Cell _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("# Item")) .SetTextAlignment(TextAlignment.CENTER) .SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Codigo Articulo")) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Descripcion")) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Precio Unitario")) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Cantidad")) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Subtotal")) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); int x = 0; foreach (CartItem item in carrito) { x++; _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph(x.ToString())).SetBorder(Border.NO_BORDER) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph(item.ProductId.ToString())).SetBorder(Border.NO_BORDER) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph(item.Product.Title.ToString())).SetBorder(Border.NO_BORDER) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph(item.Price.ToString())).SetBorder(Border.NO_BORDER) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph(item.Quantity.ToString())).SetBorder(Border.NO_BORDER) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); _prodecell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph((item.Quantity * item.Price).ToString())).SetBorder(Border.NO_BORDER) .SetTextAlignment(TextAlignment.CENTER).SetMarginBottom(10); _prodtable.AddCell(_prodecell); } doc.Add(_prodtable); //Total iText.Layout.Element.Table totaltable = new iText.Layout.Element.Table(1).UseAllAvailableWidth().SetMarginTop(20) /*.SetBorder(Border.NO_BORDER)*/; iText.Layout.Element.Cell totalcell = new iText.Layout.Element.Cell(1, 1).Add(new Paragraph("Total: $" + order.TotalPrice)) .SetTextAlignment(TextAlignment.RIGHT) .SetMarginBottom(10).SetBorder(Border.NO_BORDER); totaltable.AddCell(totalcell); doc.Add(totaltable); //pdfdocument.AddEventHandler(PdfDocumentEvent.END_PAGE, new HeaderEventHandler1(img)); //iText.Layout.Element.Table _table = new iText.Layout.Element.Table(1).UseAllAvailableWidth(); doc.Close(); byte[] byteStream = ms.ToArray(); var inputAsString = Convert.ToString(Convert.ToBase64String(ms.ToArray())); ms = new MemoryStream(); ms.Write(byteStream, 0, byteStream.Length); ms.Position = 0; var pdf = new FileStreamResult(ms, "application/pdf"); /*return new FileStreamResult(ms, "application/pdf")*/; return(inputAsString.ToString()); }
public async Task <IActionResult> CreateDocument() { string user = User.FindFirst("Index").Value; var Currentuser = await _taskRepository.GetCurrentUser(user); ViewBag.photo = Currentuser.PhotoURL; //Creates a new PDF document PdfDocument document = new PdfDocument(); //Adds page settings document.PageSettings.Orientation = PdfPageOrientation.Portrait; document.PageSettings.Margins.All = 50; //Adds a page to the document PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; //Loads the image as stream PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 24); graphics.DrawString("Daily Time Sheet - ", font, PdfBrushes.Blue, new PointF(170, 30)); string Date = DateTime.Now.ToString("MM/dd/yyyy"); PdfFont font4 = new PdfStandardFont(PdfFontFamily.Helvetica, 18); string currentDate = "DATE " + DateTime.Now.ToString("MM/dd/yyyy"); graphics.DrawString(Date, font4, PdfBrushes.Blue, new PointF(370, 33)); PdfFont font2 = new PdfStandardFont(PdfFontFamily.Helvetica, 16); graphics.DrawString("Ishara Maduhansi", font2, PdfBrushes.Black, new PointF(190, 70)); PdfFont font3 = new PdfStandardFont(PdfFontFamily.Helvetica, 13); graphics.DrawString("Software Engineer", font3, PdfBrushes.Black, new PointF(190, 95)); FileStream imageStream = new FileStream("wwwroot/images/bell.jpg", FileMode.Open, FileAccess.Read); RectangleF bounds = new RectangleF(10, 0, 150, 150); PdfImage image = PdfImage.FromStream(imageStream); //Draws the image to the PDF page page.Graphics.DrawImage(image, bounds); PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); bounds = new RectangleF(0, 160, graphics.ClientSize.Width, 30); //Draws a rectangle to place the heading in that region. graphics.DrawRectangle(solidBrush, bounds); //Creates a font for adding the heading in the page PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14); //Creates a text element to add the invoice number PdfTextElement element = new PdfTextElement("Time Sheet ", subHeadingFont); element.Brush = PdfBrushes.White; //Draws the heading on the page PdfLayoutResult result = element.Draw(page, new PointF(10, 165)); //Measures the width of the text to place it in the correct location SizeF textSize = subHeadingFont.MeasureString(currentDate); PointF textPosition = new PointF(graphics.ClientSize.Width - textSize.Width - 10, 165); //Draws the date by using DrawString method graphics.DrawString(currentDate, subHeadingFont, element.Brush, textPosition); //Creates text elements to add the address and draw it to the page. PdfPen linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f); PointF startPoint = new PointF(0, result.Bounds.Bottom + 3); PointF endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3); ////Draws a line at the bottom of the address graphics.DrawLine(linePen, startPoint, endPoint); //Creates the datasource for the table // Creates a PDF grid // Creates the grid cell styles //Create a PdfGrid. PdfGrid pdfGrid = new PdfGrid(); //Add values to list List <object> data = new List <object>(); object[] ary = new object[2]; Object row1 = new { task = "Login", Start_Date = Date, End_Date = Date, Effort = "2 h 40 Min" }; Object row2 = new { task = "Time Sheet", Start_Date = Date, End_Date = Date, Effort = "3 h " }; Object row3 = new { task = "Employee", Start_Date = Date, End_Date = Date, Effort = "2 h 40 Min" }; Object row4 = new { task = "Leave Part", Start_Date = Date, End_Date = Date, Effort = "4 h 20 Min" }; Object row5 = new { task = "Attendence Part", Start_Date = Date, End_Date = Date, Effort = "1 h 40 Min" }; data.Add(row1); data.Add(row2); data.Add(row3); data.Add(row4); data.Add(row5); //Add list to IEnumerable IEnumerable <object> dataTable = data; //Assign data source. pdfGrid.DataSource = dataTable; //Draw grid to the page of PDF document. pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(10, 230)); MemoryStream stream = new MemoryStream(); document.Save(stream); //If the position is not set to '0' then the PDF will be empty. stream.Position = 0; //Close the document. FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); //Creates a FileContentResult object by using the file contents, content type, and file name. return(fileStreamResult); }
public FileStreamResult GetProfilePayload() { var serviceBaseUri = ServiceBaseUri(); // If we are not doing Re-writes of Url, we need to set the thumbnails explicitly at all places var payloadDetails = PayloadDetailsExtensions.InitializePayload(); payloadDetails.Thumbnail = RewriteThumbnailUrl(payloadDetails.Thumbnail, "defaultfolderwwtthumbnail"); payloadDetails.Name = Resources.MyFolderLabel; //upgrade notice //var upgradeLink = new Place(); //upgradeLink.Name = "Upgrade Notice"; //upgradeLink.Url = "/upgrade/index?wwtfull=true"; //upgradeLink.Permission = Permission.Reader; //upgradeLink.Thumbnail = RewriteThumbnailUrl(upgradeLink.Thumbnail, "upgradenotice"); //payloadDetails.Links.Add(upgradeLink); // Get My communities node. var myCommunities = PayloadDetailsExtensions.InitializePayload(); myCommunities.Name = Resources.MyCommunitiesWWTLabel; myCommunities.Url = string.Format(CultureInfo.InvariantCulture, "{0}/Communities", serviceBaseUri); myCommunities.Thumbnail = RewriteThumbnailUrl(myCommunities.Thumbnail, "defaultfolderwwtthumbnail"); payloadDetails.Children.Add(myCommunities); // Get My contents node. var myContents = PayloadDetailsExtensions.InitializePayload(); myContents.Name = Resources.MyContentsWWTLabel; myContents.Url = string.Format(CultureInfo.InvariantCulture, "{0}/Contents", serviceBaseUri); myContents.Thumbnail = RewriteThumbnailUrl(myContents.Thumbnail, "defaultfolderwwtthumbnail"); payloadDetails.Children.Add(myContents); // Get Browse EO node. var browseDetails = PayloadDetailsExtensions.InitializePayload(); browseDetails.Name = Resources.BrowseWWTLabel; browseDetails.Url = string.Format(CultureInfo.InvariantCulture, "{0}/Browse", serviceBaseUri); browseDetails.Thumbnail = RewriteThumbnailUrl(browseDetails.Thumbnail, "defaultfolderwwtthumbnail"); payloadDetails.Children.Add(browseDetails); // TODO: Get Search EO node. var searchEoLink = new Place(); searchEoLink.Name = Resources.SearchWWTLabel; searchEoLink.Url = string.Format(CultureInfo.InvariantCulture, "{0}/Community/index{1}", BaseUri(), "?wwtfull=true"); searchEoLink.Permission = Permission.Reader; searchEoLink.Thumbnail = RewriteThumbnailUrl(searchEoLink.Thumbnail, "searchwwtthumbnail"); // This will make sure that the additional context menu options specific to folders are not shown in WWT. searchEoLink.MSRComponentId = -1; payloadDetails.Links.Add(searchEoLink); // TODO: Get Help node. var helpLink = new Place(); helpLink.Name = Resources.HelpWWTLabel; helpLink.Url = string.Format(CultureInfo.InvariantCulture, "{0}/Support/index{1}", BaseUri(), "?wwtfull=true"); helpLink.Permission = Permission.Reader; helpLink.Thumbnail = RewriteThumbnailUrl(helpLink.Thumbnail, "helpwwtthumbnail"); // This will make sure that the additional context menu options specific to folders are not shown in WWT. helpLink.MSRComponentId = -1; payloadDetails.Links.Add(helpLink); var payload = new FileStreamResult(GetOutputStream(payloadDetails), Response.ContentType); return(payload); }
public IActionResult pdf(int id) { //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); WebKitConverterSettings settings = new WebKitConverterSettings(); //Set WebKit path settings.WebKitPath = Path.Combine(hosting.ContentRootPath, "QtBinariesWindows"); //Assign WebKit settings to HTML converter htmlConverter.ConverterSettings = settings; //Convert URL to PDF Application mrki = _db.Application.Where(a => a.ApplicationId == id).Include(b => b.Applicant).ThenInclude(c => c.ApplicationUser).Include(d => d.Infos).ThenInclude(q => q.Citizenship).Include(e => e.HomeInstitutions).Include(f => f.Languages).Include(g => g.Contacts).ThenInclude(z => z.Country).Include(h => h.Documents).Include(i => i.Others).FirstOrDefault(); PdfDocument pdfDocument = new PdfDocument(); //Add a page to the PDF document. PdfPage pdfPage = pdfDocument.Pages.Add(); PdfPage pdfPage2 = pdfDocument.Pages.Add(); //Create a PDF Template. PdfTemplate template = new PdfTemplate(900, 900); PdfTemplate template2 = new PdfTemplate(900, 900); //Draw a rectangle on the template graphics template.Graphics.DrawRectangle(PdfBrushes.White, new Syncfusion.Drawing.RectangleF(0, 0, 900, 900)); template2.Graphics.DrawRectangle(PdfBrushes.White, new Syncfusion.Drawing.RectangleF(0, 0, 900, 900)); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); PdfFont font2 = new PdfStandardFont(PdfFontFamily.Helvetica, 20); PdfFont font3 = new PdfStandardFont(PdfFontFamily.Helvetica, 16); PdfBrush brush = new PdfSolidBrush(Color.Black); //Draw a string using the graphics of the template. RectangleF bounds = new RectangleF(0, 0, pdfDocument.Pages[0].GetClientSize().Width, 52); PdfPageTemplateElement header = new PdfPageTemplateElement(bounds); //Load the PDF document FileStream imageStream = new FileStream("unmo_logo.png", FileMode.Open, FileAccess.Read); PdfImage image = new PdfBitmap(imageStream); //Draw the image in the header. header.Graphics.DrawImage(image, new PointF(75, 0), new SizeF(137, 52)); header.Graphics.DrawString("Application number " + mrki.ApplicationId, font2, brush, 205, 12); //Add the header at the top. pdfDocument.Template.Top = header; template.Graphics.DrawString("About", font3, brush, 10, 17); template.Graphics.DrawString("Full name: ", font, brush, 32, 42); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.Name + " " + mrki.Applicant.ApplicationUser.Surname, font, brush, 280, 42); template.Graphics.DrawString("Account created: ", font, brush, 32, 57); template.Graphics.DrawString(mrki.Applicant.CreatedProfile.ToString(), font, brush, 280, 57); template.Graphics.DrawString("Application created: ", font, brush, 32, 72); template.Graphics.DrawString(mrki.CreatedApp.ToString(), font, brush, 280, 72); template.Graphics.DrawString("Application submitted: ", font, brush, 32, 87); template.Graphics.DrawString(mrki.FinishedTime.ToString(), font, brush, 280, 87); template.Graphics.DrawString("Information", font3, brush, 10, 107); template.Graphics.DrawString("Gender: ", font, brush, 32, 132); template.Graphics.DrawString(mrki.Infos.Gender, font, brush, 280, 132); template.Graphics.DrawString("Date of birth: ", font, brush, 32, 149); template.Graphics.DrawString(mrki.Infos.DateOfBirth.ToShortDateString(), font, brush, 280, 149); template.Graphics.DrawString("Place of birth: ", font, brush, 32, 166); template.Graphics.DrawString(mrki.Infos.PlaceOfBirth.ToString(), font, brush, 280, 166); template.Graphics.DrawString("Citizenship: ", font, brush, 32, 183); template.Graphics.DrawString(mrki.Infos.Citizenship.Name.ToString(), font, brush, 280, 183); template.Graphics.DrawString("Passport number: ", font, brush, 32, 200); template.Graphics.DrawString(mrki.Infos.PassportNumber.ToString(), font, brush, 280, 200); template.Graphics.DrawString("Passport issue date: ", font, brush, 32, 217); template.Graphics.DrawString(mrki.Infos.PassportIssueDate.ToShortDateString(), font, brush, 280, 217); template.Graphics.DrawString("Passport expiry date: ", font, brush, 32, 234); template.Graphics.DrawString(mrki.Infos.PassportExpiryDate.ToShortDateString(), font, brush, 280, 234); template.Graphics.DrawString("Contacts", font3, brush, 10, 259); template.Graphics.DrawString("E-mail: ", font, brush, 32, 284); template.Graphics.DrawString(mrki.Contacts.Email.ToString(), font, brush, 280, 284); template.Graphics.DrawString("Phone number: ", font, brush, 32, 301); template.Graphics.DrawString(mrki.Contacts.Telephone.ToString(), font, brush, 280, 301); template.Graphics.DrawString("Street name: ", font, brush, 32, 318); template.Graphics.DrawString(mrki.Contacts.StreetName.ToString(), font, brush, 280, 318); template.Graphics.DrawString("City, town, village: ", font, brush, 32, 335); template.Graphics.DrawString(mrki.Contacts.PlaceName.ToString(), font, brush, 280, 335); template.Graphics.DrawString("Postal code: ", font, brush, 32, 352); template.Graphics.DrawString(mrki.Contacts.PostalCode.ToString(), font, brush, 280, 352); template.Graphics.DrawString("Country of residence: ", font, brush, 32, 369); template.Graphics.DrawString(mrki.Contacts.Country.Name.ToString(), font, brush, 280, 369); template.Graphics.DrawString("Languages", font3, brush, 10, 394); template.Graphics.DrawString("Native language: ", font, brush, 32, 419); template.Graphics.DrawString(mrki.Languages.Native.ToString(), font, brush, 280, 419); template.Graphics.DrawString("First foreign language: ", font, brush, 32, 436); string ff = mrki.Languages.ForeignFirst + " | " + mrki.Languages.ForeignFirstProficiency; template.Graphics.DrawString(ff, font, brush, 280, 436); template.Graphics.DrawString("Second foreign language: ", font, brush, 32, 453); string sf = mrki.Languages.ForeignSecond + " | " + mrki.Languages.ForeignSecondProficiency; template.Graphics.DrawString(sf, font, brush, 280, 453); template.Graphics.DrawString("Third foreign language: ", font, brush, 32, 470); string tf = mrki.Languages.ForeignThird + " | " + mrki.Languages.ForeignThirdProficiency; template.Graphics.DrawString(tf, font, brush, 280, 470); template.Graphics.DrawString("Number of foreign experiences: ", font, brush, 32, 487); template.Graphics.DrawString(mrki.Languages.ForeignExperienceNumber.ToString(), font, brush, 280, 487); template.Graphics.DrawString("Home institution", font3, brush, 10, 512); template.Graphics.DrawString("University: ", font, brush, 32, 537); template.Graphics.DrawString(mrki.HomeInstitutions.OfficialName.ToString(), font, brush, 280, 537); //template.Graphics.DrawString("Faculty: ", font, brush, 5, 335); //template.Graphics.DrawString(mrki.Applicant.FacultyName.ToString(), font, brush, 280, 335); template.Graphics.DrawString("Department name: ", font, brush, 32, 554); template.Graphics.DrawString(mrki.HomeInstitutions.DepartmentName.ToString(), font, brush, 280, 554); template.Graphics.DrawString("Study programme: ", font, brush, 32, 571); template.Graphics.DrawString(mrki.HomeInstitutions.StudyProgramme.ToString(), font, brush, 280, 571); template.Graphics.DrawString("Study cycle: ", font, brush, 32, 588); template.Graphics.DrawString(mrki.Applicant.StudyCycle, font, brush, 280, 588); template.Graphics.DrawString("Current term/year: ", font, brush, 32, 605); template.Graphics.DrawString(mrki.HomeInstitutions.CurrentTermOrYear.ToString(), font, brush, 280, 605); template.Graphics.DrawString("Coordinator full name: ", font, brush, 32, 622); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorFullName.ToString(), font, brush, 280, 622); template.Graphics.DrawString("Coordinator e-mail: ", font, brush, 32, 639); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorEmail.ToString(), font, brush, 280, 639); template.Graphics.DrawString("Coordinator phone number: ", font, brush, 32, 656); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorPhoneNum.ToString(), font, brush, 280, 656); template.Graphics.DrawString("Coordinator address: ", font, brush, 32, 673); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorAddress.ToString(), font, brush, 280, 673); template.Graphics.DrawString("Coordinator position: ", font, brush, 32, 690); template.Graphics.DrawString(mrki.HomeInstitutions.CoordinatorPosition.ToString(), font, brush, 280, 690); template2.Graphics.DrawString("Others", font3, brush, 10, 5); template2.Graphics.DrawString("Medical info: ", font, brush, 32, 30); template2.Graphics.DrawString(mrki.Others.MedicalInfo.ToString(), font, brush, 280, 30); template2.Graphics.DrawString("Additional requests: ", font, brush, 32, 47); template2.Graphics.DrawString(mrki.Others.AdditionalRequests.ToString(), font, brush, 280, 47); var path1 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.LearningAgreement); var path2 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.CV); var path3 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.EngProficiency); var path4 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.TranscriptOfRecords); var path5 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.MotivationLetter); var path6 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Documents.ReferenceLetter); FileStream stream1 = new FileStream(path1, FileMode.Open, FileAccess.Read); FileStream stream2 = new FileStream(path2, FileMode.Open, FileAccess.Read); FileStream stream3 = new FileStream(path3, FileMode.Open, FileAccess.Read); FileStream stream4 = new FileStream(path4, FileMode.Open, FileAccess.Read); FileStream stream5 = new FileStream(path5, FileMode.Open, FileAccess.Read); //FileStream stream6 = new FileStream(path6, FileMode.Open, FileAccess.Read); // Creates a PDF stream for merging Stream[] streams = { stream1, stream2, stream3, stream4, stream5 };// stream6 }; // Merges PDFDocument. PdfDocumentBase.Merge(pdfDocument, streams); ////Draw the template on the page graphics of the document. pdfPage.Graphics.DrawPdfTemplate(template, PointF.Empty); pdfPage2.Graphics.DrawPdfTemplate(template2, PointF.Empty); //Save the document into stream MemoryStream stream = new MemoryStream(); pdfDocument.Save(stream); stream.Position = 0; pdfDocument.Close(true); //Define the file name FileStreamResult nova = new FileStreamResult(stream, "application/pdf"); string nameOfFile = "Application_" + mrki.ApplicationId + "_" + mrki.Applicant.ApplicationUser.Name + "_" + mrki.Applicant.ApplicationUser.Surname + ".pdf"; nova.FileDownloadName = nameOfFile; return(nova); }
public IActionResult RenderBill(int id) { var bill = _billRepo.BillHeaders.Where(b => b.Id == id).Include(b => b.BillDetails).FirstOrDefault(); var details = bill.BillDetails.Select(d => new { BillDetailType = Convert.ToInt32(d.BillDetailType), d.FixedAmount, d.UnitRate, d.Quantity, d.Subtotal, d.Description, d.TaxesAmount }).ToList(); string basePath = _hostingEnvironment.ContentRootPath; string fullPath = basePath + @"/Reports/Bill.rdlc"; FileStream inputStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read); ReportDataSourceCollection dataSources = new ReportDataSourceCollection(); dataSources.Add(new ReportDataSource { Name = "BillDataSet", Value = details }); Syncfusion.ReportWriter.ReportWriter writer = new Syncfusion.ReportWriter.ReportWriter(inputStream, dataSources); //writer.DataSources = dataSources; //Setting up the parameters List <ReportParameter> parameters = new List <ReportParameter>(); //IsEnglish bool isBillingInEnglish = _clientRepo.Clients.Where(c => c.Id == bill.ClientId).Select(c => c.BillingInEnglish).First(); ReportParameter isEnglishParam = new ReportParameter(); isEnglishParam.Name = "IsEnglish"; isEnglishParam.Values = new List <string>() { isBillingInEnglish ? "1" : "0" }; //IsBilled ReportParameter isBilledParam = new ReportParameter(); isBilledParam.Name = "IsBilled"; isBilledParam.Values = new List <string>() { "1" }; //ClientName ReportParameter clientNameParam = new ReportParameter(); clientNameParam.Name = "ClientName"; clientNameParam.Values = new List <string>() { bill.BillName }; //BillingPeriod string culture = isBillingInEnglish ? "en" : "es"; string billingPeriod = $"{CultureInfo.GetCultureInfoByIetfLanguageTag(culture).DateTimeFormat.GetMonthName(DateTime.UtcNow.AddHours(-6).Month)} - {bill.BillYear}"; ReportParameter billingPeriodParam = new ReportParameter(); billingPeriodParam.Name = "BillingPeriod"; billingPeriodParam.Values = new List <string>() { billingPeriod }; //Subtotal ReportParameter subTotalExpenseParam = new ReportParameter(); subTotalExpenseParam.Name = "Subtotal"; subTotalExpenseParam.Values = new List <string>() { bill.BillSubtotal.ToString() }; //Discount ReportParameter discountParam = new ReportParameter(); discountParam.Name = "Discount"; discountParam.Values = new List <string>() { bill.BillDiscount.ToString() }; //Taxes ReportParameter taxesParam = new ReportParameter(); taxesParam.Name = "Taxes"; taxesParam.Values = new List <string>() { bill.Taxes.ToString() }; //TotalExpense ReportParameter totalParam = new ReportParameter(); totalParam.Name = "Total"; totalParam.Values = new List <string>() { bill.Total.ToString() }; //TotalExpense ReportParameter billDateParam = new ReportParameter(); billDateParam.Name = "BillDate"; billDateParam.Values = new List <string>() { bill.BillDate.ToString() }; parameters.Add(isEnglishParam); parameters.Add(isBilledParam); parameters.Add(clientNameParam); parameters.Add(billingPeriodParam); parameters.Add(subTotalExpenseParam); parameters.Add(discountParam); parameters.Add(taxesParam); parameters.Add(totalParam); parameters.Add(billDateParam); writer.SetParameters(parameters); writer.ReportProcessingMode = ProcessingMode.Local; MemoryStream memoryStream = new MemoryStream(); writer.Save(memoryStream, WriterFormat.PDF); memoryStream.Position = 0; FileStreamResult fileStreamResult = new FileStreamResult(memoryStream, "application/pdf"); fileStreamResult.FileDownloadName = $"FacturaCliente{bill.BillName}deMes{bill.BillMonth}YAño{bill.BillYear}.pdf"; return(fileStreamResult); }
public static FileStreamResult GerarPdfEmpenho(ConsultaNe consulta, string tipo, Model.Entity.Empenho.Empenho empenho) { #region Configuraçao var meses = new List <mes>(); var properties = consulta.GetType().GetProperties().ToList(); int i = 0; foreach (var propertyInfo in properties) { if (propertyInfo.Name.Contains("Mes")) { if (propertyInfo.GetValue(consulta).ToString() != "") { mes mes = new mes { Mes = propertyInfo.GetValue(consulta).ToString(), Valor = "" }; meses.Add(mes); } i += 1; } } i = 0; foreach (var propertyInfo in properties) { if (propertyInfo.Name.Contains("Valor") && propertyInfo.Name != "Valor") { if (propertyInfo.GetValue(consulta).ToString() != "") { meses[i].Valor = propertyInfo.GetValue(consulta).ToString(); i += 1; } } } var fileName = consulta.NumeroNe + ".pdf"; string file = @"C:\Users\810235\Documents/" + fileName; FileInfo newFile = new FileInfo(file); if (newFile.Exists) { newFile.Delete(); } int inicio = 30; int linha = 68; int pularLinha = 13; var document = new PdfDocument(); var page = document.AddPage(); page.Size = PageSize.A4; var graphics = XGraphics.FromPdfPage(page); var textFormatter = new PdfSharp.Drawing.Layout.XTextFormatter(graphics); double val = 0; double espaco = 25; var diretorio = GerarImagem(); #endregion #region Cabeçario // Imagem. graphics.DrawImage(XImage.FromFile(diretorio), inicio - 20, 20, 60, 72); // Textos. //textFormatter.Alignment = PdfSharp.Drawing.Layout.XParagraphAlignment.Left; textFormatter.DrawString("GOVERNO DO ESTADO DE SÃO PAULO", new XFont("Calibri", 12, XFontStyle.Bold), XBrushes.Black, new XRect(85, linha, page.Width - 60, page.Height - 60)); linha += 32; textFormatter.DrawString("Nota de " + tipo, new XFont("Calibri", 18.5, XFontStyle.Regular), XBrushes.Black, new XRect(inicio - 20, linha, page.Width - 60, page.Height - 60)); // Figuras geométricas. linha += 20; graphics.DrawRectangle(XPens.Silver, XBrushes.White, new XRect(inicio - 20, linha, page.Width - 20, 0.1)); #endregion #region Bloco1 //Nº do Documento linha += 30; textFormatter.DrawString("Nº do Documento:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Nº do Documento:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.NumeroNe, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //Data Emissão val += graphics.MeasureString("Nº do Documento:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Data da Emissão:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); val += graphics.MeasureString("Data da Emissão:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.DataEmissao, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //Nº do Documento Prodesp linha += (pularLinha); textFormatter.DrawString("Nº do Empenho Prodesp:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Nº do Empenho Prodesp:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(empenho.NumeroEmpenhoProdesp ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //Gestão linha += pularLinha; textFormatter.DrawString("Gestão:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Gestão:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.Gestao, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //Nº Processo linha += (pularLinha); textFormatter.DrawString("Nº Processo:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Nº Processo:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.NumeroProcesso, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); #endregion #region Bloco2 //Credor linha += (pularLinha * 2); textFormatter.DrawString("Credor:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Credor:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.GestaoCredor, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); linha += (pularLinha); //CPF / CNPJ textFormatter.DrawString("CPF / CNPJ:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("CPF / CNPJ:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.CgcCpf, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //Origem do Material linha += (pularLinha * 2); textFormatter.DrawString("Origem do Material:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Origem do Material:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.OrigemMaterial, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); #endregion #region Bloco3 //Evento linha += (pularLinha * 2); textFormatter.DrawString("Evento", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Evento:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString(consulta.Evento, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); val = 0; //UO linha += (pularLinha * 2); textFormatter.DrawString("UO", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Uo, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //PT val += graphics.MeasureString("UO", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Programa de Trabalho", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Pt, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //Fonte val += graphics.MeasureString("Programa de Trabalho", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Fonte", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Fonte, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //Natureza Despesa val += graphics.MeasureString("Fonte", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Nat. Desp.", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Despesa, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //UGR val += graphics.MeasureString("Nat. Desp.", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("UGR", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Ugo, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //Plano Interno val += graphics.MeasureString("UGR", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("PI", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.PlanoInterno, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); #endregion #region Bloco3 //ReferenciaLegal linha += (pularLinha * 3); textFormatter.DrawString("Refer. Legal:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Refer. Legal:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.ReferenciaLegal, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //EmpenhoOriginal textFormatter.DrawString("Empenho Orig:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect((page.Width * 0.45), linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Empenho Orig:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.EmpenhoOriginal, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect((page.Width * 0.45) + val, linha, page.Width - 60, page.Height - 60)); //Licitação linha += (pularLinha); textFormatter.DrawString("Licitação:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Licitação:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.Licitacao, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //Modalidade textFormatter.DrawString("Modalidade:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect((page.Width * 0.45), linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Modalidade:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.Modalidade, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect((page.Width * 0.45) + val, linha, page.Width - 60, page.Height - 60)); //Tipo Empenho linha += (pularLinha); textFormatter.DrawString("Tipo Empenho:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Tipo Empenho:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.TipoEmpenho, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //Modalidade textFormatter.DrawString("Nº do Contrato:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect((page.Width * 0.45), linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Nº do Contrato:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.NumeroContrato, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect((page.Width * 0.45) + val, linha, page.Width - 60, page.Height - 60)); #endregion #region Bloco4 linha += (pularLinha); if (!string.IsNullOrEmpty(empenho.NumeroEmpenhoSiafem)) { //Obra textFormatter.DrawString("Nº da Obra:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Nº da Obra:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.IdentificadorObra, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); //Unidade de Medida linha += (pularLinha * 2); textFormatter.DrawString("Unidade de Medida:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Repete.tabela.unidade, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio, linha + pularLinha, page.Width - 60, page.Height - 60)); //Valor Unitario val = graphics.MeasureString("Unidade de Medida:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Valor Unitario:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Repete.tabela.valorunitario, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //Preço Total val += graphics.MeasureString("Valor Unitario:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Preço Total:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Repete.tabela.precototal, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); } #endregion #region Bloco5 linha += (pularLinha); if (!string.IsNullOrEmpty(empenho.NumeroEmpenhoSiafisico)) { val = 0; //Unidade de Medida linha += (pularLinha * 2); textFormatter.DrawString("Item Seq.", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Repete.tabela.sequencia, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio, linha + pularLinha, page.Width - 60, page.Height - 60)); //Item Serviço val += graphics.MeasureString("Item Seq.", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Item Serviço", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Repete.tabela.item, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //Quantidade do Item val += graphics.MeasureString("Item Serviço", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Quantidade do Item", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Repete.tabela.qtdeitem, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //Valor Unitario val += graphics.MeasureString("Quantidade do Item:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Valor Unitario", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Repete.tabela.valorunitario, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); //Preço Total val += graphics.MeasureString("Valor Unitario", new XFont("Calibri", 10, XFontStyle.Bold)).Width + espaco; textFormatter.DrawString("Preço Total", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(consulta.Repete.tabela.precototal, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); } #endregion #region Bloco6 linha += pularLinha * 3; //Valor Empenho textFormatter.DrawString("Valor Empenho:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Valor Empenho:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.Valor, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); #endregion #region Bloco7 linha += (pularLinha * 3); textFormatter.Alignment = PdfSharp.Drawing.Layout.XParagraphAlignment.Center; textFormatter.DrawString("Cronograma de Desembolso Previsto", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Cronograma de Desembolso Previsto", new XFont("Calibri", 10, XFontStyle.Bold)).Width / 2; graphics.DrawRectangle(XPens.Silver, XBrushes.White, new XRect(inicio - 20, linha + 11.8, page.Width - 20, 0.1)); linha += (pularLinha * 2); textFormatter.DrawString("Janeiro", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio - val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "01")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio - val, linha + pularLinha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Fevereiro", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "02")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio, linha + pularLinha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Março", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "03")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); linha += (pularLinha * 2); textFormatter.DrawString("Abril", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio - val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "04")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio - val, linha + pularLinha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Maio", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "05")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio, linha + pularLinha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Junho", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "06")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); linha += (pularLinha * 2); textFormatter.DrawString("Julho", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio - val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "07")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio - val, linha + pularLinha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Agosto", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "08")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio, linha + pularLinha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Setembro", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "09")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); linha += (pularLinha * 2); textFormatter.DrawString("Outubro", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio - val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "10")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio - val, linha + pularLinha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Novembro", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "11")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio, linha + pularLinha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Dezembro", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString(meses.FirstOrDefault(x => x.Mes == "12")?.Valor ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, linha + pularLinha, page.Width - 60, page.Height - 60)); #endregion #region bloco8 linha += (pularLinha * 9); textFormatter.Alignment = PdfSharp.Drawing.Layout.XParagraphAlignment.Left; textFormatter.DrawString("Lançado Por:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Lançado Por:", new XFont("Calibri", 10, XFontStyle.Bold)).Width; textFormatter.DrawString(consulta.Lancadopor, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val + 5, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Em:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + (page.Width * 0.6), linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Em:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.DataLancamento, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + (page.Width * 0.6) + val, linha, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Às:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio + (page.Width * 0.715), linha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Às:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(consulta.HoraLancamento, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + (page.Width * 0.715) + val, linha, page.Width - 60, page.Height - 60)); var text = "Impresso através de consulta Web Service ao SIAFEM na data " + DateTime.Now.ToShortDateString() + " e hora " + consulta.HoraConsulta; textFormatter.DrawString(text, new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio, page.Height - 40, page.Width - 60, page.Height - 60)); textFormatter.DrawString("Nº FCO:", new XFont("Calibri", 10, XFontStyle.Bold), XBrushes.Black, new XRect(inicio, page.Height - 40 + pularLinha, page.Width - 60, page.Height - 60)); val = graphics.MeasureString("Nº FCO:", new XFont("Calibri", 10, XFontStyle.Bold)).Width + 2; textFormatter.DrawString(empenho.NumeroEmpenhoProdesp ?? "", new XFont("Calibri", 10, XFontStyle.Regular), XBrushes.Black, new XRect(inicio + val, page.Height - 40 + pularLinha, page.Width - 60, page.Height - 60)); #endregion document.Save(fileName); System.Diagnostics.Process.Start(fileName); var contentType = "application/pdf"; MemoryStream stream = new MemoryStream { Position = 0 }; document.Save(stream, false); stream.Position = 0; var fileDownloadName = string.Format("{0}.pdf", consulta.NumeroNe); var fsr = new FileStreamResult(stream, contentType) { FileDownloadName = fileDownloadName }; return(fsr); }
public ActionResult MultiColumnHTML(string InsideBrowser) { string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; //Create a PDF document PdfDocument doc = new PdfDocument(); doc.PageSettings.Size = new SizeF(870, 732); //Add a page PdfPage page = doc.Pages.Add(); PdfSolidBrush brush = new PdfSolidBrush(Color.Black); PdfPen pen = new PdfPen(Color.Black, 1f); //Create font PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 11.5f); FileStream fontstream = new FileStream(dataPath + "Calibri.ttf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PdfTrueTypeFont heading = new PdfTrueTypeFont(fontstream, 14f, PdfFontStyle.Bold); font = new PdfStandardFont(PdfFontFamily.Helvetica, 8.5f); //Adding Header this.AddMulticolumnHeader(doc, "Syncfusion Essential PDF", "MultiColumnText Demo"); //Adding Footer this.AddFooter(doc, "@Copyright 2015"); #region htmlText string longtext = "<font color='#FF0000F'><b>PDF</b></font> stands for <i>\"Portable Document Format\"</i>." + " The key word is <i>portable</i>, intended to combine the qualities of <u>authenticity," + " reliability and ease of use together into a single packaged concept</u>.<br/><br/>" + "Adobe Systems invented PDF technology in the early 1990s to smooth the " + "process of moving text and graphics from publishers to printing-presses." + " <font color='#FF0000F'><b>PDF</b></font> turned out to be the very essence of paper, brought to life in a computer." + " In creating PDF, Adobe had almost unwittingly invented nothing less than a " + "bridge between the paper and computer worlds. <br/><br/>To be truly portable, an authentic electronic " + "document would have to appear exactly the same way on any computer at any time," + " at no cost to the user. It will deliver the exact same results in print or on-screen " + "with near-total reliability. "; #endregion //Rendering HtmlText PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(longtext, font, brush); // Formatting Layout PdfLayoutFormat format = new PdfLayoutFormat(); format.Layout = PdfLayoutType.OnePage; //Drawing htmlString richTextElement.Draw(page, new RectangleF(0, 15, 190, page.GetClientSize().Height), format); FileStream imageStream = new FileStream(dataPath + "PDFImage.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); ////Drawing Image PdfBitmap image = new PdfBitmap(imageStream); page.Graphics.DrawImage(image, new PointF(50, 295)); #region HtmlText longtext = "<font color='#FF0000F'><b>PDF</b></font> is used for representing two-dimensional documents in " + "a manner independent of the application software, hardware, and operating system.<sup>[1]</sup>" + "<br/><br/>Each PDF file encapsulates a complete description of a fixed-layout 2-D document " + "(and, with Acrobat 3-D, embedded 3-D documents) that includes the text, fonts, images, " + "and 2-D vector graphics which comprise the documents." + " <br/><br/><b>PDF</b> is an open standard that was officially published on July 1, 2008 by the ISO as" + "ISO 32000-1:2008.<sub>[2]</sub><br/><br/>" + "The PDF combines the technologies such as A sub-set of the PostScript page description programming " + "language, a font-embedding/replacement system to allow fonts to travel with the documents and a " + "structured storage system to bundle these elements and any associated content into a single file," + "with data compression where appropriate."; #endregion richTextElement = new PdfHTMLTextElement(longtext, font, brush); richTextElement.Draw(page, new RectangleF(0, 375, 190, page.GetClientSize().Height), format); #region HtmlText ////HtmlString string longText = "<font color='#0000F8'>Essential PDF</font> is a <u><i>.NET</i></u> " + "library with the capability to produce Adobe PDF files " + "It features a full-fledged object model for the easy creation of PDF files from any .NET language. " + " It does not use any external libraries and is built from scratch in C#. "; #endregion ////Rendering HtmlText richTextElement = new PdfHTMLTextElement(longText, font, brush); //Drawing htmlString richTextElement.Draw(page, new RectangleF(195, 15, 225, page.GetClientSize().Height), format); FileStream gifStream = new FileStream(dataPath + "Essen PDF.gif", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); ////Drawing Image PdfImage image1 = new PdfTiffImage(gifStream); page.Graphics.DrawImage(image1, new PointF(225, 100)); #region HtmlText string htmlText = "Essential PDF supports many features for creating a PDF document including <b>" + "drawing text, images, tables and other shapes</b>. " + "<br/><br/><font face='TimesRoman'>The generated PDF document can also be protected using <I>" + "40 Bit and 128 Bit encryption.</I></font><br/>" + "<p>Essential PDF is compatible with Microsoft Visual Studio .NET 2005 and 2008. " + "It is also compatible with the Express editions of Visual Studio.NET. <br/><br/>" + "The Essential PDF library can be used in any .NET environment including C#, VB.NET and managed C++.</p>" + "The PDF file that is created using Essential PDF can be viewed using Adobe Acrobat or the free " + "version of <u> Acrobat Viewer from Adobe only.</u>" + "<font color='#0000F8'><b><br/><br/>Essential PDF</b></font> It can be used on the server " + "side (ASP.NET or any other environment) or with Windows Forms applications. " + "The library is 100% managed, being written in C#.<br/><br/> " + "<font color='#FF0000F'>PdfDocument</font> is a top-level object in Essential PDF which implies a " + "representation of a PDF document. <br/><br/> " + "The document contains a collection of sections that are represented by the <font color='#FF0000F'>PdfSection</font> class, " + "which is a logical entity containing a collection of pages and their settings. <br/><br/> Pages (which are represented by <font color='#FF0000F'>PdfPage</font> class) " + "are the main destinations of the graphics output.<br/><br/>" + "A document can be saved through its <font color='#0000F8'>Save()</font> method. It can be saved either to a file or stream.<br/><br/>" + "In order to use the Essential PDF library in your project, add the PdfConfig component found in the toolbox to a project to enable support for PDF. "; #endregion //Rendering HtmlText PdfHTMLTextElement richTextElement1 = new PdfHTMLTextElement(htmlText, font, brush); //Drawing htmlString richTextElement1.Draw(page, new RectangleF(195, 200, 225, page.GetClientSize().Height), format); #region HtmlText htmlText = "<p>Every Syncfusion license includes a <i>one-year subscription</i> for unlimited technical support and new releases." + "Syncfusion licenses each product on a simple per-developer basis and charges no royalties," + "runtimes, or server deployment fees. A licensee can install his/her " + "license on multiple personal machines at <u>no extra charge.</u></p>" + "<p> At Syncfusion we are very excited about the Microsoft .NET platform.<br/><br/> " + "We believe that one of the key benefits of <font color='#0000F8'>.NET</font> is improved programmer productivity. " + "Solutions that used to take a very long time with traditional tools can now be " + "implemented in a much shorter time period with the <font color='#0000F8'>.NET</font> platform.</p>" + "Essential Studio includes seven component libraries in one great package." + "Essential Studio is available with full source code. It incorporates a " + "unique debugging support system that allows switching between 'Debug' and " + "\'Release\' versions of our library with a single click from inside the Visual" + "Studio.NET IDE. <br/><br/> <p> To ensure the highest quality of support possible," + "we use a state of the art <font color='#0000F8'>Customer Relationship Management software (CRM)</font> " + "based Developer Support System called Direct-Trac. Syncfusion Direc-Trac is a " + "support system that is uniquely tailored for developer needs. Support incidents " + "can be created and tracked to completion 24 hours a day, 7 days a week.</p><br/><br/> " + "We have a simple, royalty-free licensing model. Components are licensed to a single user." + " We recognize that you often work at home or on your laptop in addition to your work machine." + "Therefore, our license permits our products to be installed in more than one location." + " At Syncfusion, we stand behind our products 100%. <br/><br/>We have top notch management" + ", architects, product managers, sales people, support personnel, and developers " + "all working with you, the customer, as their focal point."; #endregion richTextElement = new PdfHTMLTextElement(htmlText, font, brush); //Drawing htmlString richTextElement.Draw(page, new RectangleF(425, 15, 225, page.GetClientSize().Height), format); #region HtmlText htmlText = "Each licensed control would need to have an entry in the licx file. This would mean that if you were using 20 licensed controls, you would have 20 different entries complete with a full version number in your licx file." + "<br/><br/> This posed major problems when upgrading to a newer version since these entries would need to have their version numbers changed. This also made trouble shooting licensing issues very difficult. "; #endregion richTextElement = new PdfHTMLTextElement(htmlText, font, brush); //Drawing htmlString richTextElement.Draw(page, new RectangleF(425, 500, 225, page.GetClientSize().Height), format); MemoryStream stream = new MemoryStream(); //Save the PDF document doc.Save(stream); stream.Position = 0; //Close the PDF document doc.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); fileStreamResult.FileDownloadName = "MergedPDF.pdf"; return(fileStreamResult); }
public ActionResult FormFilling(string submit1, string submit, string InsideBrowser, string flatten) { if (submit1 == "View Template") { string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; //Read the file FileStream file = new FileStream(dataPath + "Form.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Load the template document PdfLoadedDocument doc = new PdfLoadedDocument(file); //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); doc.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Close the PDF document. doc.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "template.pdf"; return(fileStreamResult); } else if (submit == "Generate PDF") { string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; //Read the file FileStream file = new FileStream(dataPath + "Form.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Load the template document PdfLoadedDocument doc = new PdfLoadedDocument(file); PdfLoadedForm form = doc.Form; // fill the fields from the first page (form.Fields["f1-1"] as PdfLoadedTextBoxField).Text = "1"; (form.Fields["f1-2"] as PdfLoadedTextBoxField).Text = "1"; (form.Fields["f1-3"] as PdfLoadedTextBoxField).Text = "1"; (form.Fields["f1-4"] as PdfLoadedTextBoxField).Text = "3"; (form.Fields["f1-5"] as PdfLoadedTextBoxField).Text = "1"; (form.Fields["f1-6"] as PdfLoadedTextBoxField).Text = "1"; (form.Fields["f1-7"] as PdfLoadedTextBoxField).Text = "22"; (form.Fields["f1-8"] as PdfLoadedTextBoxField).Text = "30"; (form.Fields["f1-9"] as PdfLoadedTextBoxField).Text = "John"; (form.Fields["f1-10"] as PdfLoadedTextBoxField).Text = "Doe"; (form.Fields["f1-11"] as PdfLoadedTextBoxField).Text = "3233 Spring Rd."; (form.Fields["f1-12"] as PdfLoadedTextBoxField).Text = "Atlanta, GA 30339"; (form.Fields["f1-13"] as PdfLoadedTextBoxField).Text = "332"; (form.Fields["f1-14"] as PdfLoadedTextBoxField).Text = "43"; (form.Fields["f1-15"] as PdfLoadedTextBoxField).Text = "4556"; (form.Fields["f1-16"] as PdfLoadedTextBoxField).Text = "3"; (form.Fields["f1-17"] as PdfLoadedTextBoxField).Text = "2000"; (form.Fields["f1-18"] as PdfLoadedTextBoxField).Text = "Exempt"; (form.Fields["f1-19"] as PdfLoadedTextBoxField).Text = "Syncfusion, Inc"; (form.Fields["f1-20"] as PdfLoadedTextBoxField).Text = "200"; (form.Fields["f1-21"] as PdfLoadedTextBoxField).Text = "22"; (form.Fields["f1-22"] as PdfLoadedTextBoxField).Text = "56654"; (form.Fields["c1-1[0]"] as PdfLoadedCheckBoxField).Items[0].Checked = true; (form.Fields["c1-1[1]"] as PdfLoadedCheckBoxField).Items[0].Checked = true; // fill the fields from the second page (form.Fields["f2-1"] as PdfLoadedTextBoxField).Text = "3200"; (form.Fields["f2-2"] as PdfLoadedTextBoxField).Text = "4850"; (form.Fields["f2-3"] as PdfLoadedTextBoxField).Text = "0"; (form.Fields["f2-4"] as PdfLoadedTextBoxField).Text = "500"; (form.Fields["f2-5"] as PdfLoadedTextBoxField).Text = "500"; (form.Fields["f2-6"] as PdfLoadedTextBoxField).Text = "800"; (form.Fields["f2-7"] as PdfLoadedTextBoxField).Text = "0"; (form.Fields["f2-8"] as PdfLoadedTextBoxField).Text = "0"; (form.Fields["f2-9"] as PdfLoadedTextBoxField).Text = "3"; (form.Fields["f2-10"] as PdfLoadedTextBoxField).Text = "3"; (form.Fields["f2-11"] as PdfLoadedTextBoxField).Text = "3"; (form.Fields["f2-12"] as PdfLoadedTextBoxField).Text = "2"; (form.Fields["f2-13"] as PdfLoadedTextBoxField).Text = "3"; (form.Fields["f2-14"] as PdfLoadedTextBoxField).Text = "3"; (form.Fields["f2-15"] as PdfLoadedTextBoxField).Text = "2"; (form.Fields["f2-16"] as PdfLoadedTextBoxField).Text = "1"; (form.Fields["f2-17"] as PdfLoadedTextBoxField).Text = "200"; (form.Fields["f2-18"] as PdfLoadedTextBoxField).Text = "600"; (form.Fields["f2-19"] as PdfLoadedTextBoxField).Text = "250"; if (flatten == "From Flatten") { doc.Form.Flatten = true; } //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); doc.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Close the PDF document. doc.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "Form.pdf"; return(fileStreamResult); } return(View()); }
public async Task <IActionResult> ProductImport(IFormFile file, int items) { if (file == null || file.Length == 0) { return(null); } var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot", file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } // Update the database once a day //updateFragrancex(); //Dictionary<string, double> calculation = new Dictionary<string, double>(); //Match shippingMatch = Regex.Match(shipping, @"[\d]+"); //calculation.Add("shipping", Double.Parse(shippingMatch.Value)); //Match amazonFee = Regex.Match(fee, @"[\d]+[/.]?[\d]+"); //calculation.Add("fee", Double.Parse(amazonFee.Value)); //Match profitMatch = Regex.Match(profit, @"[\d]+"); //calculation.Add("profit", Double.Parse(profitMatch.Value)); //if (markdown != null) //{ // Match markdownMatch = Regex.Match(markdown, @"[\d]+"); // calculation.Add("markDown", Double.Parse(markdownMatch.Value)); //} //var upc = _context.UPC.ToDictionary(x => x.ItemID, y => y.Upc); var prices = _context.Wholesaler_Fragrancex.ToDictionary(x => x.Sku, y => y.WholePriceUSD); Profile profile = new Profile(); IExcelExtension excelExtension = new ShopifyExcelUpdator(profile) { path = path, fragrancexPrices = prices }; //ExcelHelper.ExcelGenerator(path, prices, items); var memory = new MemoryStream(); using (var stream = new FileStream(path, FileMode.Open)) { await stream.CopyToAsync(memory); } memory.Position = 0; FileStreamResult returnFile = File(memory, Helper.GetContentType(path), Path.GetFileNameWithoutExtension(path) + "_Price_Updated" + Path.GetExtension(path).ToLowerInvariant()); System.IO.File.Delete(path); return(returnFile); }
public ActionResult Portfolio(string InsideBrowser) { //Stream readFile = new FileStream(ResolveApplicationDataPath(@"..\DocIO\DocToPDF.doc"), FileMode.Open, FileAccess.Read, FileShare.Read); // Create a new instance of PdfDocument class. PdfDocument document = new PdfDocument(); //Creating new portfolio document.PortfolioInformation = new PdfPortfolioInformation(); //setting the view mode of the portfolio document.PortfolioInformation.ViewMode = PdfPortfolioViewMode.Tile; string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; //Read the file FileStream file = new FileStream(dataPath + "CorporateBrochure.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Creating the attachment PdfAttachment pdfFile = new PdfAttachment("CorporateBrochure.pdf", file); pdfFile.FileName = "CorporateBrochure.pdf"; file = new FileStream(dataPath + "Stock.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Creating the attachement PdfAttachment wordfile = new PdfAttachment("Stock.docx", file); wordfile.FileName = "Stock.docx"; file = new FileStream(dataPath + "Chart.xlsx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Creating the attachement PdfAttachment excelfile = new PdfAttachment("Chart.xlsx", file); excelfile.FileName = "Chart.xlsx"; //Setting the startup document to view document.PortfolioInformation.StartupDocument = pdfFile; //Adding the attachment into document document.Attachments.Add(pdfFile); document.Attachments.Add(wordfile); document.Attachments.Add(excelfile); //Adding new page into the document document.Pages.Add(); //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); document.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Close the PDF document. document.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "Portfolio.pdf"; return(fileStreamResult); }
public ActionResult CreateDocument() { //Creates a new PDF document PdfDocument document = new PdfDocument(); //Adds page settings document.PageSettings.Orientation = PdfPageOrientation.Portrait; document.PageSettings.Margins.All = 50; //Adds a page to the document PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; RectangleF bounds = new RectangleF(); if (person.photo != null) { //Loads the image as stream System.Drawing.Image img = System.Drawing.Image.FromFile(@person.photo.ImagePath); double perc; perc = 200.0 / img.Width; float newHeight = (float)(img.Height * perc); FileStream imageStream = new FileStream(person.photo.ImagePath, FileMode.Open, FileAccess.Read); bounds = new RectangleF(250, 0, 200, newHeight); PdfImage image = PdfImage.FromStream(imageStream); //Draws the image to the PDF page page.Graphics.DrawImage(image, bounds); } PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); bounds = new RectangleF(0, bounds.Bottom + 90, graphics.ClientSize.Width, 30); //Draws a rectangle to place the heading in that region. graphics.DrawRectangle(solidBrush, bounds); //Creates a font for adding the heading in the page PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14); //Creates a text element to add the invoice number PdfTextElement element = new PdfTextElement("Personal Information", subHeadingFont); element.Brush = PdfBrushes.White; //Draws the heading on the page PdfLayoutResult result = element.Draw(page, new PointF(10, bounds.Top + 8)); string name = person.personalInfo.FirstName + " " + person.personalInfo.LastName; SizeF textSize = subHeadingFont.MeasureString(name); PointF textPosition = new PointF(graphics.ClientSize.Width - textSize.Width - 10, result.Bounds.Y); graphics.DrawString(name, subHeadingFont, element.Brush, textPosition); PdfFont timesRoman = new PdfStandardFont(PdfFontFamily.TimesRoman, 12); //Creates text elements to add the address and draw it to the page. element = new PdfTextElement(System.Environment.NewLine + "Phonenumber: " + person.personalInfo.Phonenumber + System.Environment.NewLine, timesRoman); element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0)); result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25)); PdfPen linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f); PointF startPoint = new PointF(0, result.Bounds.Bottom + 3); PointF endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3); //Draws a line at the bottom of the address graphics.DrawLine(linePen, startPoint, endPoint); element = new PdfTextElement(System.Environment.NewLine + "Email: " + person.personalInfo.Email + System.Environment.NewLine, timesRoman); element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0)); result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25)); linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f); startPoint = new PointF(0, result.Bounds.Bottom + 3); endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3); //Draws a line at the bottom of the address graphics.DrawLine(linePen, startPoint, endPoint); DateTime strDate = new DateTime(person.personalInfo.BirthDay.Year, person.personalInfo.BirthDay.Month, person.personalInfo.BirthDay.Day); element = new PdfTextElement(System.Environment.NewLine + "BirthDay: " + person.personalInfo.BirthDay.ToString("d") + System.Environment.NewLine, timesRoman); element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0)); result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25)); linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f); startPoint = new PointF(0, result.Bounds.Bottom + 3); endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3); //Draws a line at the bottom of the address graphics.DrawLine(linePen, startPoint, endPoint); element = new PdfTextElement(System.Environment.NewLine + "Location: " + person.personalInfo.City + System.Environment.NewLine, timesRoman); element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0)); result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25)); linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f); startPoint = new PointF(0, result.Bounds.Bottom + 3); endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3); //Draws a line at the bottom of the address graphics.DrawLine(linePen, startPoint, endPoint); if (!person.personalInfo.Skills.Contains("Enter text here...")) { element = new PdfTextElement(System.Environment.NewLine + "Skills: " + person.personalInfo.Skills + System.Environment.NewLine, timesRoman); element.Brush = new PdfSolidBrush(new PdfColor(1, 0, 0)); result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25)); linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f); startPoint = new PointF(0, result.Bounds.Bottom + 3); endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3); //Draws a line at the bottom of the address graphics.DrawLine(linePen, startPoint, endPoint); } DataTable Details; PdfGrid grid; PdfGridCellStyle cellStyle; PdfGridRow header; PdfGridCellStyle headerStyle = new PdfGridCellStyle(); PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat(); PdfGridLayoutResult gridResult; if (person.gainedEducation != null && person.gainedEducation.Count > 0) { //Creates the datasource for the table Details = new DataTable(); Details = CreateDataTable(person.gainedEducation); //Creates a PDF grid grid = new PdfGrid(); //Adds the data source grid.DataSource = Details; //Creates the grid cell styles cellStyle = new PdfGridCellStyle(); cellStyle.Borders.All = PdfPens.White; header = grid.Headers[0]; //Creates the header style headerStyle = new PdfGridCellStyle(); headerStyle.Borders.All = new PdfPen(new PdfColor(126, 151, 173)); headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); headerStyle.TextBrush = PdfBrushes.White; headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular); //Adds cell customizations for (int i = 0; i < header.Cells.Count; i++) { if (i == 0 || i == 1) { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); } else { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); } } //Applies the header style header.ApplyStyle(headerStyle); cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f); cellStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f); cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(131, 130, 136)); //Creates the layout format for grid layoutFormat = new PdfGridLayoutFormat(); // Creates layout format settings to allow the table pagination layoutFormat.Layout = PdfLayoutType.Paginate; //Draws the grid to the PDF page. gridResult = grid.Draw(page, new RectangleF (new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 50)), layoutFormat); page = document.Pages.Add(); element = new PdfTextElement(" ", subHeadingFont); element.Brush = PdfBrushes.White; graphics = page.Graphics; result = element.Draw(page, new PointF(10, 10)); } if (person.Languages != null && person.Languages.Count > 0) { Details = new DataTable(); //Creates the datasource for the table Details = CreateDataTable(person.Languages); //Creates a PDF grid grid = new PdfGrid(); //Adds the data source grid.DataSource = Details; //Creates the grid cell styles cellStyle = new PdfGridCellStyle(); cellStyle.Borders.All = PdfPens.White; header = grid.Headers[0]; //Creates the header style headerStyle = new PdfGridCellStyle(); headerStyle.Borders.All = new PdfPen(new PdfColor(126, 151, 173)); headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); headerStyle.TextBrush = PdfBrushes.White; headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular); //Adds cell customizations for (int i = 0; i < header.Cells.Count; i++) { if (i == 0 || i == 1) { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); } else { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); } } //Applies the header style header.ApplyStyle(headerStyle); cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f); cellStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f); cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(131, 130, 136)); //Creates the layout format for grid layoutFormat = new PdfGridLayoutFormat(); // Creates layout format settings to allow the table pagination layoutFormat.Layout = PdfLayoutType.Paginate; //Draws the grid to the PDF page. gridResult = grid.Draw(page, new RectangleF (new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 50)), layoutFormat); page = document.Pages.Add(); element = new PdfTextElement(" ", subHeadingFont); element.Brush = PdfBrushes.White; graphics = page.Graphics; result = element.Draw(page, new PointF(10, 10)); } if (person.gainedExperience != null && person.gainedExperience.Count > 0) { Details = new DataTable(); //Creates the datasource for the table Details = CreateDataTable(person.gainedExperience); //Creates a PDF grid grid = new PdfGrid(); //Adds the data source grid.DataSource = Details; //Creates the grid cell styles cellStyle = new PdfGridCellStyle(); cellStyle.Borders.All = PdfPens.White; header = grid.Headers[0]; //Creates the header style headerStyle = new PdfGridCellStyle(); headerStyle.Borders.All = new PdfPen(new PdfColor(126, 151, 173)); headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); headerStyle.TextBrush = PdfBrushes.White; headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular); //Adds cell customizations for (int i = 0; i < header.Cells.Count; i++) { if (i == 0 || i == 1) { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); } else { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); } } //Applies the header style header.ApplyStyle(headerStyle); cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f); cellStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f); cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(131, 130, 136)); //Creates the layout format for grid layoutFormat = new PdfGridLayoutFormat(); // Creates layout format settings to allow the table pagination layoutFormat.Layout = PdfLayoutType.Paginate; //Draws the grid to the PDF page. gridResult = grid.Draw(page, new RectangleF (new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 50)), layoutFormat); } //FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite); ////Save and close the PDF document //document.Save(fileStream); ////document.Close(true); MemoryStream stream = new MemoryStream(); document.Save(stream); //If the position is not set to '0' then the PDF will be empty. stream.Position = 0; //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); fileStreamResult.FileDownloadName = "YourCV.pdf"; return(fileStreamResult); ////Create a new PDF document //PdfDocument document = new PdfDocument(); ////Add a page to the document //PdfPage page = document.Pages.Add(); ////Create PDF graphics for the page //PdfGraphics graphics = page.Graphics; ////Set the standard font //PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20); ////Draw the text //graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0)); ////Saving the PDF to the MemoryStream //MemoryStream stream = new MemoryStream(); //document.Save(stream); ////If the position is not set to '0' then the PDF will be empty. //stream.Position = 0; ////Download the PDF document in the browser. //FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); //fileStreamResult.FileDownloadName = "YourCV.pdf"; //return fileStreamResult; }
public IActionResult Index() { //Creates a new PDF document PdfDocument document = new PdfDocument(); //Adds page settings document.PageSettings.Orientation = PdfPageOrientation.Landscape; document.PageSettings.Margins.All = 50; //Adds a page to the document PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; //Loads the image as stream FileStream imageStream = new FileStream("logo.png", FileMode.Open, FileAccess.Read); RectangleF bounds = new RectangleF(176, 0, 390, 130); PdfImage image = PdfImage.FromStream(imageStream); //Draws the image to the PDF page page.Graphics.DrawImage(image, bounds); PdfBrush solidBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); bounds = new RectangleF(0, bounds.Bottom + 90, graphics.ClientSize.Width, 30); //Draws a rectangle to place the heading in that region. graphics.DrawRectangle(solidBrush, bounds); //Creates a font for adding the heading in the page PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14); //Creates a text element to add the invoice number PdfTextElement element = new PdfTextElement("Purchase Order", subHeadingFont); element.Brush = PdfBrushes.White; //Draws the heading on the page PdfLayoutResult result = element.Draw(page, new PointF(10, bounds.Top + 8)); string currentDate = "DATE " + DateTime.Now.ToString("MM/dd/yyyy"); //Measures the width of the text to place it in the correct location SizeF textSize = subHeadingFont.MeasureString(currentDate); PointF textPosition = new PointF(graphics.ClientSize.Width - textSize.Width - 10, result.Bounds.Y); //Draws the date by using DrawString method graphics.DrawString(currentDate, subHeadingFont, element.Brush, textPosition); PdfFont timesRoman = new PdfStandardFont(PdfFontFamily.TimesRoman, 10); //Creates text elements to add the address and draw it to the page. element = new PdfTextElement("BILL TO ", timesRoman); element.Brush = new PdfSolidBrush(new PdfColor(126, 155, 203)); result = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25)); PdfPen linePen = new PdfPen(new PdfColor(126, 151, 173), 0.70f); PointF startPoint = new PointF(0, result.Bounds.Bottom + 3); PointF endPoint = new PointF(graphics.ClientSize.Width, result.Bounds.Bottom + 3); //Draws a line at the bottom of the address graphics.DrawLine(linePen, startPoint, endPoint); //Creates the datasource for the table var invoiceDetails = GetProductDetailsAsDataTable(); //Creates a PDF grid PdfGrid grid = new PdfGrid(); //Adds the data source grid.DataSource = invoiceDetails; //Creates the grid cell styles PdfGridCellStyle cellStyle = new PdfGridCellStyle(); cellStyle.Borders.All = PdfPens.White; PdfGridRow header = grid.Headers[0]; //Creates the header style PdfGridCellStyle headerStyle = new PdfGridCellStyle(); headerStyle.Borders.All = new PdfPen(new PdfColor(126, 151, 173)); headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 151, 173)); headerStyle.TextBrush = PdfBrushes.White; headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Regular); //Adds cell customizations for (int i = 0; i < header.Cells.Count; i++) { if (i == 0 || i == 1) { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle); } else { header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle); } } //Applies the header style header.ApplyStyle(headerStyle); cellStyle.Borders.Bottom = new PdfPen(new PdfColor(217, 217, 217), 0.70f); cellStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f); cellStyle.TextBrush = new PdfSolidBrush(new PdfColor(131, 130, 136)); //Creates the layout format for grid PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat(); // Creates layout format settings to allow the table pagination layoutFormat.Layout = PdfLayoutType.Paginate; //Draws the grid to the PDF page. PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(graphics.ClientSize.Width, graphics.ClientSize.Height - 100)), layoutFormat); //Save the PDF document to stream MemoryStream ms = new MemoryStream(); document.Save(ms); document.Close(true); ms.Position = 0; FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "Sample.pdf"; return(fileStreamResult); }
public FileStreamResult StyleSheet() { string controller = Crypto.Decrypt(Request.Params[ResourceDispatchParamControllerKey], ResourceDispatcherController.ResourceDispatchCryptoPasswordKey); string cacheKeyCss = this.GenerateCacheKey(controller, MediaType.stylesheet); if (controller == ResourceDispatcherController.ResourceDispatchParamCommonKey) { cacheKeyCss = "Common.css"; } if (!this.FileIsCached(cacheKeyCss)) { StringBuilder sb = new StringBuilder(); if (controller == ResourceDispatcherController.ResourceDispatchParamCommonKey) { sb.Append(System.IO.File.ReadAllText(Server.MapPath(string.Format("{0}{1}", ApplicationConfiguration.ClientResourcesSettingsSection.CDN_CSS_VirtualRoot, ApplicationConfiguration.ClientResourcesSettingsSection.CDN_CSS_CommonFileName(MvcApplication.Version))))); } else { sb.Append(new Template_T4_Runtime_CSS_ControllerStylesheets() { Session = new Dictionary<string, object>() { { ResourceDispatcherController.TTSessionContext_ControllerType, Type.GetType(controller) } } }.TransformText()); } this.FileSetCache(sb, cacheKeyCss, MediaType.stylesheet); } FileStreamResult fsr = new FileStreamResult(new MemoryStream(UTF8Encoding.UTF8.GetBytes((string)this._objCacheManager.Get(cacheKeyCss))), "text/css"); return fsr; }
public JsonResult GeneratePreBill(BillRequest billRequest) { bool isEnglishBilling; var preBill = _billRepo.GeneratePreBill(billRequest, out isEnglishBilling); //Report setup var details = preBill.BillDetails.Select(d => new { BillDetailType = Convert.ToInt32(d.BillDetailType), FixedAmount = d.FixedAmount, UnitRate = d.UnitRate, Quantity = d.Quantity, Subtotal = d.Subtotal, Description = d.Description, TaxesAmount = d.TaxesAmount }).ToList(); string basePath = _hostingEnvironment.ContentRootPath; string fullPath = basePath + @"/Reports/Bill.rdlc"; FileStream inputStream = new FileStream(fullPath, FileMode.Open, FileAccess.Read); ReportDataSourceCollection dataSources = new ReportDataSourceCollection(); dataSources.Add(new ReportDataSource { Name = "BillDataSet", Value = details }); Syncfusion.ReportWriter.ReportWriter writer = new Syncfusion.ReportWriter.ReportWriter(inputStream, dataSources); //Setting up the parameters List <ReportParameter> parameters = new List <ReportParameter>(); //IsEnglish ReportParameter isEnglishParam = new ReportParameter(); isEnglishParam.Name = "IsEnglish"; isEnglishParam.Values = new List <string>() { isEnglishBilling ? "1" : "0" }; //IsBilled ReportParameter isBilledParam = new ReportParameter(); isBilledParam.Name = "IsBilled"; isBilledParam.Values = new List <string>() { "0" }; //ClientName ReportParameter clientNameParam = new ReportParameter(); clientNameParam.Name = "ClientName"; clientNameParam.Values = new List <string>() { preBill.BillName }; //BillingPeriod string culture = isEnglishBilling ? "en" : "es"; string billingPeriod = $"{CultureInfo.GetCultureInfoByIetfLanguageTag(culture).DateTimeFormat.GetMonthName(DateTime.UtcNow.AddHours(-6).Month)} - {preBill.BillYear}"; ReportParameter billingPeriodParam = new ReportParameter(); billingPeriodParam.Name = "BillingPeriod"; billingPeriodParam.Values = new List <string>() { billingPeriod }; //Subtotal ReportParameter subTotalExpenseParam = new ReportParameter(); subTotalExpenseParam.Name = "Subtotal"; subTotalExpenseParam.Values = new List <string>() { preBill.BillSubtotal.ToString() }; //Discount ReportParameter discountParam = new ReportParameter(); discountParam.Name = "Discount"; discountParam.Values = new List <string>() { preBill.BillDiscount.ToString() }; //Taxes ReportParameter taxesParam = new ReportParameter(); taxesParam.Name = "Taxes"; taxesParam.Values = new List <string>() { preBill.Taxes.ToString() }; //TotalExpense ReportParameter totalParam = new ReportParameter(); totalParam.Name = "Total"; totalParam.Values = new List <string>() { preBill.Total.ToString() }; //TotalExpense ReportParameter billDateParam = new ReportParameter(); billDateParam.Name = "BillDate"; billDateParam.Values = new List <string>() { preBill.BillDate.ToString("dd/MM/yyyy") }; parameters.Add(isEnglishParam); parameters.Add(isBilledParam); parameters.Add(clientNameParam); parameters.Add(billingPeriodParam); parameters.Add(subTotalExpenseParam); parameters.Add(discountParam); parameters.Add(taxesParam); parameters.Add(totalParam); parameters.Add(billDateParam); writer.SetParameters(parameters); writer.ReportProcessingMode = ProcessingMode.Local; MemoryStream memoryStream = new MemoryStream(); writer.Save(memoryStream, WriterFormat.PDF); memoryStream.Position = 0; FileStreamResult fileStreamResult = new FileStreamResult(memoryStream, "application/pdf"); fileStreamResult.FileDownloadName = $"FacturaCliente{preBill.BillName}deMes{preBill.BillMonth}YAño{preBill.BillYear}.pdf"; return(Json(new { result = memoryStream.ConvertToBase64() })); }
public ActionResult InteractiveFeatures(string InsideBrowser) { #region Field Definitions document = new PdfDocument(); document.PageSettings.Margins.All = 0; document.PageSettings.Size = new SizeF(PdfPageSize.A4.Width, 600); interactivePage = document.Pages.Add(); PdfGraphics g = interactivePage.Graphics; RectangleF rect = new RectangleF(0, 0, interactivePage.Graphics.ClientSize.Width, 100); PdfBrush whiteBrush = new PdfSolidBrush(white); PdfPen whitePen = new PdfPen(white, 5); PdfBrush purpleBrush = new PdfSolidBrush(new PdfColor(255, 158, 0, 160)); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 25); Syncfusion.Drawing.Color maroonColor = Color.FromArgb(255, 188, 32, 60); Syncfusion.Drawing.Color orangeColor = Color.FromArgb(255, 255, 167, 73); #endregion #region Header g.DrawRectangle(purpleBrush, rect); g.DrawPie(whitePen, whiteBrush, new RectangleF(-20, 35, 700, 200), 20, -180); g.DrawRectangle(whiteBrush, new RectangleF(0, 99.5f, 700, 200)); g.DrawString("Invoice", new PdfStandardFont(PdfFontFamily.TimesRoman, 24), PdfBrushes.White, new PointF(500, 10)); string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; //Read the file FileStream file = new FileStream(dataPath + "AdventureCycle.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); g.DrawImage(PdfImage.FromStream(file), new RectangleF(100, 70, 390, 130)); #endregion #region Body //Invoice Number Random invoiceNumber = new Random(); g.DrawString("Invoice No: " + invoiceNumber.Next().ToString(), new PdfStandardFont(PdfFontFamily.Helvetica, 14), new PdfSolidBrush(maroonColor), new PointF(50, 210)); g.DrawString("Date: ", new PdfStandardFont(PdfFontFamily.Helvetica, 14), new PdfSolidBrush(maroonColor), new PointF(350, 210)); //Current Date PdfTextBoxField textBoxField = new PdfTextBoxField(interactivePage, "date"); textBoxField.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); textBoxField.Bounds = new RectangleF(384, 204, 150, 30); textBoxField.ForeColor = new PdfColor(maroonColor); textBoxField.ReadOnly = true; document.Actions.AfterOpen = new PdfJavaScriptAction(@"var newdate = new Date(); var thisfieldis = this.getField('date'); var theday = util.printd('dddd',newdate); var thedate = util.printd('d',newdate); var themonth = util.printd('mmmm',newdate); var theyear = util.printd('yyyy',newdate); thisfieldis.strokeColor=color.transparent; thisfieldis.value = theday + ' ' + thedate + ', ' + themonth + ' ' + theyear ;"); document.Form.Fields.Add(textBoxField); //invoice table PdfLightTable table = new PdfLightTable(); table.Style.ShowHeader = true; g.DrawRectangle(new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(238, 238, 238, 248)), new RectangleF(50, 240, 500, 140)); //Header Style PdfCellStyle headerStyle = new PdfCellStyle(); headerStyle.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold); headerStyle.TextBrush = whiteBrush; headerStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center); headerStyle.BackgroundBrush = new PdfSolidBrush(orangeColor); headerStyle.BorderPen = new PdfPen(whiteBrush, 0); table.Style.HeaderStyle = headerStyle; //Cell Style PdfCellStyle bodyStyle = new PdfCellStyle(); bodyStyle.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 10); bodyStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Left); bodyStyle.BorderPen = new PdfPen(whiteBrush, 0); table.Style.DefaultStyle = bodyStyle; table.DataSource = GetProductReport(_hostingEnvironment.WebRootPath); table.Columns[0].Width = 90; table.Columns[1].Width = 160; table.Columns[3].Width = 100; table.Columns[4].Width = 65; table.Style.CellPadding = 3; table.BeginCellLayout += table_BeginCellLayout; PdfLightTableLayoutResult result = table.Draw(interactivePage, new RectangleF(50, 240, 500, 140)); g.DrawString("Grand Total:", new PdfStandardFont(PdfFontFamily.Helvetica, 12), new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(255, 255, 167, 73)), new PointF(result.Bounds.Right - 150, result.Bounds.Bottom)); CreateTextBox(interactivePage, "GrandTotal", "Grand Total", new RectangleF(result.Bounds.Width - 15, result.Bounds.Bottom - 2, 66, 18), true, ""); //Send to Server PdfButtonField sendButton = new PdfButtonField(interactivePage, "OrderOnline"); sendButton.Bounds = new RectangleF(200, result.Bounds.Bottom + 70, 80, 25); sendButton.BorderColor = white; sendButton.BackColor = maroonColor; sendButton.ForeColor = white; sendButton.Text = "Order Online"; PdfSubmitAction submitAction = new PdfSubmitAction("http://stevex.net/dump.php"); submitAction.DataFormat = SubmitDataFormat.Html; sendButton.Actions.MouseUp = submitAction; document.Form.Fields.Add(sendButton); //Order by Mail PdfButtonField sendMail = new PdfButtonField(interactivePage, "sendMail"); sendMail.Bounds = new RectangleF(300, result.Bounds.Bottom + 70, 80, 25); sendMail.Text = "Order By Mail"; sendMail.BorderColor = white; sendMail.BackColor = maroonColor; sendMail.ForeColor = white; // Create a javascript action. PdfJavaScriptAction javaAction = new PdfJavaScriptAction("address = app.response(\"Enter an e-mail address.\",\"SEND E-MAIL\",\"\");" + "var aSubmitFields = [];" + "for( var i = 0 ; i < this.numFields; i++){" + "aSubmitFields[i] = this.getNthFieldName(i);" + "}" + "if (address){ cmdLine = \"mailto:\" + address;this.submitForm(cmdLine,true,false,aSubmitFields);}"); sendMail.Actions.MouseUp = javaAction; document.Form.Fields.Add(sendMail); //Print PdfButtonField printButton = new PdfButtonField(interactivePage, "print"); printButton.Bounds = new RectangleF(400, result.Bounds.Bottom + 70, 80, 25); printButton.BorderColor = white; printButton.BackColor = maroonColor; printButton.ForeColor = white; printButton.Text = "Print"; printButton.Actions.MouseUp = new PdfJavaScriptAction("this.print (true); "); document.Form.Fields.Add(printButton); file = new FileStream(dataPath + "Product Catalog.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PdfAttachment attachment = new PdfAttachment("Product Catalog.pdf", file); attachment.ModificationDate = DateTime.Now; attachment.Description = "Specification"; document.Attachments.Add(attachment); //Open Specification PdfButtonField openSpecificationButton = new PdfButtonField(interactivePage, "openSpecification"); openSpecificationButton.Bounds = new RectangleF(50, result.Bounds.Bottom + 20, 87, 15); openSpecificationButton.TextAlignment = PdfTextAlignment.Left; openSpecificationButton.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 10); openSpecificationButton.BorderStyle = PdfBorderStyle.Underline; openSpecificationButton.BorderColor = orangeColor; openSpecificationButton.BackColor = new PdfColor(255, 255, 255); openSpecificationButton.ForeColor = orangeColor; openSpecificationButton.Text = "Open Specification"; openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Product Catalog.pdf', nLaunch: 2 });"); document.Form.Fields.Add(openSpecificationButton); RectangleF uriAnnotationRectangle = new RectangleF(interactivePage.Graphics.ClientSize.Width - 160, interactivePage.Graphics.ClientSize.Height - 30, 80, 20); PdfTextWebLink linkAnnot = new PdfTextWebLink(); linkAnnot.Url = "http://www.adventure-works.com"; linkAnnot.Text = "http://www.adventure-works.com"; linkAnnot.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 8); linkAnnot.Brush = PdfBrushes.White; linkAnnot.DrawTextWebLink(interactivePage, uriAnnotationRectangle.Location); #endregion #region Footer g.DrawRectangle(purpleBrush, new RectangleF(0, interactivePage.Graphics.ClientSize.Height - 100, interactivePage.Graphics.ClientSize.Width, 100)); g.DrawPie(whitePen, whiteBrush, new RectangleF(-20, interactivePage.Graphics.ClientSize.Height - 250, 700, 200), 0, 180); #endregion //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); document.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Close the PDF document. document.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "Interactive features.pdf"; return(fileStreamResult); }
public ActionResult Conformance(string InsideBrowser, string radioButton) { string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; PdfDocument document = null; if (radioButton == "Pdf_A1B") { //Create a new document with PDF/A standard. document = new PdfDocument(PdfConformanceLevel.Pdf_A1B); } else if (radioButton == "Pdf_A2B") { document = new PdfDocument(PdfConformanceLevel.Pdf_A2B); } else if (radioButton == "Pdf_A3B") { document = new PdfDocument(PdfConformanceLevel.Pdf_A3B); //Read the file FileStream file = new FileStream(dataPath + "Text1.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Creates an attachment PdfAttachment attachment = new PdfAttachment("Text1.txt", file); attachment.Relationship = PdfAttachmentRelationship.Alternative; attachment.ModificationDate = DateTime.Now; attachment.Description = "PDF_A"; attachment.MimeType = "application/xml"; document.Attachments.Add(attachment); } //Add a page to the document. PdfPage page = document.Pages.Add(); //Create PDF graphics for the page. PdfGraphics graphics = page.Graphics; FileStream imageStream = new FileStream(dataPath + "AdventureCycle.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Load the image from the disk. PdfImage img = PdfImage.FromStream(imageStream); //Draw the image in the specified location and size. graphics.DrawImage(img, new RectangleF(150, 30, 200, 100)); //Create font FileStream fontFileStream = new FileStream(dataPath + "arial.ttf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PdfFont font = new PdfTrueTypeFont(fontFileStream, 14); PdfTextElement textElement = new PdfTextElement("Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based," + " is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, " + "European and Asian commercial markets. While its base operation is located in Bothell, Washington with 290 employees, several regional" + " sales teams are located throughout their market base.") { Font = font }; PdfLayoutResult layoutResult = textElement.Draw(page, new RectangleF(0, 150, page.GetClientSize().Width, page.GetClientSize().Height)); MemoryStream stream = new MemoryStream(); document.Save(stream); document.Close(); stream.Position = 0; //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); fileStreamResult.FileDownloadName = "PDF_A.pdf"; return(fileStreamResult); }
public ActionResult export_email_addresses(FormCollection collection) { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters string returnUrl = collection["returnUrl"]; ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get form values Int32 languageId = Convert.ToInt32(collection["selectLanguage"]); // Create a stream writer MemoryStream outputStream = null; // Create the file stream result FileStreamResult fileStreamResult = null; try { // Get email addresses string emailAddresses = Customer.GetEmailAddresses(languageId, false); // Get the stream byte[] streamData = System.Text.Encoding.UTF8.GetBytes(emailAddresses); // Write to the stream outputStream = new MemoryStream(streamData); // Go to the beginning of the output stream outputStream.Seek(0, SeekOrigin.Begin); // Create the file stream result fileStreamResult = new FileStreamResult(outputStream, "text/plain") { FileDownloadName = "email_addresses.txt" }; } catch (Exception exception) { string exceptionMessage = ""; exceptionMessage = exception.Message; } // Return the text file return fileStreamResult; } // End of the export_email_addresses method
public async Task <IActionResult> Export(int courseId) { // Get the course to be exported Course course = _courseService.GetCourse(courseId); // Create export directory under the courses ID CreateExportDirectory(course.Id); // Get all scenes under the course IEnumerable <Scene> scenes = _sceneService.GetScenesWithCourseId(courseId); // Set the scene index to 0 int sceneIndex = 0; // cycle through each scene foreach (Scene item in scenes) { // Get all the vr Objects in the scene IEnumerable <VRObject> vRObjects = _VRObjectService.GetVROBjectsWithSceneId(item.Id); // for each vr object, if it's video or audio, find the file in the MEDIA folder and move it to the scorm content folder foreach (VRObject v in vRObjects) { if (v.ObjectType == "VideoObject" || v.ObjectType == "AudioObject") { MoveMediaFileToScormContentFolder(v.ObjectType, v.Value, courseId); } } // Getting all the hotspot, question and responses in the scene IEnumerable <VRHotspot> vRHotspots = _VRObjectService.GetVRHotspotsWithSceneId(item.Id); IEnumerable <VRQuestionCard> vRQuestionCards = _VRObjectService.GetVRQuestionsWithSceneId(item.Id); IEnumerable <VRQuestionResponse> tempResponses = new List <VRQuestionResponse>(); List <VRQuestionResponse> responses = new List <VRQuestionResponse>(); if (vRQuestionCards != null && vRQuestionCards.Count() > 0) { foreach (VRQuestionCard q in vRQuestionCards) { // stores the individual question's responses in temp responses // This is reset each iteration of the foreach loop tempResponses = _VRObjectService.GetVRQuestionresponsesWithQuestionId(q.Id); foreach (VRQuestionResponse r in tempResponses) { // iterate through the tempResponses to add the response to the responses to be exported responses.Add(r); } } } // Get the current scenes background image VRBackground Image = _VRBackgroundService.getBackgroundImageObjectWithSceneId(item.Id); // Export Model to be passed to export.cshtml ExportModel eModel = new ExportModel() { backgroundImage = Image, VRObjects = vRObjects, VRHotSpots = vRHotspots, VRQuestionCards = vRQuestionCards, VRQuestionResponses = responses }; // Returns a string of the Export.cshtml after it has been populated with the above data string exportView = await this.RenderViewToStringAsync("/Views/Export/Export.cshtml", eModel); // Writes the above data to a html file for each scene WriteToFile(exportView, item.CourseId, sceneIndex); sceneIndex++; } // once the loop is complete, zip it as per the xAPI standard wrapper docs ZipScorm(course.Id); // Relocate from the ZIPS to be downloaded by the user FileStreamResult fileStreamResult = null; try { string path = "C:/OPT/ZIPS/" + courseId + ".zip"; FileStream fileStreamInput = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Delete); fileStreamResult = new FileStreamResult(fileStreamInput, "APPLICATION/octet-stream"); fileStreamResult.FileDownloadName = "yourScorm.zip"; } catch (Exception e) { Console.WriteLine(e); } finally { // Ensure the zip is always deleted so the course can be downlaoded multiple times DeleteExportedZip(course.Id); } return(fileStreamResult); }
public FileStreamResult ToExcel(IQueryable query) { var columns = GetProperties(query.ElementType); var stream = new MemoryStream(); using (var document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook)) { var workbookPart = document.AddWorkbookPart(); workbookPart.Workbook = new Workbook(); var worksheetPart = workbookPart.AddNewPart <WorksheetPart>(); worksheetPart.Worksheet = new Worksheet(); var workbookStylesPart = workbookPart.AddNewPart <WorkbookStylesPart>(); GenerateWorkbookStylesPartContent(workbookStylesPart); var sheets = workbookPart.Workbook.AppendChild(new Sheets()); var sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" }; sheets.Append(sheet); workbookPart.Workbook.Save(); var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData()); var headerRow = new Row(); foreach (var column in columns) { headerRow.Append(new Cell() { CellValue = new CellValue(column.Key), DataType = new EnumValue <CellValues>(CellValues.String) }); } sheetData.AppendChild(headerRow); foreach (var item in query) { var row = new Row(); foreach (var column in columns) { var value = GetValue(item, column.Key); var stringValue = $"{value}"; var cell = new Cell(); var underlyingType = column.Value.IsGenericType && column.Value.GetGenericTypeDefinition() == typeof(Nullable <>) ? Nullable.GetUnderlyingType(column.Value) : column.Value; var typeCode = Type.GetTypeCode(underlyingType); if (typeCode == TypeCode.DateTime) { if (stringValue != string.Empty) { cell.CellValue = new CellValue() { Text = DateTime.Parse(stringValue).ToOADate().ToString() }; cell.StyleIndex = (UInt32Value)1U; } } else if (typeCode == TypeCode.Boolean) { cell.CellValue = new CellValue(stringValue.ToLower()); cell.DataType = new EnumValue <CellValues>(CellValues.Boolean); } else if (IsNumeric(typeCode)) { cell.CellValue = new CellValue(stringValue); cell.DataType = new EnumValue <CellValues>(CellValues.Number); } else { cell.CellValue = new CellValue(stringValue); cell.DataType = new EnumValue <CellValues>(CellValues.String); } row.Append(cell); } sheetData.AppendChild(row); } workbookPart.Workbook.Save(); } if (stream?.Length > 0) { stream.Seek(0, SeekOrigin.Begin); } var result = new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); result.FileDownloadName = $"{query.ElementType}.xls"; return(result); }
// Download file(s) or folder(s) public virtual FileStreamResult Download(string path, string[] names, FileManagerDirectoryContent[] data) { FileStreamResult fileStreamResult = null; List <String> files = new List <String> { }; DriveService service = GetService(); foreach (FileManagerDirectoryContent item in data) { File fileProperties = service.Files.Get(item.Id).Execute(); byte[] fileContent = null; if (item.IsFile) { fileContent = service.HttpClient.GetByteArrayAsync(fileProperties.DownloadUrl).Result; if (System.IO.File.Exists(Path.Combine(Path.GetTempPath(), item.Name))) { System.IO.File.Delete(Path.Combine(Path.GetTempPath(), item.Name)); } using (Stream file = System.IO.File.OpenWrite(Path.Combine(Path.GetTempPath(), item.Name))) { file.Write(fileContent, 0, fileContent.Length); } } else { Directory.CreateDirectory(Path.GetTempPath() + item.Name); } if (files.IndexOf(item.Name) == -1) { files.Add(item.Name); } } if (files.Count == 1 && data[0].IsFile) { try { FileStream fileStreamInput = new FileStream(Path.Combine(Path.GetTempPath(), files[0]), FileMode.Open, FileAccess.Read); fileStreamResult = new FileStreamResult(fileStreamInput, "APPLICATION/octet-stream"); fileStreamResult.FileDownloadName = files[0]; } catch (Exception ex) { throw ex; } } else { ZipArchiveEntry zipEntry; ZipArchive archive; using (archive = ZipFile.Open(Path.Combine(Path.GetTempPath(), "files.zip"), ZipArchiveMode.Update)) { for (int i = 0; i < files.Count; i++) { if (!data[i].IsFile) { zipEntry = archive.CreateEntry(data[i].Name + "/"); DownloadFolderFiles(data[i].Id, data[i].Name, archive, zipEntry); } else { zipEntry = archive.CreateEntryFromFile(Path.GetTempPath() + files[i], files[i], CompressionLevel.Fastest); } } archive.Dispose(); FileStream fileStreamInput = new FileStream(Path.Combine(Path.GetTempPath(), "files.zip"), FileMode.Open, FileAccess.Read, FileShare.Delete); fileStreamResult = new FileStreamResult(fileStreamInput, "APPLICATION/octet-stream"); fileStreamResult.FileDownloadName = "files.zip"; if (System.IO.File.Exists(Path.Combine(Path.GetTempPath(), "files.zip"))) { System.IO.File.Delete(Path.Combine(Path.GetTempPath(), "files.zip")); } } } return(fileStreamResult); }
public ActionResult BulletsLists(string InsideBrowser) { //Create a new PDf document PdfDocument document = new PdfDocument(); //Add a page PdfPage page = document.Pages.Add(); PdfGraphics graphics = page.Graphics; //Create a unordered list PdfUnorderedList list = new PdfUnorderedList(); //Set the marker style list.Marker.Style = PdfUnorderedMarkerStyle.Disk; //Create a font and write title PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold); graphics.DrawString("List Features", font, PdfBrushes.DarkBlue, new PointF(225, 10)); string[] products = { "Tools", "Grid", "Chart", "Edit", "Diagram", "XlsIO", "Grouping", "Calculate", "PDF", "HTMLUI", "DocIO" }; string[] IO = { "XlsIO", "PDF", "DocIO" }; font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Regular); graphics.DrawString("This sample demonstrates various features of bullets and lists. A list can be ordered and Unordered. Essential PDF provides support for creating and formatting ordered and unordered lists.", font, PdfBrushes.Black, new RectangleF(0, 50, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height)); //Create string format PdfStringFormat format = new PdfStringFormat(); format.LineSpacing = 10f; font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Bold); //Apply formattings to list list.Font = font; list.StringFormat = format; //Set list indent list.Indent = 10; //Add items to the list list.Items.Add("List of Essential Studio products"); list.Items.Add("IO products"); //Set text indent list.TextIndent = 10; //Create Ordered list as sublist of parent list PdfOrderedList subList = new PdfOrderedList(); subList.Marker.Brush = PdfBrushes.Black; subList.Indent = 20; list.Items[0].SubList = subList; //Set format for sub list font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Italic); subList.Font = font; subList.StringFormat = format; foreach (string s in products) { //Add items subList.Items.Add(string.Concat("Essential ", s)); } //Create unorderd sublist for the second item of parent list PdfUnorderedList SubsubList = new PdfUnorderedList(); SubsubList.Marker.Brush = PdfBrushes.Black; SubsubList.Indent = 20; list.Items[1].SubList = SubsubList; string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; //Read the file FileStream file = new FileStream(dataPath + "logo.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); PdfImage image = PdfImage.FromStream(file); font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Regular); SubsubList.Font = font; SubsubList.StringFormat = format; //Add subitems SubsubList.Items.Add("Essential PDF: It is a .NET library with the capability to produce Adobe PDF files. It features a full-fledged object model for the easy creation of PDF files from any .NET language. It does not use any external libraries and is built from scratch in C#. It can be used on the server side (ASP.NET or any other environment) or with Windows Forms applications. Essential PDF supports many features for creating a PDF document. Drawing Text, Images, Shapes, etc can be drawn easily in the PDF document."); SubsubList.Items.Add("Essential DocIO: It is a .NET library that can read and write Microsoft Word files. It features a full-fledged object model similar to the Microsoft Office COM libraries. It does not use COM interop and is built from scratch in C#. It can be used on systems that do not have Microsoft Word installed. Here are some of the most common questions that arise regarding the usage and functionality of Essential DocIO."); SubsubList.Items.Add("Essential XlsIO: It is a .NET library that can read and write Microsoft Excel files (BIFF 8 format). It features a full-fledged object model similar to the Microsoft Office COM libraries. It does not use COM interop and is built from scratch in C#. It can be used on systems that do not have Microsoft Excel installed, making it an excellent reporting engine for tabular data. "); //Set image as marker SubsubList.Marker.Image = image; //Draw list list.Draw(page, new RectangleF(0, 130, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height)); //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); document.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Close the PDF document. document.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "BulletsAndLists.pdf"; return(fileStreamResult); }
[NonAction] // Not really necessary on an ext method, but in case we ever move it to a Controller or Controll base class public static IActionResult Model(this ControllerBase c, object model) { PropertyInfo toResultProperty = null; // Used to detect more than one result property IActionResult result = null; var props = model.GetType().GetTypeInfo().GetProperties(); foreach (var p in props) { var toHeader = p.GetCustomAttribute(typeof(ToHeaderAttribute)) as ToHeaderAttribute; if (toHeader != null) { var headerName = toHeader.Name; if (string.IsNullOrEmpty(headerName)) { headerName = p.Name; } // if (LOG.IsEnabled(LogLevel.Debug)) // LOG.LogDebug($"Adding Header[{headerName}] replace=[{toHeader.Replace}]"); // TODO: Add support for string[]??? var headerValue = ConvertTo <string>(p.GetValue(model, null)); if (toHeader.Replace) { c.Response.Headers[headerName] = headerValue; } else { c.Response.Headers.Add(headerName, headerValue); } continue; } var toResult = p.GetCustomAttribute(typeof(ToResultAttribute)) as ToResultAttribute; if (toResult != null) { if (toResultProperty != null) { throw new InvalidOperationException("multiple Result-mapping attributes found"); } toResultProperty = p; var toResultType = p.PropertyType; if (typeof(IActionResult).IsAssignableFrom(toResultType)) { result = (IActionResult)p.GetValue(model, null); continue; } var contentType = toResult.ContentType; if (toResultType == typeof(byte[])) { var resultValue = (byte[])p.GetValue(model, null); result = new FileContentResult(resultValue, contentType ?? CONTENT_TYPE_OCTET_STREAM); continue; } if (typeof(Stream).IsAssignableFrom(toResultType)) { var resultValue = (Stream)p.GetValue(model, null); result = new FileStreamResult(resultValue, contentType ?? CONTENT_TYPE_OCTET_STREAM); continue; } if (typeof(FileInfo).IsAssignableFrom(toResultType)) { var resultValue = (FileInfo)p.GetValue(model, null); result = new PhysicalFileResult(resultValue.FullName, contentType ?? CONTENT_TYPE_OCTET_STREAM); continue; } if (typeof(string) == toResultType) { var resultValue = (string)p.GetValue(model, null); result = new ContentResult { Content = resultValue, ContentType = contentType }; continue; } var pValue = p.GetValue(model, null); if (pValue != null) { result = new JsonResult(pValue); } } } if (result == null) { result = new OkResult(); } return(result); }
public ActionResult DocumentSettings(string InsideBrowser) { //Create a new PDF Document. The pdfDoc object represents the PDF document. //This document has one page by default and additional pages have to be added. PdfDocument pdfDoc = new PdfDocument(); PdfPage page = pdfDoc.Pages.Add(); // Get xmp object. XmpMetadata xmp = pdfDoc.DocumentInformation.XmpMetadata; // XMP Basic Schema. BasicSchema basic = xmp.BasicSchema; basic.Advisory.Add("advisory"); basic.BaseURL = new Uri("http://google.com"); basic.CreateDate = DateTime.Now; basic.CreatorTool = "creator tool"; basic.Identifier.Add("identifier"); basic.Label = "label"; basic.MetadataDate = DateTime.Now; basic.ModifyDate = DateTime.Now; basic.Nickname = "nickname"; basic.Rating.Add(-25); //Setting various Document properties. pdfDoc.DocumentInformation.Title = "Document Properties Information"; pdfDoc.DocumentInformation.Author = "Syncfusion"; pdfDoc.DocumentInformation.Keywords = "PDF"; pdfDoc.DocumentInformation.Subject = "PDF demo"; pdfDoc.DocumentInformation.Producer = "Syncfusion Software"; pdfDoc.DocumentInformation.CreationDate = DateTime.Now; PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f); PdfFont boldFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold); PdfBrush brush = PdfBrushes.Black; PdfGraphics g = page.Graphics; PdfStringFormat format = new PdfStringFormat(); format.LineSpacing = 10f; g.DrawString("Press Ctrl+D to see Document Properties", boldFont, brush, 10, 10); g.DrawString("Basic Schema Xml:", boldFont, brush, 10, 50); g.DrawString(basic.XmlData.ToString(), font, brush, new RectangleF(10, 70, 500, 500), format); //Defines and set values for Custom metadata and add them to the Pdf document CustomSchema custom = new CustomSchema(xmp, "custom", "http://www.syncfusion.com/"); custom["Company"] = "Syncfusion"; custom["Website"] = "http://www.syncfusion.com/"; custom["Product"] = "Essential PDF"; //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); pdfDoc.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Close the PDF document. pdfDoc.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "DocumentSettings.pdf"; return(fileStreamResult); }
public void Show_GivenImage_ReturnsSameData() { FileStreamResult actResult = CallShow(photoId); CollectionAssert.AreEqual(GetHash(testImageStream), GetHash(actResult.FileStream)); }
public ActionResult AnnotationFlatten(string InsideBrowser, string checkboxFlatten) { //Creates a new PDF document. PdfDocument document = new PdfDocument(); //Creates a new page PdfPage page = document.Pages.Add(); document.PageSettings.SetMargins(0); //Create new PDF color PdfColor blackColor = new PdfColor(0, 0, 0); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f); PdfBrush brush = new PdfSolidBrush(blackColor); string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base."; page.Graphics.DrawString("Annotation with Comments and Reviews", font, brush, new PointF(30, 10)); page.Graphics.DrawString(text, font, brush, new RectangleF(30, 40, page.GetClientSize().Width - 60, 60)); string markupText = "North American, European and Asian commercial markets"; PdfTextMarkupAnnotation textMarkupAnnot = new PdfTextMarkupAnnotation("sample", "Highlight", markupText, new PointF(147, 63.5f), font); textMarkupAnnot.Author = "Annotation"; textMarkupAnnot.Opacity = 1.0f; textMarkupAnnot.Subject = "Comments and Reviews"; textMarkupAnnot.ModifiedDate = new DateTime(2015, 1, 18); textMarkupAnnot.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.Highlight; textMarkupAnnot.TextMarkupColor = new PdfColor(Color.Yellow); textMarkupAnnot.InnerColor = new PdfColor(Color.Red); textMarkupAnnot.Color = new PdfColor(Color.Yellow); if (checkboxFlatten == "Flatten") { textMarkupAnnot.Flatten = true; } //Create a new comment. PdfPopupAnnotation userQuery = new PdfPopupAnnotation(); userQuery.Author = "John"; userQuery.Text = "Can you please change South Asian to Asian?"; userQuery.ModifiedDate = new DateTime(2015, 1, 18); //Add comment to the annotation textMarkupAnnot.Comments.Add(userQuery); //Creates a new comment PdfPopupAnnotation userAnswer = new PdfPopupAnnotation(); userAnswer.Author = "Smith"; userAnswer.Text = "South Asian has changed as Asian"; userAnswer.ModifiedDate = new DateTime(2015, 1, 18); //Add comment to the annotation textMarkupAnnot.Comments.Add(userAnswer); //Creates a new review PdfPopupAnnotation userAnswerReview = new PdfPopupAnnotation(); userAnswerReview.Author = "Smith"; userAnswerReview.State = PdfAnnotationState.Completed; userAnswerReview.StateModel = PdfAnnotationStateModel.Review; userAnswerReview.ModifiedDate = new DateTime(2015, 1, 18); //Add review to the comment userAnswer.ReviewHistory.Add(userAnswerReview); //Creates a new review PdfPopupAnnotation userAnswerReviewJohn = new PdfPopupAnnotation(); userAnswerReviewJohn.Author = "John"; userAnswerReviewJohn.State = PdfAnnotationState.Accepted; userAnswerReviewJohn.StateModel = PdfAnnotationStateModel.Review; userAnswerReviewJohn.ModifiedDate = new DateTime(2015, 1, 18); //Add review to the comment userAnswer.ReviewHistory.Add(userAnswerReviewJohn); //Add annotation to the page page.Annotations.Add(textMarkupAnnot); RectangleF bounds = new RectangleF(350, 170, 80, 80); //Creates a new Circle annotation. PdfCircleAnnotation circleannotation = new PdfCircleAnnotation(bounds); circleannotation.InnerColor = new PdfColor(Color.Yellow); circleannotation.Color = new PdfColor(Color.Red); circleannotation.AnnotationFlags = PdfAnnotationFlags.Default; circleannotation.Author = "Syncfusion"; circleannotation.Subject = "CircleAnnotation"; circleannotation.ModifiedDate = new DateTime(2015, 1, 18); page.Annotations.Add(circleannotation); page.Graphics.DrawString("Circle Annotation", font, brush, new PointF(350, 130)); //Creates a new Ellipse annotation. PdfEllipseAnnotation ellipseannotation = new PdfEllipseAnnotation(new RectangleF(30, 150, 50, 100), "Ellipse Annotation"); ellipseannotation.Color = new PdfColor(Color.Red); ellipseannotation.InnerColor = new PdfColor(Color.Yellow); page.Graphics.DrawString("Ellipse Annotation", font, brush, new PointF(30, 130)); page.Annotations.Add(ellipseannotation); //Creates a new Square annotation. PdfSquareAnnotation squareannotation = new PdfSquareAnnotation(new RectangleF(30, 300, 80, 80)); squareannotation.Text = "SquareAnnotation"; squareannotation.InnerColor = new PdfColor(Color.Red); squareannotation.Color = new PdfColor(Color.Yellow); page.Graphics.DrawString("Square Annotation", font, brush, new PointF(30, 280)); page.Annotations.Add(squareannotation); //Creates a new Rectangle annotation. RectangleF rectannot = new RectangleF(350, 320, 100, 50); PdfRectangleAnnotation rectangleannotation = new PdfRectangleAnnotation(rectannot, "RectangleAnnotation"); rectangleannotation.InnerColor = new PdfColor(Color.Red); rectangleannotation.Color = new PdfColor(Color.Yellow); page.Graphics.DrawString("Rectangle Annotation", font, brush, new PointF(350, 280)); page.Annotations.Add(rectangleannotation); //Creates a new Line annotation. int[] points = new int[] { 400, 350, 550, 350 }; PdfLineAnnotation lineAnnotation = new PdfLineAnnotation(points, "Line Annoation is the one of the annotation type..."); lineAnnotation.Author = "Syncfusion"; lineAnnotation.Subject = "LineAnnotation"; lineAnnotation.ModifiedDate = new DateTime(2015, 1, 18); lineAnnotation.Text = "PdfLineAnnotation"; lineAnnotation.BackColor = new PdfColor(Color.Red); page.Graphics.DrawString("Line Annotation", font, brush, new PointF(400, 420)); page.Annotations.Add(lineAnnotation); //Creates a new Polygon annotation. int[] polypoints = new int[] { 50, 298, 100, 325, 200, 355, 300, 230, 180, 230 }; PdfPolygonAnnotation polygonannotation = new PdfPolygonAnnotation(polypoints, "PolygonAnnotation"); polygonannotation.Bounds = new RectangleF(30, 210, 300, 200); PdfPen pen = new PdfPen(Color.Red); polygonannotation.Text = "polygon"; polygonannotation.Color = new PdfColor(Color.Red); polygonannotation.InnerColor = new PdfColor(Color.LightPink); page.Graphics.DrawString("Polygon Annotation", font, brush, new PointF(50, 420)); page.Annotations.Add(polygonannotation); //Creates a new Freetext annotation. RectangleF freetextrect = new RectangleF(405, 645, 80, 30); PdfFreeTextAnnotation freeText = new PdfFreeTextAnnotation(freetextrect); freeText.MarkupText = "Free Text with Callouts"; freeText.TextMarkupColor = new PdfColor(Color.Green); freeText.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 7f); freeText.BorderColor = new PdfColor(Color.Blue); freeText.Border = new PdfAnnotationBorder(.5f); freeText.AnnotationFlags = PdfAnnotationFlags.Default; freeText.Text = "Free Text"; freeText.Color = new PdfColor(Color.Yellow); PointF[] Freetextpoints = { new PointF(365, 700), new PointF(379, 654), new PointF(405, 654) }; freeText.CalloutLines = Freetextpoints; page.Graphics.DrawString("FreeText Annotation", font, brush, new PointF(400, 610)); page.Annotations.Add(freeText); //Creates a new Ink annotation. List <float> linePoints = new List <float> { 72.919f, 136.376f, 72.264f, 136.376f, 62.446f, 142.922f, 61.137f, 142.922f, 55.901f, 139.649f, 55.246f, 138.34f, 54.592f, 132.449f, 54.592f, 127.867f, 55.901f, 125.904f, 59.828f, 121.976f, 63.101f, 121.322f, 65.719f, 122.631f, 68.992f, 125.249f, 70.301f, 130.485f, 71.61f, 133.104f, 72.264f, 136.376f, 72.919f, 140.304f, 74.883f, 144.885f, 76.192f, 150.776f, 76.192f, 151.431f, 76.192f, 152.085f, 76.192f, 158.631f, 76.192f, 159.94f, 75.537f, 155.358f, 74.228f, 150.122f, 74.228f, 146.195f, 73.574f, 141.613f, 73.574f, 137.685f, 74.228f, 132.449f, 74.883f, 128.522f, 75.537f, 124.594f, 76.192f, 123.285f, 76.846f, 122.631f, 80.774f, 122.631f, 82.737f, 123.285f, 85.355f, 125.249f, 88.628f, 129.831f, 89.283f, 133.104f, 89.937f, 137.031f, 90.592f, 140.958f, 89.937f, 142.267f, 86.665f, 141.613f, 85.355f, 140.304f, 84.701f, 138.34f, 84.701f, 137.685f, 85.355f, 137.031f, 87.974f, 135.722f, 90.592f, 136.376f, 92.555f, 137.031f, 96.483f, 139.649f, 98.446f, 140.958f, 101.719f, 142.922f, 103.028f, 142.922f, 100.41f, 138.34f, 99.756f, 134.413f, 99.101f, 131.14f, 99.101f, 128.522f, 99.756f, 127.213f, 101.065f, 125.904f, 102.374f, 123.94f, 103.683f, 123.94f, 107.61f, 125.904f, 110.228f, 129.831f, 114.156f, 135.067f, 117.428f, 140.304f, 119.392f, 143.576f, 121.356f, 144.231f, 122.665f, 144.231f, 123.974f, 142.267f, 126.592f, 139.649f, 127.247f, 140.304f, 126.592f, 142.922f, 124.628f, 143.576f, 122.01f, 142.922f, 118.083f, 141.613f, 114.81f, 136.376f, 114.81f, 131.14f, 113.501f, 127.213f, 114.156f, 125.904f, 118.083f, 125.904f, 120.701f, 126.558f, 123.319f, 130.485f, 125.283f, 136.376f, 125.937f, 140.304f, 125.937f, 142.922f, 126.592f, 143.576f, 125.937f, 135.722f, 125.937f, 131.794f, 125.937f, 131.14f, 127.247f, 129.176f, 129.21f, 127.213f, 131.828f, 127.213f, 134.447f, 128.522f, 136.41f, 136.376f, 139.028f, 150.122f, 141.647f, 162.558f, 140.992f, 163.213f, 138.374f, 160.595f, 135.756f, 153.395f, 135.101f, 148.158f, 134.447f, 140.304f, 134.447f, 130.485f, 133.792f, 124.594f, 133.792f, 115.431f, 133.792f, 110.194f, 133.792f, 105.612f, 134.447f, 105.612f, 137.065f, 110.194f, 137.719f, 116.74f, 139.028f, 120.013f, 139.028f, 123.94f, 137.719f, 127.213f, 135.756f, 130.485f, 134.447f, 130.485f, 133.792f, 130.485f, 137.719f, 131.794f, 141.647f, 135.722f, 146.883f, 142.922f, 152.774f, 153.395f, 153.428f, 159.286f, 150.156f, 159.94f, 147.537f, 156.667f, 146.883f, 148.813f, 146.883f, 140.958f, 146.883f, 134.413f, 146.883f, 125.904f, 145.574f, 118.703f, 145.574f, 114.776f, 145.574f, 112.158f, 146.228f, 111.503f, 147.537f, 111.503f, 148.192f, 112.158f, 150.156f, 112.812f, 150.81f, 113.467f, 152.119f, 114.776f, 154.083f, 117.394f, 155.392f, 119.358f, 156.701f, 120.667f, 157.356f, 121.976f, 156.701f, 121.322f, 156.047f, 120.013f, 155.392f, 119.358f, 154.083f, 117.394f, 154.083f, 116.74f, 152.774f, 114.776f, 152.119f, 114.121f, 150.81f, 113.467f, 149.501f, 113.467f, 147.537f, 112.158f, 146.883f, 112.158f, 145.574f, 111.503f, 144.919f, 112.158f, 144.265f, 114.121f, 144.265f, 115.431f, 144.265f, 116.74f, 144.265f, 117.394f, 144.265f, 118.049f, 144.919f, 118.703f, 145.574f, 120.667f, 146.228f, 122.631f, 147.537f, 123.285f, 147.537f, 124.594f, 148.192f, 125.904f, 147.537f, 128.522f, 147.537f, 129.176f, 147.537f, 130.485f, 147.537f, 132.449f, 147.537f, 134.413f, 147.537f, 136.376f, 147.537f, 138.34f, 147.537f, 138.994f, 145.574f, 138.994f, 142.956f, 138.252f }; RectangleF rectangle = new RectangleF(30, 580, 300, 400); PdfInkAnnotation inkAnnotation = new PdfInkAnnotation(rectangle, linePoints); inkAnnotation.Bounds = rectangle; inkAnnotation.Color = new PdfColor(Color.Red); page.Graphics.DrawString("Ink Annotation", font, brush, new PointF(30, 610)); page.Annotations.Add(inkAnnotation); PdfPage secondPage = document.Pages.Add(); //Creates a new TextMarkup annotation. string s = "This is TextMarkup annotation!!!"; secondPage.Graphics.DrawString(s, font, brush, new PointF(30, 70)); PdfTextMarkupAnnotation textannot = new PdfTextMarkupAnnotation("sample", "Strikeout", s, new PointF(30, 70), font); textannot.Author = "Annotation"; textannot.Opacity = 1.0f; textannot.Subject = "pdftextmarkupannotation"; textannot.ModifiedDate = new DateTime(2015, 1, 18); textannot.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.StrikeOut; textannot.TextMarkupColor = new PdfColor(Color.Yellow); textannot.InnerColor = new PdfColor(Color.Red); textannot.Color = new PdfColor(Color.Yellow); if (checkboxFlatten == "Flatten") { textannot.Flatten = true; } secondPage.Graphics.DrawString("TextMarkup Annotation", font, brush, new PointF(30, 40)); secondPage.Annotations.Add(textannot); //Creates a new popup annotation. RectangleF popupRect = new RectangleF(430, 70, 30, 30); PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation(); popupAnnotation.Border.Width = 4; popupAnnotation.Border.HorizontalRadius = 20; popupAnnotation.Border.VerticalRadius = 30; popupAnnotation.Opacity = 1; popupAnnotation.Open = true; popupAnnotation.Text = "Popup Annotation"; popupAnnotation.Color = Color.Green; popupAnnotation.InnerColor = Color.Blue; popupAnnotation.Bounds = popupRect; if (checkboxFlatten == "Flatten") { popupAnnotation.FlattenPopUps = true; popupAnnotation.Flatten = true; } secondPage.Graphics.DrawString("Popup Annotation", font, brush, new PointF(400, 40)); secondPage.Annotations.Add(popupAnnotation); //Creates a new Line measurement annotation. points = new int[] { 400, 630, 550, 630 }; PdfLineMeasurementAnnotation lineMeasureAnnot = new PdfLineMeasurementAnnotation(points); lineMeasureAnnot.Author = "Syncfusion"; lineMeasureAnnot.Subject = "LineAnnotation"; lineMeasureAnnot.ModifiedDate = new DateTime(2015, 1, 18); lineMeasureAnnot.Unit = PdfMeasurementUnit.Inch; lineMeasureAnnot.lineBorder.BorderWidth = 2; lineMeasureAnnot.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular); lineMeasureAnnot.Color = new PdfColor(Color.Red); if (checkboxFlatten == "Flatten") { lineMeasureAnnot.Flatten = true; } secondPage.Graphics.DrawString("Line Measurement Annotation", font, brush, new PointF(370, 130)); secondPage.Annotations.Add(lineMeasureAnnot); //Creates a new Freetext annotation. RectangleF freetextrect0 = new RectangleF(80, 160, 100, 50); PdfFreeTextAnnotation freeText0 = new PdfFreeTextAnnotation(freetextrect0); freeText0.MarkupText = "Free Text with Callouts"; freeText0.TextMarkupColor = new PdfColor(Color.Green); freeText0.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 7f); freeText0.BorderColor = new PdfColor(Color.Blue); freeText0.Border = new PdfAnnotationBorder(.5f); freeText0.AnnotationFlags = PdfAnnotationFlags.Default; freeText0.Text = "Free Text"; freeText0.Rotate = PdfAnnotationRotateAngle.RotateAngle90; freeText0.Color = new PdfColor(Color.Yellow); PointF[] Freetextpoints0 = { new PointF(45, 220), new PointF(60, 175), new PointF(80, 175) }; freeText0.CalloutLines = Freetextpoints0; secondPage.Graphics.DrawString("Rotated FreeText Annotation", font, brush, new PointF(40, 130)); if (checkboxFlatten == "Flatten") { freeText0.Flatten = true; } secondPage.Annotations.Add(freeText0); MemoryStream SourceStream = new MemoryStream(); document.Save(SourceStream); document.Close(true); //Creates a new Loaded document. PdfLoadedDocument lDoc = new PdfLoadedDocument(SourceStream); PdfLoadedPage lpage1 = lDoc.Pages[0] as PdfLoadedPage; PdfLoadedPage lpage2 = lDoc.Pages[1] as PdfLoadedPage; if (checkboxFlatten == "Flatten") { lpage1.Annotations.Flatten = true; lpage2.Annotations.Flatten = true; } //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); lDoc.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; lDoc.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "Annotation.pdf"; return(fileStreamResult); }
public ActionResult Default(string Browser) { //Creating new PDF document instance PdfDocument document = new PdfDocument(); //Setting margin document.PageSettings.Margins.All = 0; //Adding a new page PdfPage page = document.Pages.Add(); PdfGraphics g = page.Graphics; //Creating font instances PdfFont headerFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 35); PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 16); //Drawing content onto the PDF g.DrawRectangle(new PdfSolidBrush(gray), new Syncfusion.Drawing.RectangleF(0, 0, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height)); g.DrawRectangle(new PdfSolidBrush(black), new Syncfusion.Drawing.RectangleF(0, 0, page.Graphics.ClientSize.Width, 130)); g.DrawRectangle(new PdfSolidBrush(white), new Syncfusion.Drawing.RectangleF(0, 400, page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height - 450)); g.DrawString("Enterprise", headerFont, new PdfSolidBrush(violet), new Syncfusion.Drawing.PointF(10, 20)); g.DrawRectangle(new PdfSolidBrush(violet), new Syncfusion.Drawing.RectangleF(10, 63, 140, 35)); g.DrawString("Reporting Solutions", subHeadingFont, new PdfSolidBrush(black), new Syncfusion.Drawing.PointF(15, 70)); PdfLayoutResult result = HeaderPoints("Develop cloud-ready reporting applications in as little as 20% of the time.", 15, page); result = HeaderPoints("Proven, reliable platform thousands of users over the past 10 years.", result.Bounds.Bottom + 15, page); result = HeaderPoints("Microsoft Excel, Word, Adobe PDF, RDL display and editing.", result.Bounds.Bottom + 15, page); result = HeaderPoints("Why start from scratch? Rely on our dependable solution frameworks", result.Bounds.Bottom + 15, page); result = BodyContent("Deployment-ready framework tailored to your needs.", result.Bounds.Bottom + 45, page); result = BodyContent("Our architects and developers have years of reporting experience.", result.Bounds.Bottom + 25, page); result = BodyContent("Solutions available for web, desktop, and mobile applications.", result.Bounds.Bottom + 25, page); result = BodyContent("Backed by our end-to-end product maintenance infrastructure.", result.Bounds.Bottom + 25, page); result = BodyContent("The quickest path from concept to delivery.", result.Bounds.Bottom + 25, page); PdfPen redPen = new PdfPen(PdfBrushes.Red, 2); g.DrawLine(redPen, new Syncfusion.Drawing.PointF(40, result.Bounds.Bottom + 92), new Syncfusion.Drawing.PointF(40, result.Bounds.Bottom + 145)); float headerBulletsXposition = 40; PdfTextElement txtElement = new PdfTextElement("The Experts"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 90, 450, 200)); PdfPen violetPen = new PdfPen(PdfBrushes.Violet, 2); g.DrawLine(violetPen, new Syncfusion.Drawing.PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 92), new Syncfusion.Drawing.PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 145)); txtElement = new PdfTextElement("Accurate Estimates"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); result = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 90, 450, 200)); txtElement = new PdfTextElement("A substantial number of .NET reporting applications use our frameworks"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200)); txtElement = new PdfTextElement("Given our expertise, you can expect estimates to be accurate."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200)); PdfPen greenPen = new PdfPen(PdfBrushes.Green, 2); g.DrawLine(greenPen, new Syncfusion.Drawing.PointF(40, result.Bounds.Bottom + 32), new Syncfusion.Drawing.PointF(40, result.Bounds.Bottom + 85)); txtElement = new PdfTextElement("Product Licensing"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 30, 450, 200)); PdfPen bluePen = new PdfPen(PdfBrushes.Blue, 2); g.DrawLine(bluePen, new Syncfusion.Drawing.PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 32), new Syncfusion.Drawing.PointF(headerBulletsXposition + 280, result.Bounds.Bottom + 85)); txtElement = new PdfTextElement("About Syncfusion"); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 20); result = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 290, result.Bounds.Bottom + 30, 450, 200)); txtElement = new PdfTextElement("Solution packages can be combined with product licensing for great cost savings."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 5, result.Bounds.Bottom + 5, 250, 200)); txtElement = new PdfTextElement("Syncfusion offers over 1,000 components and frameworks for mobile, web, and desktop development."); txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular); result = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 290, result.Bounds.Y, 250, 200)); g.DrawString("All trademarks mentioned belong to their owners.", new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic), PdfBrushes.White, new Syncfusion.Drawing.PointF(10, g.ClientSize.Height - 30)); PdfTextWebLink linkAnnot = new PdfTextWebLink(); linkAnnot.Url = "//www.syncfusion.com"; linkAnnot.Text = "www.syncfusion.com"; linkAnnot.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 8, PdfFontStyle.Italic); linkAnnot.Brush = PdfBrushes.White; linkAnnot.DrawTextWebLink(page, new Syncfusion.Drawing.PointF(g.ClientSize.Width - 100, g.ClientSize.Height - 30)); //Saving the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); document.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "Sample.pdf"; return(fileStreamResult); }
public FileStreamResult CreateReciept(OrderViewModel model) { try { var customerName = model.Order?.Name; var customerPhone = model.Order?.PhoneNumber; var customerAddress = model.Order?.Address; var orderId = model.Order.Id; var deliveryDAte = model.Order?.DeliveryDate.ToString("yyyy MMMM dd"); string html = @"<!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8'> <title>Invoice</title> <style> .clearfix:after { content: ''; display: table; clear: both; } a { color: #5D6975; text-decoration: underline; } body { position: relative; margin: 0 auto; color: #001028; background: #FFFFFF; font-size: 12px; } header { padding: 10px 0; } h1 { border-top: 1px solid #73c067;; border-bottom: 1px solid #73c067;; color: #73c067; font-size: 2.4em; line-height: 1.4em; font-weight: normal; text-align: center; margin: 0 0 20px 0; background: url(dimension.png); } #project { float: left; } #project span { color: #5D6975; text-align: right; width: 52px; margin-right: 10px; display: inline-block; font-size: 1em; } #project div{ white-space: nowrap; } table, td, th { border: 1px solid #ddd; text-align: center; } td, th { padding: 2px; } tr:nth-child(even) {background-color: #a3d39c;} table { border-collapse: collapse; width: 100%; } </style> </head> <body> <header class='clearfix'> <h1 style='margin-top: 3px;'>INVOICE</h1> <h3 style='color: #73c067'>Payment Link: <a href='http://www.farmhut.com.bd/Payment/OrderDetails/" + orderId + @"' style='text-decoration: none;'> (Click Me)</a></h3> <h3 style='color: #73c067'>Order Id: <a style='cursor: none;color:red;text-decoration: none;'>" + orderId + @"</a></h3> <div id='project'> <div><span>Customer</span> " + customerName + @"</div> <div><span>Phone No</span> " + customerPhone + @"</div> <div><span>Address</span> " + customerAddress + @"</div> <div><span>DATE</span> " + DateTime.Now.ToString("MM/dd/yyyy") + @"</div> <div><span>Delivery DATE</span> " + deliveryDAte + @" </div> </div> </header> <div> <h3 style='color: #73c067;'>Product Details</h3> <table style='margin: auto; width: 60%;'> <tbody> <tr> <td>Title</td> <td>" + model.LiveAnimal.Title + @"</td> </tr> <tr> <td>Category</td> <td>" + model.LiveAnimal.Category + @"</td> </tr> <tr> <td>Height</td> <td>" + model.LiveAnimal.Height + @"</td> </tr> <tr> <td>Weight</td> <td>" + model.LiveAnimal.Weight + @"</td> </tr> <tr> <td>Teeth</td> <td>" + model.LiveAnimal.Teeth + @"</td> </tr> <tr> <td>Origin</td> <td>" + model.LiveAnimal.Origin + @"</td> </tr> <tr> <td>Location</td> <td>" + model.LiveAnimal.Location + @"</td> </tr> <tr> <td>Color</td> <td>" + model.LiveAnimal.Color + @"</td> </tr> </tbody> </table> <h3 style='color: #73c067'>Payment</h3> <table> <thead> <tr> <th class='service'>Title</th> <th>PRICE (DUE)</th> <th>QUANTITY</th> <th>TOTAL</th> </tr> </thead> <tbody> <tr> <td class='service'>" + model.LiveAnimal.Title + @"</td> <td class='unit'>" + model.LiveAnimal.Price + @"</td> <td class='qty'>1</td> <td class='total'>" + model.LiveAnimal.Price + @"</td> </tr> </tr> <tr> <td style='text-align: right;' colspan='3'>SUBTOTAL</td> <td class='total'>" + model.LiveAnimal.Price + @"</td> </tr> <tr> <td style='text-align: right;' colspan='3'>TAX 0%</td> <td class='total'>0</td> </tr> <tr> <td style='text-align: right;' colspan='3' class='grand total'>GRAND TOTAL (DUE)</td> <td class='grand total'>" + model.LiveAnimal.Price + @"</td> </tr> </tbody> </table> <div> <h3 style='color: red'>Notice:</h3> <ul> <li>Use the Order Id for online payment.</li> <li>Keep the invoice safe.</li> </ul> </div> </div> </body> </html>"; MemoryStream stream = new MemoryStream(); PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.A5); pdf.Save(stream); FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); fileStreamResult.FileDownloadName = "Booking Recipet.pdf"; return(fileStreamResult); } catch (Exception e) { _logger.LogError(e, $"Voucher generate Failed: {e.Message}"); return(null); } /*PdfDocument pdf = PdfGenerator.GeneratePdf("<p><h1>Hello World</h1>This is html rendered text</p>", PageSize.A4); * pdf.Save("document.pdf");*/ }
public ActionResult Layers(string InsideBrowser) { //Create a new PDF document PdfDocument doc = new PdfDocument(); doc.PageSettings = new PdfPageSettings(new SizeF(350, 300)); PdfPage page = doc.Pages.Add(); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 16); page.Graphics.DrawString("Layers", font, PdfBrushes.DarkBlue, new PointF(150, 10)); //Add the first layer PdfPageLayer layer = page.Layers.Add("Layer1"); PdfGraphics graphics = layer.Graphics; graphics.TranslateTransform(100, 60); //Draw Arc PdfPen pen = new PdfPen(Color.Red, 50); RectangleF rect = new RectangleF(0, 0, 50, 50); graphics.DrawArc(pen, rect, 360, 360); pen = new PdfPen(Color.Blue, 30); graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360); pen = new PdfPen(Color.Yellow, 20); graphics.DrawArc(pen, rect, 360, 360); pen = new PdfPen(Color.Green, 10); graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360); //Add another layer on the page layer = page.Layers.Add("Layer2"); graphics = layer.Graphics; graphics.TranslateTransform(100, 180); //graphics.SkewTransform(0, 50); //Draw another set of elements pen = new PdfPen(Color.Red, 50); graphics.DrawArc(pen, rect, 360, 360); pen = new PdfPen(Color.Blue, 30); graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360); pen = new PdfPen(Color.Yellow, 20); graphics.DrawArc(pen, rect, 360, 360); pen = new PdfPen(Color.Green, 10); graphics.DrawArc(pen, 0, 0, 50, 50, 360, 360); //Add another layer layer = page.Layers.Add("Layer3"); graphics = layer.Graphics; graphics.TranslateTransform(160, 120); //Draw another set of elements. pen = new PdfPen(Color.Red, 50); graphics.DrawArc(pen, rect, -60, 60); pen = new PdfPen(Color.Blue, 30); graphics.DrawArc(pen, 0, 0, 50, 50, -60, 60); pen = new PdfPen(Color.Yellow, 20); graphics.DrawArc(pen, rect, -60, 60); pen = new PdfPen(Color.Green, 10); graphics.DrawArc(pen, 0, 0, 50, 50, -60, 60); MemoryStream stream = new MemoryStream(); //Save the PDF document doc.Save(stream); stream.Position = 0; //Close the PDF document doc.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf"); fileStreamResult.FileDownloadName = "Layers.pdf"; return(fileStreamResult); }
public Task ExecuteAsync(ActionContext context, FileStreamResult result) { SetHeadersAndLog(context, result); return WriteFileAsync(context, result); }