This commit is contained in:
buildautomation 2021-01-28 20:12:36 +05:30
Родитель bc585a3ae8
Коммит 16075f0e59
3888 изменённых файлов: 0 добавлений и 2818517 удалений

Просмотреть файл

@ -1,105 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region AdvancedReplace
public ActionResult AdvancedReplace(string Group1, string Button)
{
if (Group1 == null)
return View();
try
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPathTemp = basePath + @"/DocIO/SourceTemplate1.doc";
string dataPathTemplate = basePath + @"/DocIO/SourceTemplate2.doc";
string dataPathMaster = basePath + @"/DocIO/MasterTemplate.doc";
string contenttype1 = "application/msword";
//Load Template document stream.
FileStream fileStream = new FileStream(dataPathMaster, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Button == "View Template")
{
return File(fileStream, contenttype1, "MasterTemplate.doc");
}
fileStream.Dispose();
fileStream = null;
//Creating new documents.
WordDocument docSource1 = new WordDocument();
WordDocument docSource2 = new WordDocument();
WordDocument docMaster = new WordDocument();
//Load Templates.
fileStream = new FileStream(dataPathTemp, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
docSource1.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
fileStream = new FileStream(dataPathTemplate, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
docSource2.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
fileStream = new FileStream(dataPathMaster, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
docMaster.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
//Search for a string and store in TextSelection
//The TextSelection copies a text segment with formatting.
TextSelection selection1 = docSource1.Find("PlaceHolder text is replaced with this formatted animated text", false, false);
//Get the text segment to replace the tex across multiple paragraphs
TextBodyPart replacePart = new TextBodyPart(docSource2);
foreach (TextBodyItem bodyItem in docSource2.LastSection.Body.ChildEntities)
replacePart.BodyItems.Add(bodyItem.Clone());
//Replacing the placeholder inside Master Template with matches found while
//search the two template documents.
docMaster.Replace("PlaceHolder1", selection1, true, true, true);
docMaster.ReplaceSingleLine((new System.Text.RegularExpressions.Regex("PlaceHolder2Start:Suppliers/Vendors of Northwind." +
"Customers of Northwind.Employee details of Northwind traders.The product information.The inventory details.The shippers." +
"PO transactions i.e Purchase Order transactions.Sales Order transaction.Inventory transactions.Invoices.PlaceHolder2End")), replacePart);
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
docMaster.Save(ms, type);
docMaster.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
catch (Exception)
{
}
return View();
}
#endregion
}
}

Просмотреть файл

@ -1,147 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.IO;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region AutoShapes
public ActionResult AutoShapes(string Group1)
{
if (Group1 == null)
return View();
//Initialize Word document
WordDocument doc = new WordDocument();
//Ensure Minimum
doc.EnsureMinimal();
//Append AutoShape
Shape shape = doc.LastParagraph.AppendShape(AutoShapeType.RoundedRectangle, 130, 45);
//Set horizontal alignment
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
//Set horizontal origin
shape.HorizontalOrigin = HorizontalOrigin.Page;
//Set vertical origin
shape.VerticalOrigin = VerticalOrigin.Page;
//Set vertical position
shape.VerticalPosition = 50;
//Set AllowOverlap to true for overlapping shapes
shape.WrapFormat.AllowOverlap = true;
//Set Fill Color
shape.FillFormat.Color = Syncfusion.Drawing.Color.Blue;
//Set Content vertical alignment
shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
//Add Texbody contents to Shape
IWParagraph para = shape.TextBody.AddParagraph();
para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
para.AppendText("Requirement").ApplyCharacterFormat(new WCharacterFormat(doc) { Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana" });
shape = doc.LastParagraph.AppendShape(AutoShapeType.DownArrow, 45, 45);
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
shape.HorizontalOrigin = HorizontalOrigin.Page;
shape.VerticalOrigin = VerticalOrigin.Page;
shape.VerticalPosition = 95;
shape.WrapFormat.AllowOverlap = true;
shape = doc.LastParagraph.AppendShape(AutoShapeType.RoundedRectangle, 130, 45);
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
shape.HorizontalOrigin = HorizontalOrigin.Page;
shape.VerticalOrigin = VerticalOrigin.Page;
shape.VerticalPosition = 140;
shape.WrapFormat.AllowOverlap = true;
shape.FillFormat.Color = Syncfusion.Drawing.Color.Orange;
shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
para = shape.TextBody.AddParagraph();
para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
para.AppendText("Design").ApplyCharacterFormat(new WCharacterFormat(doc) { Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana" });
shape = doc.LastParagraph.AppendShape(AutoShapeType.DownArrow, 45, 45);
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
shape.HorizontalOrigin = HorizontalOrigin.Page;
shape.VerticalOrigin = VerticalOrigin.Page;
shape.VerticalPosition = 185;
shape.WrapFormat.AllowOverlap = true;
shape = doc.LastParagraph.AppendShape(AutoShapeType.RoundedRectangle, 130, 45);
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
shape.HorizontalOrigin = HorizontalOrigin.Page;
shape.VerticalOrigin = VerticalOrigin.Page;
shape.VerticalPosition = 230;
shape.WrapFormat.AllowOverlap = true;
shape.FillFormat.Color = Syncfusion.Drawing.Color.Blue;
shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
para = shape.TextBody.AddParagraph();
para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
para.AppendText("Execution").ApplyCharacterFormat(new WCharacterFormat(doc) { Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana" });
shape = doc.LastParagraph.AppendShape(AutoShapeType.DownArrow, 45, 45);
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
shape.HorizontalOrigin = HorizontalOrigin.Page;
shape.VerticalOrigin = VerticalOrigin.Page;
shape.VerticalPosition = 275;
shape.WrapFormat.AllowOverlap = true;
shape = doc.LastParagraph.AppendShape(AutoShapeType.RoundedRectangle, 130, 45);
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
shape.HorizontalOrigin = HorizontalOrigin.Page;
shape.VerticalOrigin = VerticalOrigin.Page;
shape.VerticalPosition = 320;
shape.WrapFormat.AllowOverlap = true;
shape.FillFormat.Color = Syncfusion.Drawing.Color.Violet;
shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
para = shape.TextBody.AddParagraph();
para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
para.AppendText("Testing").ApplyCharacterFormat(new WCharacterFormat(doc) { Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana" });
shape = doc.LastParagraph.AppendShape(AutoShapeType.DownArrow, 45, 45);
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
shape.HorizontalOrigin = HorizontalOrigin.Page;
shape.VerticalOrigin = VerticalOrigin.Page;
shape.VerticalPosition = 365;
shape.WrapFormat.AllowOverlap = true;
shape = doc.LastParagraph.AppendShape(AutoShapeType.RoundedRectangle, 130, 45);
shape.HorizontalAlignment = ShapeHorizontalAlignment.Center;
shape.HorizontalOrigin = HorizontalOrigin.Page;
shape.VerticalOrigin = VerticalOrigin.Page;
shape.VerticalPosition = 410;
shape.WrapFormat.AllowOverlap = true;
shape.FillFormat.Color = Syncfusion.Drawing.Color.PaleVioletRed;
shape.TextFrame.TextVerticalAlignment = VerticalAlignment.Middle;
para = shape.TextBody.AddParagraph();
para.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
para.AppendText("Release").ApplyCharacterFormat(new WCharacterFormat(doc) { Bold = true, TextColor = Syncfusion.Drawing.Color.White, FontSize = 12, FontName = "Verdana" });
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .xml format
if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
doc.Save(ms, type);
doc.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion
}
}

Просмотреть файл

@ -1,110 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.OfficeChart;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIORenderer;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Bar Chart
public ActionResult BarChart(string Group1)
{
if (Group1 == null)
return View();
//A new document is created.
WordDocument document = new WordDocument();
//Add new section to the Word document
IWSection section = document.AddSection();
//Set page margins of the section
section.PageSetup.Margins.All = 72;
//Add new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Apply heading style to the title paragraph
paragraph.ApplyStyle(BuiltinStyle.Heading1);
//Apply center alignment to the paragraph
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
//Append text to the paragraph
paragraph.AppendText("Northwind Management Report").CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181);
//Add new paragraph
paragraph = section.AddParagraph();
//Set before spacing to the paragraph
paragraph.ParagraphFormat.BeforeSpacing = 20;
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/Excel_Template.xlsx";
//Load the excel template as stream
Stream excelStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read);
//Create and Append chart to the paragraph with excel stream as parameter
WChart BarChart = paragraph.AppendChart(excelStream, 1, "B2:C6", 470, 300);
//Set chart data
BarChart.ChartType = OfficeChartType.Bar_Clustered;
BarChart.ChartTitle = "Purchase Details";
BarChart.ChartTitleArea.FontName = "Calibri (Body)";
BarChart.ChartTitleArea.Size = 14;
//Set name to chart series
BarChart.Series[0].Name = "Sum of Purchases";
BarChart.Series[1].Name = "Sum of Future Expenses";
//Set Chart Data table
BarChart.HasDataTable = true;
BarChart.DataTable.HasBorders = true;
BarChart.DataTable.HasHorzBorder = true;
BarChart.DataTable.HasVertBorder = true;
BarChart.DataTable.ShowSeriesKeys = true;
BarChart.HasLegend = false;
//Setting background color
BarChart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(208, 206, 206);
BarChart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(208, 206, 206);
//Setting line pattern to the chart area
BarChart.PrimaryCategoryAxis.Border.LinePattern = OfficeChartLinePattern.None;
BarChart.PrimaryValueAxis.Border.LinePattern = OfficeChartLinePattern.None;
BarChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None;
BarChart.PrimaryValueAxis.MajorGridLines.Border.LineColor = Syncfusion.Drawing.Color.FromArgb(175, 171, 171);
//Set label for primary catagory axis
BarChart.PrimaryCategoryAxis.CategoryLabels = BarChart.ChartData[2, 1, 6, 1];
string filename = "";
string contenttype = "";
MemoryStream ms = new MemoryStream();
#region Document SaveOption
if (Group1 == "WordDocx")
{
filename = "Sample.docx";
contenttype = "application/msword";
document.Save(ms, FormatType.Docx);
}
else if (Group1 == "WordML")
{
filename = "Sample.xml";
contenttype = "application/msword";
document.Save(ms, FormatType.WordML);
}
else
{
filename = "Sample.pdf";
contenttype = "application/pdf";
DocIORenderer renderer = new DocIORenderer();
renderer.ConvertToPDF(document).Save(ms);
}
#endregion Document SaveOption
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion
}
}

Просмотреть файл

@ -1,212 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Reflection;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region BookmarkNavigation
public ActionResult BookmarkNavigation(string Group1)
{
if (Group1 == null)
return View();
#region BookmarkNavigation
// Creating a new document.
WordDocument document = new WordDocument();
//Adds section with one empty paragraph to the Word document
document.EnsureMinimal();
//sets the page margins
document.LastSection.PageSetup.Margins.All = 72f;
//Appends bookmark to the paragraph
document.LastParagraph.AppendBookmarkStart("NorthwindDatabase");
document.LastParagraph.AppendText("Northwind database with normalization concept");
document.LastParagraph.AppendBookmarkEnd("NorthwindDatabase");
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/Bookmark_Template.doc";
string dataPathTemp = basePath + @"/DocIO/BkmkDocumentPart_Template.doc";
// Open an existing template document with single section to get Northwind.information
WordDocument nwdInformation = new WordDocument();
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
nwdInformation.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
// Open an existing template document with multiple section to get Northwind data.
WordDocument templateDocument = new WordDocument();
fileStream = new FileStream(dataPathTemp, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
templateDocument.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
// Creating a bookmark navigator. Which help us to navigate through the
// bookmarks in the template document.
BookmarksNavigator bk = new BookmarksNavigator(templateDocument);
// Move to the NorthWind bookmark in template document
bk.MoveToBookmark("NorthWind");
//Gets the bookmark content as WordDocumentPart
WordDocumentPart documentPart = bk.GetContent();
// Creating a bookmark navigator. Which help us to navigate through the
// bookmarks in the Northwind information document.
bk = new BookmarksNavigator(nwdInformation);
// Move to the information bookmark
bk.MoveToBookmark("Information");
// Get the content of information bookmark.
TextBodyPart bodyPart = bk.GetBookmarkContent();
// Creating a bookmark navigator. Which help us to navigate through the
// bookmarks in the destination document.
bk = new BookmarksNavigator(document);
// Move to the NorthWind database in the destination document
bk.MoveToBookmark("NorthwindDatabase");
//Replace the bookmark content using word document parts
bk.ReplaceContent(documentPart);
// Move to the Northwind_Information in the destination document
bk.MoveToBookmark("Northwind_Information");
// Replacing content of Northwind_Information bookmark.
bk.ReplaceBookmarkContent(bodyPart);
// Move to the text bookmark
bk.MoveToBookmark("Text");
//Deletes the bookmark content
bk.DeleteBookmarkContent(true);
// Inserting text inside the bookmark. This will preserve the source formatting
bk.InsertText("Northwind Database contains the following table:");
#region tableinsertion
WTable tbl = new WTable(document);
tbl.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
tbl.TableFormat.IsAutoResized = true;
tbl.ResetCells(8, 2);
IWParagraph paragraph;
tbl.Rows[0].IsHeader = true;
paragraph = tbl[0, 0].AddParagraph();
paragraph.AppendText("Suppliers");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[0, 1].AddParagraph();
paragraph.AppendText("1");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[1, 0].AddParagraph();
paragraph.AppendText("Customers");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[1, 1].AddParagraph();
paragraph.AppendText("1");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[2, 0].AddParagraph();
paragraph.AppendText("Employees");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[2, 1].AddParagraph();
paragraph.AppendText("3");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[3, 0].AddParagraph();
paragraph.AppendText("Products");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[3, 1].AddParagraph();
paragraph.AppendText("1");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[4, 0].AddParagraph();
paragraph.AppendText("Inventory");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[4, 1].AddParagraph();
paragraph.AppendText("2");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[5, 0].AddParagraph();
paragraph.AppendText("Shippers");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[5, 1].AddParagraph();
paragraph.AppendText("1");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[6, 0].AddParagraph();
paragraph.AppendText("PO Transactions");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[6, 1].AddParagraph();
paragraph.AppendText("3");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[7, 0].AddParagraph();
paragraph.AppendText("Sales Transactions");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
paragraph = tbl[7, 1].AddParagraph();
paragraph.AppendText("7");
paragraph.BreakCharacterFormat.FontName = "Calibri";
paragraph.BreakCharacterFormat.FontSize = 10;
bk.InsertTable(tbl);
#endregion tableinsertion
//Move to image bookmark
bk.MoveToBookmark("Image");
//Deletes the bookmark content
bk.DeleteBookmarkContent(true);
// Inserting image to the bookmark.
IWPicture pic = bk.InsertParagraphItem(ParagraphItemType.Picture) as WPicture;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Northwind.png", FileMode.Open, FileAccess.Read);
pic.LoadImage(imageStream);
pic.WidthScale = 50f; // It reduce the image size because it don't fit
pic.HeightScale = 75f; // in document page.
#endregion BookmarkNavigation
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion
}
}

Просмотреть файл

@ -1,106 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Bookmarks
public ActionResult Bookmarks(string Group1)
{
if (Group1 == null)
return View();
#region BookmarkCreation
// Creating a new document.
WordDocument document = new WordDocument();
// Adding a section to the document.
IWSection section = document.AddSection();
// Adding a new paragraph to the section.
IWParagraph paragraph = section.AddParagraph();
// Writing text
paragraph.AppendText("This document demonstrates Essential DocIO's Bookmark functionality.").CharacterFormat.FontSize = 14f;
// Adding paragraph to the section.
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.AppendText("1. Inserting Bookmark Text").CharacterFormat.FontSize = 12f;
// Adding paragraph to the section.
section.AddParagraph();
paragraph = section.AddParagraph();
// BookmarkStart.
paragraph.AppendBookmarkStart("Bookmark");
// Write bookmark
paragraph.AppendText("Bookmark Text");
// BookmarkEnd.
paragraph.AppendBookmarkEnd("Bookmark");
// Adding paragraph to the section.
section.AddParagraph();
paragraph = section.AddParagraph();
// Indicating hidden bookmark text start.
paragraph.AppendBookmarkStart("_HiddenText");
// Writing bookmark text
paragraph.AppendText("2. Hidden Bookmark Text").CharacterFormat.Font = new Syncfusion.Drawing.Font("Comic Sans MS", 10);
// Indicating hidden bookmark text end.
paragraph.AppendBookmarkEnd("_HiddenText");
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.AppendText("3. Nested Bookmarks").CharacterFormat.FontSize = 12f;
// Writing nested bookmarks
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.AppendBookmarkStart("Main");
paragraph.AppendText(" Main data ");
paragraph.AppendBookmarkStart("Nested");
paragraph.AppendText(" Nested data ");
paragraph.AppendBookmarkStart("NestedNested");
paragraph.AppendText(" Nested Nested ");
paragraph.AppendBookmarkEnd("NestedNested");
paragraph.AppendText(" data Nested ");
paragraph.AppendBookmarkEnd("Nested");
paragraph.AppendText(" Data Main ");
paragraph.AppendBookmarkEnd("Main");
#endregion BookmarkCreation
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion Bookmarks
}
}

Просмотреть файл

@ -1,110 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Clone and Merge
public ActionResult CloneandMerge(string Group1, string Group2, string ImportOptions)
{
if (Group1 == null)
return View();
if (Group2 == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/Adventure.docx";
string dataPathTemp = basePath + @"/DocIO/Northwind.docx";
// Opens a source document.
WordDocument document = new WordDocument();
FileStream fileStream = new FileStream(dataPathTemp, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document.Open(fileStream, FormatType.Docx);
fileStream.Dispose();
fileStream = null;
if (Group2 == "UseImportcontents")
{
fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document.ImportContent(new WordDocument(fileStream, FormatType.Doc), GetImportOption(ImportOptions));
fileStream.Dispose();
fileStream = null;
}
else
{
//Specifies the import option for the cloning the contents.
document.ImportOptions = GetImportOption(ImportOptions);
// Read the source template document
WordDocument destinationDocument = new WordDocument();
fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
destinationDocument.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
// Enumerate all the sections from the source document.
foreach (IWSection sec in destinationDocument.Sections)
{
// Cloning all the sections one by one and merging it to the destination document.
document.Sections.Add(sec.Clone());
// Setting section break code to be the same as the template.
document.LastSection.BreakCode = sec.BreakCode;
}
}
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
/// <summary>
/// Returns the ImportOption.
/// </summary>
private ImportOptions GetImportOption(string value)
{
switch (value)
{
case "0":
return ImportOptions.KeepSourceFormatting;
case "1":
return ImportOptions.MergeFormatting;
case "2":
return ImportOptions.KeepTextOnly;
case "3":
return ImportOptions.UseDestinationStyles;
case "4":
return ImportOptions.ListContinueNumbering;
case "5":
return ImportOptions.ListRestartNumbering;
}
return ImportOptions.UseDestinationStyles;
}
#endregion Clone and Merge
}
}

Просмотреть файл

@ -1,74 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region doc to ODT
public ActionResult DOCtoODT(string button)
{
if (button == null)
return View();
if (Request.Form.Files != null)
{
var extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();
if (extension == ".doc" || extension == ".docx" || extension == ".dot" || extension == ".dotx" || extension == ".dotm" || extension == ".docm"
|| extension == ".xml" || extension == ".rtf")
{
MemoryStream stream = new MemoryStream();
Request.Form.Files[0].CopyTo(stream);
WordDocument document = new WordDocument(stream, FormatType.Automatic);
stream.Dispose();
stream = null;
//Convert word document into ODT document
try
{
#region Document SaveOption
//Save as .odt format
FormatType type = FormatType.Odt;
string filename = "WordToODT.odt";
string contenttype = "application/msword";
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
catch (Exception)
{ }
finally
{
}
}
else
{
ViewBag.Message = string.Format("Please choose Word format document to convert to ODT");
}
}
else
{
ViewBag.Message = string.Format("Browse a Word document and then click the button to convert as a ODT document");
}
return View();
}
#endregion doc to ODT
}
}

Просмотреть файл

@ -1,105 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Document Protection
public ActionResult DocumentProtection(string Protection_Type, string Password1, string Group2)
{
if (Group2 == null)
return View();
WordDocument document;
ProtectionType protectionType;
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
//Loads the template document.
if (Protection_Type == "AllowOnlyFormFields")
{
dataPath = basePath + @"/DocIO/TemplateFormFields.doc";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document = new WordDocument(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
// Sets the protection type as allow only Form Fields.
protectionType = ProtectionType.AllowOnlyFormFields;
}
else if (Protection_Type == "AllowOnlyComments")
{
dataPath = basePath + @"/DocIO/TemplateComments.doc";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document = new WordDocument(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
// Sets the protection type as allow only Comments.
protectionType = ProtectionType.AllowOnlyComments;
}
else if (Protection_Type == "AllowOnlyRevisions")
{
dataPath = basePath + @"/DocIO/TemplateRevisions.doc";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document = new WordDocument(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
// Enables track changes in the document.
document.TrackChanges = true;
// Sets the protection type as allow only Revisions.
protectionType = ProtectionType.AllowOnlyRevisions;
}
else
{
dataPath = basePath + @"/DocIO/Essential DocIO.doc";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document = new WordDocument(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
// Sets the protection type as allow only Reading.
protectionType = ProtectionType.AllowOnlyReading;
}
// Enforces protection of the document.
if (string.IsNullOrEmpty(Password1))
document.Protect(protectionType);
else
document.Protect(protectionType, Password1);
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group2 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group2 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion Document Protection
}
}

Просмотреть файл

@ -1,136 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region DocumentSettings
public ActionResult DocumentSettings(string Group1)
{
if (Group1 == null)
return View();
//A new document is created.
WordDocument document = new WordDocument();
//Adding a section to the document.
IWSection section = document.AddSection();
//Adding a paragraph to the section.
IWParagraph paragraph = section.AddParagraph();
#region DocVariable
string name = "John Smith";
string address = "Cary, NC";
//Get the variables in the existing document
DocVariables dVariable = document.Variables;
//Add doc variables
dVariable.Add("Customer Name", name);
dVariable.Add("Customer Address", address);
#endregion DocVariable
#region Document Properties
//Setting document Properties
document.BuiltinDocumentProperties.Author = "Essential DocIO";
document.BuiltinDocumentProperties.ApplicationName = "Essential DocIO";
document.BuiltinDocumentProperties.Category = "Document Generator";
document.BuiltinDocumentProperties.Comments = "This document was generated using Essential DocIO";
document.BuiltinDocumentProperties.Company = "Syncfusion Inc";
document.BuiltinDocumentProperties.Subject = "Native Word Generator";
document.BuiltinDocumentProperties.Keywords = "Syncfusion";
document.BuiltinDocumentProperties.Manager = "Sync Manager";
document.BuiltinDocumentProperties.Title = "Essential DocIO";
// Add a custom document Property
document.CustomDocumentProperties.Add("My_Doc_Date", DateTime.Today);
document.CustomDocumentProperties.Add("My_Doc", true);
document.CustomDocumentProperties.Add("My_ID", 1031);
document.CustomDocumentProperties.Add("My_Comment", "Essential DocIO");
//Remove a custome property
document.CustomDocumentProperties.Remove("My_Doc");
#endregion Document Properties
IWTextRange text = paragraph.AppendText("");
text.CharacterFormat.FontName = "Calibri";
text.CharacterFormat.FontSize = 13;
text = paragraph.AppendText("This document is created with various Document Properties Summary Information and page settings information \n\n You can view Document Properties through: File -> Properties -> Summary/Custom.");
text.CharacterFormat.FontName = "Calibri";
text.CharacterFormat.FontSize = 13;
#region Page setup
// Write section properties
section.PageSetup.PageSize = new Syncfusion.Drawing.SizeF(500, 750);
section.PageSetup.Orientation = PageOrientation.Landscape;
section.PageSetup.Margins.Bottom = 100;
section.PageSetup.Margins.Top = 100;
section.PageSetup.Margins.Left = 50;
section.PageSetup.Margins.Right = 50;
section.PageSetup.PageBordersApplyType = PageBordersApplyType.AllPages;
section.PageSetup.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DoubleWave;
section.PageSetup.Borders.Color = Syncfusion.Drawing.Color.DarkBlue;
section.PageSetup.VerticalAlignment = PageAlignment.Middle;
#endregion Page setup
paragraph = section.AddParagraph();
text = paragraph.AppendText("");
text.CharacterFormat.FontName = "Calibri";
text.CharacterFormat.FontSize = 13;
text = paragraph.AppendText("\n\n You can view Page setup options through File -> PageSetup.");
text.CharacterFormat.FontName = "Calibri";
text.CharacterFormat.FontSize = 13;
#region Get document variables
paragraph = document.LastSection.AddParagraph();
dVariable = document.Variables;
text = paragraph.AppendText("\n\n Document Variables\n");
text.CharacterFormat.FontName = "Calibri";
text.CharacterFormat.FontSize = 13;
text.CharacterFormat.Bold = true;
text = paragraph.AppendText("\n" + dVariable.GetNameByIndex(1) + ": " + dVariable.GetValueByIndex(1));
text.CharacterFormat.FontName = "Calibri";
text.CharacterFormat.FontSize = 13;
//Display the current variable count
text = paragraph.AppendText("\n\nDocument Variables Count: " + dVariable.Count);
text.CharacterFormat.FontName = "Calibri";
text.CharacterFormat.FontSize = 13;
#endregion Get document variables
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion DocumentSettings
}
}

Просмотреть файл

@ -1,363 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Data;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Reflection;
using System.Text;
using Syncfusion.Drawing;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region EmployeeReport
public ActionResult EmployeeReport(string Group1, string Button)
{
if (Group1 == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPathEmployee = basePath + @"/DocIO/EmployeesReportDemo.doc";
string contenttype1 = "application/msword";
FileStream fileStream = new FileStream(dataPathEmployee, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Button == "View Template")
return File(fileStream, contenttype1, "EmployeesReportDemo.doc");
fileStream.Dispose();
fileStream = null;
// Creating a new document.
WordDocument document = new WordDocument();
// Load template
fileStream = new FileStream(dataPathEmployee, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_EmployeeImage);
//Create MailMergeDataTable
MailMergeDataTable mailMergeDataTable = GetMailMergeDataTableEmployee();
// Execute Mail Merge with groups.
document.MailMerge.ExecuteGroup(mailMergeDataTable);
try
{
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
catch (Exception)
{ }
return View();
}
private void MergeField_EmployeeImage(object sender, MergeImageFieldEventArgs args)
{
// Get the image from disk during Merge.
if (args.FieldName == "Photo")
{
string ProductFileName = args.FieldValue.ToString();
byte[] bytes = Convert.FromBase64String(ProductFileName);
MemoryStream ms = new MemoryStream(bytes);
args.ImageStream = ms;
}
}
#endregion EmployeeReport
/// <summary>
/// Gets the mail merge data table.
/// </summary>
private MailMergeDataTable GetMailMergeDataTableEmployee()
{
List<Employees> employees = new List<Employees>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/EmployeesList.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Employees")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "Employees")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Employee":
employees.Add(GetEmployees(reader));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Employees") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable = new MailMergeDataTable("Employees", employees);
reader.Dispose();
fs.Dispose();
return dataTable;
}
/// <summary>
/// Gets the employees.
/// </summary>
/// <param name="reader">The reader.</param>
private Employees GetEmployees(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Employee")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
Employees employee = new Employees();
while (reader.LocalName != "Employee")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "EmployeeID":
employee.EmployeeID = reader.ReadElementContentAsString();
break;
case "LastName":
employee.LastName = reader.ReadElementContentAsString();
break;
case "FirstName":
employee.FirstName = reader.ReadElementContentAsString();
break;
case "Title":
employee.Title = reader.ReadElementContentAsString();
break;
case "TitleOfCourtesy":
employee.TitleOfCourtesy = reader.ReadElementContentAsString();
break;
case "BirthDate":
employee.BirthDate = reader.ReadElementContentAsString();
break;
case "HireDate":
employee.HireDate = reader.ReadElementContentAsString();
break;
case "Address":
employee.Address = reader.ReadElementContentAsString();
break;
case "City":
employee.City = reader.ReadElementContentAsString();
break;
case "Region":
employee.Region = reader.ReadElementContentAsString();
break;
case "PostalCode":
employee.PostalCode = reader.ReadElementContentAsString();
break;
case "Country":
employee.Country = reader.ReadElementContentAsString();
break;
case "HomePhone":
employee.HomePhone = reader.ReadElementContentAsString();
break;
case "Extension":
employee.Extension = reader.ReadElementContentAsString();
break;
case "Photo":
employee.Photo = reader.ReadElementContentAsString();
break;
case "Notes":
employee.Notes = reader.ReadElementContentAsString();
break;
case "ReportsTo":
employee.ReportsTo = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Employee") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return employee;
}
}
public class Employees
{
#region Fields
private string m_employeeID;
private string m_lastName;
private string m_firstName;
private string m_title;
private string m_titleOfCourtesy;
private string m_birthDate;
private string m_hireDate;
private string m_address;
private string m_city;
private string m_region;
private string m_postalCode;
private string m_country;
private string m_homePhone;
private string m_extension;
private string m_photo;
private string m_notes;
private string m_reportsTo;
#endregion
#region Properties
public string EmployeeID
{
get { return m_employeeID; }
set { m_employeeID = value; }
}
public string LastName
{
get { return m_lastName; }
set { m_lastName = value; }
}
public string FirstName
{
get { return m_firstName; }
set { m_firstName = value; }
}
public string Title
{
get { return m_title; }
set { m_title = value; }
}
public string TitleOfCourtesy
{
get { return m_titleOfCourtesy; }
set { m_titleOfCourtesy = value; }
}
public string BirthDate
{
get { return m_birthDate; }
set { m_birthDate = value; }
}
public string HireDate
{
get { return m_hireDate; }
set { m_hireDate = value; }
}
public string Address
{
get { return m_address; }
set { m_address = value; }
}
public string City
{
get { return m_city; }
set { m_city = value; }
}
public string Region
{
get { return m_region; }
set { m_region = value; }
}
public string PostalCode
{
get { return m_postalCode; }
set { m_postalCode = value; }
}
public string Country
{
get { return m_country; }
set { m_country = value; }
}
public string HomePhone
{
get { return m_homePhone; }
set { m_homePhone = value; }
}
public string Extension
{
get { return m_extension; }
set { m_extension = value; }
}
public string Photo
{
get { return m_photo; }
set { m_photo = value; }
}
public string Notes
{
get { return m_notes; }
set { m_notes = value; }
}
public string ReportsTo
{
get { return m_reportsTo; }
set { m_reportsTo = value; }
}
#endregion
#region Constructor
public Employees(string employeeID, string lastName, string firstName, string title, string titleOfCourtesy, string birthDate, string hireDate, string address, string city, string region, string postalCode, string country, string homePhone, string extension, string photo, string notes, string reportsTo)
{
m_employeeID = employeeID;
m_lastName = lastName;
m_firstName = firstName;
m_title = title;
m_titleOfCourtesy = titleOfCourtesy;
m_birthDate = birthDate;
m_hireDate = hireDate;
m_address = address;
m_city = city;
m_region = region;
m_postalCode = postalCode;
m_country = country;
m_homePhone = homePhone;
m_extension = extension;
m_photo = photo;
m_notes = notes;
m_reportsTo = reportsTo;
}
public Employees()
{ }
#endregion
}
}

Просмотреть файл

@ -1,81 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Drawing;
using System.Text.RegularExpressions;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.Pdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
public ActionResult FindandHighlight(string Group1, string Button, string Group2)
{
if (Group1 == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/Adventure.docx";
string contenttype1 = "application/vnd.ms-word.document.12";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Button == "View Template")
return File(fileStream, contenttype1, "Adventure.docx");
try
{
//Load template document
WordDocument doc = new WordDocument(fileStream,FormatType.Docx);
fileStream.Dispose();
fileStream = null;
//Get the pattern for regular expression
Regex regex = new Regex(Group2);
//Find the first occurrence of the text in the Word document.
TextSelection text = doc.Find(regex);
//Set the highlight color for the text.
text.GetAsOneRange().CharacterFormat.HighlightColor = Syncfusion.Drawing.Color.Green;
try
{
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
doc.Save(ms, type);
doc.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
catch (Exception)
{ }
}
catch (Exception)
{ }
return View();
}
}
}

Просмотреть файл

@ -1,215 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Reflection;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region FootnotesandEndnotes
public ActionResult FootnotesandEndnotes(string Group1)
{
if (Group1 == null)
return View();
//A new document is created.
WordDocument document = new WordDocument();
//Create footnotes at the bottom of the page
CreateFootNote(document);
//Create endnotes at the end of the section
CreateEndNote(document);
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#region Helper Methods
#region CreateFootNote
void CreateFootNote(WordDocument document)
{
//Add a new section to the document.
IWSection section = document.AddSection();
//Adding a new paragraph to the section.
IWParagraph paragraph = section.AddParagraph();
IWTextRange textRange = paragraph.AppendText("\t\t\t\t\tDemo for Footnote");
textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Black;
textRange.CharacterFormat.Bold = true;
textRange.CharacterFormat.FontSize = 20;
section.AddParagraph();
section.AddParagraph();
paragraph = section.AddParagraph();
WFootnote footnote = new WFootnote(document);
footnote = paragraph.AppendFootnote(FootnoteType.Footnote);
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//Insert Text into the paragraph
paragraph.AppendText("Google").CharacterFormat.Bold = true;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/google.png", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph = footnote.TextBody.AddParagraph();
paragraph.AppendText(" Google is the most famous search engines in the Word ");
//Adding a new paragraph to the section.
paragraph = section.AddParagraph();
paragraph = section.AddParagraph();
footnote = paragraph.AppendFootnote(FootnoteType.Footnote);
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//Insert Text into the paragraph
paragraph.AppendText("Yahoo").CharacterFormat.Bold = true;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
imageStream = new FileStream(basePath + @"/images/DocIO/yahoo.gif", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph = footnote.TextBody.AddParagraph();
paragraph.AppendText(" Yahoo experience makes it easier to discover the news and information that you care about most. ");
//Adding a new paragraph to the section.
paragraph = section.AddParagraph();
paragraph = section.AddParagraph();
footnote = paragraph.AppendFootnote(FootnoteType.Footnote);
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//Insert Text into the paragraph
paragraph.AppendText("Northwind Traders").CharacterFormat.Bold = true;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
imageStream = new FileStream(basePath + @"/images/DocIO/Northwind_logo.png", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph = footnote.TextBody.AddParagraph();
paragraph.AppendText(" The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases. ");
//Setting number format for Footnote
document.FootnoteNumberFormat = FootEndNoteNumberFormat.Arabic;
//Setting Footnote position
document.FootnotePosition = FootnotePosition.PrintAtBottomOfPage;
}
#endregion
#region CreateEndNote
void CreateEndNote(WordDocument document)
{
//Add a new section to the document.
IWSection section = document.AddSection();
//Adding a new paragraph to the section.
IWParagraph paragraph = section.AddParagraph();
IWTextRange textRange = paragraph.AppendText("\t\t\t\t\tDemo for Endnote");
textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Black;
textRange.CharacterFormat.Bold = true;
textRange.CharacterFormat.FontSize = 20;
section.AddParagraph();
section.AddParagraph();
paragraph = section.AddParagraph();
WFootnote footnote = new WFootnote(document);
footnote = paragraph.AppendFootnote(FootnoteType.Endnote);
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//Insert Text into the paragraph
paragraph.AppendText("Google").CharacterFormat.Bold = true;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/google.png", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph = footnote.TextBody.AddParagraph();
paragraph.AppendText(" Google is the most famous search engines in the Word ");
section = document.AddSection();
section.BreakCode = SectionBreakCode.NoBreak;
//Adding a new paragraph to the section.
paragraph = section.AddParagraph();
paragraph = section.AddParagraph();
footnote = paragraph.AppendFootnote(FootnoteType.Endnote);
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//Insert Text into the paragraph
paragraph.AppendText("Yahoo").CharacterFormat.Bold = true;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
imageStream = new FileStream(basePath + @"/images/DocIO/yahoo.gif", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph = footnote.TextBody.AddParagraph();
paragraph.AppendText(" Yahoo experience makes it easier to discover the news and information that you care about most. ");
section = document.AddSection();
section.BreakCode = SectionBreakCode.NoBreak;
//Adding a new paragraph to the section.
paragraph = section.AddParagraph();
paragraph = section.AddParagraph();
footnote = paragraph.AppendFootnote(FootnoteType.Endnote);
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//Insert Text into the paragraph
paragraph.AppendText("Northwind Traders").CharacterFormat.Bold = true;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
imageStream = new FileStream(basePath + @"/images/DocIO/Northwind_logo.png", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph = footnote.TextBody.AddParagraph();
paragraph.AppendText(" The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases. ");
//Set the number format for the Endnote.
document.EndnoteNumberFormat = Syncfusion.DocIO.FootEndNoteNumberFormat.LowerCaseRoman;
document.RestartIndexForEndnote = Syncfusion.DocIO.EndnoteRestartIndex.DoNotRestart;
//Set the Endnote position.
document.EndnotePosition = Syncfusion.DocIO.EndnotePosition.DisplayEndOfSection;
}
#endregion
#endregion
#endregion FootnotesandEndnotes
}
}

Просмотреть файл

@ -1,199 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System;
using System.IO;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
public IActionResult FormFillingAndProtection(string Button)
{
if (Button == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/ContentControlTemplate.docx";
string contenttype1 = "application/vnd.ms-word.document.12";
// Load Template document stream.
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Button == "View Template")
{
return File(fileStream, contenttype1, "ContentControlTemplate.docx");
}
// Creates an empty Word document instance.
WordDocument document = new WordDocument();
// Opens template document.
document.Open(fileStream, FormatType.Docx);
fileStream.Dispose();
fileStream = null;
IWTextRange textRange;
//Gets table from the template document.
IWTable table = document.LastSection.Tables[0];
WTableRow row = table.Rows[1];
#region Inserting content controls
#region Calendar content control
IWParagraph cellPara = row.Cells[0].Paragraphs[0];
//Accesses the date picker content control.
IInlineContentControl inlineControl = (cellPara.ChildEntities[2] as IInlineContentControl);
textRange = inlineControl.ParagraphItems[0] as WTextRange;
//Sets today's date to display.
textRange.Text = DateTime.Now.ToString("d");
textRange.CharacterFormat.FontSize = 14;
//Protects the content control.
inlineControl.ContentControlProperties.LockContents = true;
#endregion
#region Plain text content controls
table = document.LastSection.Tables[1];
row = table.Rows[0];
cellPara = row.Cells[0].LastParagraph;
//Accesses the plain text content control.
inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl);
//Protects the content control.
inlineControl.ContentControlProperties.LockContents = true;
textRange = inlineControl.ParagraphItems[0] as WTextRange;
//Sets text in plain text content control.
textRange.Text = "Northwind Analytics";
textRange.CharacterFormat.FontSize = 14;
cellPara = row.Cells[1].LastParagraph;
//Accesses the plain text content control.
inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl);
//Protects the content control.
inlineControl.ContentControlProperties.LockContents = true;
textRange = inlineControl.ParagraphItems[0] as WTextRange;
//Sets text in plain text content control.
textRange.Text = "Northwind";
textRange.CharacterFormat.FontSize = 14;
row = table.Rows[1];
cellPara = row.Cells[0].LastParagraph;
//Accesses the plain text content control.
inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl);
//Protects the content control.
inlineControl.ContentControlProperties.LockContents = true;
//Sets text in plain text content control.
textRange = inlineControl.ParagraphItems[0] as WTextRange;
textRange.Text = "10";
textRange.CharacterFormat.FontSize = 14;
cellPara = row.Cells[1].LastParagraph;
//Accesses the plain text content control.
inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl);
//Protects the content control.
inlineControl.ContentControlProperties.LockContents = true;
//Sets text in plain text content control.
textRange = inlineControl.ParagraphItems[0] as WTextRange;
textRange.Text = "Nancy Davolio";
textRange.CharacterFormat.FontSize = 14;
#endregion
#region CheckBox Content control
row = table.Rows[2];
cellPara = row.Cells[0].LastParagraph;
//Inserts checkbox content control.
inlineControl = cellPara.AppendInlineContentControl(ContentControlType.CheckBox);
inlineControl.ContentControlProperties.LockContents = true;
//Sets checkbox as checked state.
inlineControl.ContentControlProperties.IsChecked = true;
textRange = cellPara.AppendText("C#, ");
textRange.CharacterFormat.FontSize = 14;
//Inserts checkbox content control.
inlineControl = cellPara.AppendInlineContentControl(ContentControlType.CheckBox);
inlineControl.ContentControlProperties.LockContents = true;
//Sets checkbox as checked state.
inlineControl.ContentControlProperties.IsChecked = true;
textRange = cellPara.AppendText("VB");
textRange.CharacterFormat.FontSize = 14;
#endregion
#region Drop down list content control
cellPara = row.Cells[1].LastParagraph;
//Accesses the dropdown list content control.
inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl);
inlineControl.ContentControlProperties.LockContents = true;
//Sets default option to display.
textRange = inlineControl.ParagraphItems[0] as WTextRange;
textRange.Text = "ASP.NET";
textRange.CharacterFormat.FontSize = 14;
inlineControl.ParagraphItems.Add(textRange);
//Adds items to the dropdown list.
ContentControlListItem item;
item = new ContentControlListItem();
item.DisplayText = "ASP.NET MVC";
item.Value = "2";
inlineControl.ContentControlProperties.ContentControlListItems.Add(item);
item = new ContentControlListItem();
item.DisplayText = "Windows Forms";
item.Value = "3";
inlineControl.ContentControlProperties.ContentControlListItems.Add(item);
item = new ContentControlListItem();
item.DisplayText = "WPF";
item.Value = "4";
inlineControl.ContentControlProperties.ContentControlListItems.Add(item);
item = new ContentControlListItem();
item.DisplayText = "Xamarin";
item.Value = "5";
inlineControl.ContentControlProperties.ContentControlListItems.Add(item);
#endregion
#region Calendar content control
row = table.Rows[3];
cellPara = row.Cells[0].LastParagraph;
//Accesses the date picker content control.
inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl);
inlineControl.ContentControlProperties.LockContents = true;
//Sets default date to display.
textRange = inlineControl.ParagraphItems[0] as WTextRange;
textRange.Text = DateTime.Now.AddDays(-5).ToString("d");
textRange.CharacterFormat.FontSize = 14;
cellPara = row.Cells[1].LastParagraph;
//Inserts date picker content control.
inlineControl = (cellPara.ChildEntities[1] as IInlineContentControl);
inlineControl.ContentControlProperties.LockContents = true;
//Sets default date to display.
textRange = inlineControl.ParagraphItems[0] as WTextRange;
textRange.Text = DateTime.Now.AddDays(10).ToString("d");
textRange.CharacterFormat.FontSize = 14;
#endregion
#endregion
#region Block content control
//Accesses the block content control.
BlockContentControl blockContentControl = ((document.ChildEntities[0] as WSection).Body.ChildEntities[2] as BlockContentControl);
//Protects the block content control
blockContentControl.ContentControlProperties.LockContents = true;
#endregion
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
}
}

Просмотреть файл

@ -1,537 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
using System.Reflection;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
#region FormatTable
public partial class DocIOController : Controller
{
public ActionResult FormatTable(string Group1)
{
if (Group1 == null)
return View();
// Create a new document.
WordDocument document = new WordDocument();
// Adding a new section to the document.
IWSection section = document.AddSection();
section.PageSetup.DifferentFirstPage = true;
IWTextRange textRange;
IWParagraph paragraph = section.AddParagraph();
// --------------------------------------------
// Table in page header
// --------------------------------------------
IWParagraph hParagraph = new WParagraph(document);
hParagraph.AppendText("Header text\r\n").CharacterFormat.FontSize = 14;
section.HeadersFooters.FirstPageHeader.Paragraphs.Add(hParagraph);
IWTable hTable = document.LastSection.HeadersFooters.FirstPageHeader.AddTable();
hTable.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
hTable.TableFormat.Paddings.All = 5.4f;
hTable.ResetCells(2, 2);
hTable[0, 0].AddParagraph().AppendText("1");
hTable[0, 1].AddParagraph().AppendText("2");
hTable[1, 0].AddParagraph().AppendText("3");
hTable[1, 1].AddParagraph().AppendText("4");
// --------------------------------------------
// Tiny table
// --------------------------------------------
paragraph = section.AddParagraph();
paragraph.AppendText("Tiny table\r\n").CharacterFormat.FontSize = 14;
paragraph = section.AddParagraph();
WTextBody textBody = section.Body;
IWTable table = textBody.AddTable();
table.ResetCells(2, 2);
table.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
table.TableFormat.Paddings.All = 5.4f;
WTableRow row_0 = table.Rows[0];
row_0.Cells[0].AddParagraph().AppendText("A");
row_0.Cells[0].AddParagraph().AppendText("AA");
row_0.Cells[0].AddParagraph().AppendText("AAA");
WTableRow row_1 = table.Rows[1];
row_1.Cells[1].AddParagraph().AppendText("B");
row_1.Cells[1].AddParagraph().AppendText("BB\r\nBBB");
row_1.Cells[1].AddParagraph().AppendText("BBB");
textBody.AddParagraph().AppendText("Text after table...").CharacterFormat.FontSize = 14;
// --------------------------------------------
// Table with different formatting
// --------------------------------------------
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.AppendText("Table with different formatting\r\n").CharacterFormat.FontSize = 14;
paragraph = section.AddParagraph();
textBody = section.Body;
table = textBody.AddTable();
table.ResetCells(3, 3);
/* ------- First Row -------- */
WTableRow row0 = table.Rows[0];
paragraph = (IWParagraph)row0.Cells[0].AddParagraph();
textRange = paragraph.AppendText("1");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left;
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.Bold = true;
textRange.CharacterFormat.FontSize = 14f;
row0.Cells[0].CellFormat.Borders.LineWidth = 2f;
row0.Cells[0].CellFormat.Borders.Color = Syncfusion.Drawing.Color.Magenta;
paragraph = (IWParagraph)row0.Cells[1].AddParagraph();
textRange = paragraph.AppendText("2");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
textRange.CharacterFormat.Emboss = true;
textRange.CharacterFormat.FontSize = 15f;
row0.Cells[1].CellFormat.Borders.LineWidth = 1.3f;
row0.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DoubleWave;
paragraph = (IWParagraph)row0.Cells[2].AddParagraph();
textRange = paragraph.AppendText("3");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left;
textRange.CharacterFormat.Engrave = true;
textRange.CharacterFormat.FontSize = 15f;
row0.Cells[2].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Emboss3D;
/* ------- Second Row -------- */
WTableRow row1 = table.Rows[1];
paragraph = (IWParagraph)row1.Cells[0].AddParagraph();
textRange = paragraph.AppendText("4");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
textRange.CharacterFormat.SmallCaps = true;
textRange.CharacterFormat.FontName = "Comic Sans MS";
textRange.CharacterFormat.FontSize = 16;
row1.Cells[0].CellFormat.Borders.LineWidth = 2f;
row1.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DashDotStroker;
paragraph = (IWParagraph)row1.Cells[1].AddParagraph();
textRange = paragraph.AppendText("5");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange.CharacterFormat.Shadow = true;
textRange.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Orange;
textRange.CharacterFormat.FontSize = 15f;
row1.Cells[1].CellFormat.Borders.LineWidth = 2f;
row1.Cells[1].CellFormat.Borders.Color = Syncfusion.Drawing.Color.Brown;
paragraph = (IWParagraph)row1.Cells[2].AddParagraph();
textRange = paragraph.AppendText("6");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
textRange.CharacterFormat.Bold = true;
textRange.CharacterFormat.FontSize = 14f;
row1.Cells[2].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(51, 51, 101);
row1.Cells[2].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
/* ------- Third Row -------- */
WTableRow row2 = table.Rows[2];
paragraph = (IWParagraph)row2.Cells[0].AddParagraph();
textRange = paragraph.AppendText("7");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
textRange.CharacterFormat.FontSize = 13f;
row2.Cells[0].CellFormat.Borders.LineWidth = 1.5f;
row2.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DashLargeGap;
paragraph = (IWParagraph)row2.Cells[1].AddParagraph();
textRange = paragraph.AppendText("8");
textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Blue;
textRange.CharacterFormat.FontSize = 16f;
row2.Cells[1].CellFormat.Borders.LineWidth = 3f;
row2.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Wave;
paragraph = (IWParagraph)row2.Cells[2].AddParagraph();
textRange = paragraph.AppendText("9");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
row2.Cells[2].CellFormat.Borders.LineWidth = 2f;
row2.Cells[2].CellFormat.Borders.Color = Syncfusion.Drawing.Color.Cyan;
row2.Cells[2].CellFormat.Borders.Shadow = true;
row2.Cells[2].CellFormat.Borders.Space = 20;
// --------------------------------------------
// Table Cell Merging.
// --------------------------------------------
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.AppendText("Table Cell Merging...").CharacterFormat.FontSize = 14;
section.AddParagraph();
paragraph = section.AddParagraph();
textBody = section.Body;
// Adding a new Table to the textbody.
table = textBody.AddTable();
RowFormat format = new RowFormat();
format.Paddings.All = 5;
format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Dot;
format.Borders.LineWidth = 2;
// Inserting rows to the table.
table.ResetCells(6, 6, format, 80);
// Table formatting with cell merging.
table.Rows[0].Cells[0].CellFormat.HorizontalMerge = CellMerge.Start;
table.Rows[0].Cells[1].CellFormat.HorizontalMerge = CellMerge.Continue;
table.Rows[0].Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
table.Rows[0].Cells[0].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(218, 230, 246);
IWParagraph par = table.Rows[0].Cells[0].AddParagraph();
par.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
par.AppendText("Horizontal Merge").CharacterFormat.Bold = true;
table.Rows[2].Cells[3].CellFormat.VerticalMerge = CellMerge.Start;
table.Rows[3].Cells[3].CellFormat.VerticalMerge = CellMerge.Continue;
table.Rows[2].Cells[3].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
par = table.Rows[2].Cells[3].AddParagraph();
table.Rows[2].Cells[3].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(252, 172, 85);
par.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
par.AppendText("Vertical Merge").CharacterFormat.Bold = true;
#region Table Cell Spacing.
// --------------------------------------------
// Table Cell Spacing.
// --------------------------------------------
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.AppendText("Table Cell spacing...").CharacterFormat.FontSize = 14;
section.AddParagraph();
paragraph = section.AddParagraph();
textBody = section.Body;
// Adding a new Table to the textbody.
table = textBody.AddTable();
table.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
table.TableFormat.Paddings.All = 5.4f;
format = new RowFormat();
format.Paddings.All = 5;
format.CellSpacing = 2;
format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash;
format.IsBreakAcrossPages = true;
table.ResetCells(25, 5, format, 90);
IWTextRange text;
table.Rows[0].IsHeader = true;
for (int i = 0; i < table.Rows[0].Cells.Count; i++)
{
paragraph = table[0, i].AddParagraph() as WParagraph;
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText(string.Format("Header {0}", i + 1));
text.CharacterFormat.Font = new Font("Bitstream Vera Serif", 10);
text.CharacterFormat.Bold = true;
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(0, 21, 84);
table[0, i].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(203, 211, 226);
}
for (int i = 1; i < table.Rows.Count; i++)
{
for (int j = 0; j < 5; j++)
{
paragraph = table[i, j].AddParagraph() as WParagraph;
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1));
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50);
text.CharacterFormat.Bold = true;
if (i % 2 != 1)
table[i, j].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(231, 235, 245);
else
table[i, j].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(246, 249, 255);
}
}
#endregion Table Cell Spacing.
#region Nested Table
// --------------------------------------------
// Nested Table.
// --------------------------------------------
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.PageBreakBefore = true;
paragraph.AppendText("Nested Table...").CharacterFormat.FontSize = 14;
section.AddParagraph();
paragraph = section.AddParagraph();
textBody = section.Body;
// Adding a new Table to the textbody.
table = textBody.AddTable();
format = new RowFormat();
format.Paddings.All = 5;
format.CellSpacing = 2.5f;
format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash;
table.ResetCells(5, 3, format, 100);
for (int i = 0; i < table.Rows[0].Cells.Count; i++)
{
paragraph = table[0, i].AddParagraph() as WParagraph;
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText(string.Format("Header {0}", i + 1));
text.CharacterFormat.Font = new Font("Bitstream Vera Serif", 10);
text.CharacterFormat.Bold = true;
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(0, 21, 84);
table[0, i].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50);
}
table[0, 2].Width = 200;
for (int i = 1; i < table.Rows.Count; i++)
{
for (int j = 0; j < 3; j++)
{
paragraph = table[i, j].AddParagraph() as WParagraph;
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
if ((i == 2) && (j == 2))
{
text = paragraph.AppendText("Nested Table");
}
else
{
text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1));
}
if ((j == 2))
table[i, j].Width = 200;
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50);
text.CharacterFormat.Bold = true;
}
}
// Adding a nested Table.
IWTable nestTable = table[2, 2].AddTable();
format = new RowFormat();
format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.DotDash;
format.HorizontalAlignment = RowAlignment.Center;
nestTable.ResetCells(3, 3, format, 45);
for (int i = 0; i < nestTable.Rows.Count; i++)
{
for (int j = 0; j < 3; j++)
{
paragraph = nestTable[i, j].AddParagraph() as WParagraph;
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
nestTable[i, j].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(231, 235, 245);
text = paragraph.AppendText(string.Format("Cell {0} , {1}", i, j + 1));
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Black;
text.CharacterFormat.Bold = true;
}
}
#endregion Nested Table
#region Table with Images
Assembly execAssem = typeof(DocIOController).GetTypeInfo().Assembly;
//Add a new section to the document.
section = document.AddSection();
//Add paragraph to the section.
paragraph = section.AddParagraph();
//Writing text.
textRange = paragraph.AppendText("Table with Images");
textRange.CharacterFormat.FontSize = 13f;
textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.DarkBlue;
textRange.CharacterFormat.Bold = true;
//Add paragraph to the section.
section.AddParagraph();
paragraph = section.AddParagraph();
text = null;
//Adding a new Table to the paragraph.
table = section.Body.AddTable();
table.ResetCells(1, 3);
//Adding rows to the table.
WTableRow row = table.Rows[0];
//Set heading row height
row.Height = 25f;
//set heading values to the Table.
for (int i = 0; i < 3; i++)
{
//Add paragraph for writing Text to the cells.
paragraph = (IWParagraph)row.Cells[i].AddParagraph();
//Set Horizontal Alignment as Center.
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
//Writing Row Heading
switch (i)
{
case 0:
text = paragraph.AppendText("SNO");
row.Cells[i].Width = 50f; break;
case 1: text = paragraph.AppendText("Drinks"); break;
case 2: text = paragraph.AppendText("Showcase Image"); row.Cells[i].Width = 200f; break;
}
//Set row Heading formatting
text.CharacterFormat.Bold = true;
text.CharacterFormat.FontName = "Cambria";
text.CharacterFormat.FontSize = 11f;
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White;
//Set row cells formatting
row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row.Cells[i].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(157, 161, 190);
row.Cells[i].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
}
int sno = 1;
//Writing Sno, Product name and Product Images to the Table.
row1 = table.AddRow(false);
//Writing SNO to the table with formatting text.
paragraph = (IWParagraph)row1.Cells[0].AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText(sno.ToString());
text.CharacterFormat.Bold = true;
text.CharacterFormat.FontSize = 10f;
row1.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[0].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
//Writing Product Name to the table with Formatting.
paragraph = (IWParagraph)row1.Cells[1].AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText("Apple Juice");
text.CharacterFormat.Bold = true;
text.CharacterFormat.FontSize = 10f;
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(50, 65, 124);
row1.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[1].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
//Writing Product Images to the Table.
paragraph = (IWParagraph)row1.Cells[2].AddParagraph();
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Apple Juice.png", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
row1.Cells[2].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[2].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[2].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
sno++;
row1 = table.AddRow(false);
//Writing SNO to the table with formatting text.
paragraph = (IWParagraph)row1.Cells[0].AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText(sno.ToString());
text.CharacterFormat.Bold = true;
text.CharacterFormat.FontSize = 10f;
row1.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[0].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
//Writing Product Name to the table with Formatting.
paragraph = (IWParagraph)row1.Cells[1].AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText("Grape Juice");
text.CharacterFormat.Bold = true;
text.CharacterFormat.FontSize = 10f;
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(50, 65, 124);
row1.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[1].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
//Writing Product Images to the Table.
paragraph = (IWParagraph)row1.Cells[2].AddParagraph();
imageStream = new FileStream(basePath + @"/images/DocIO/Grape Juice.png", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
row1.Cells[2].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[2].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[2].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
sno++;
row1 = table.AddRow(false);
//Writing SNO to the table with formatting text.
paragraph = (IWParagraph)row1.Cells[0].AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText(sno.ToString());
text.CharacterFormat.Bold = true;
text.CharacterFormat.FontSize = 10f;
row1.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[0].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
//Writing Product Name to the table with Formatting.
paragraph = (IWParagraph)row1.Cells[1].AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
text = paragraph.AppendText("Hot Soup");
text.CharacterFormat.Bold = true;
text.CharacterFormat.FontSize = 10f;
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(50, 65, 124);
row1.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[1].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
//Writing Product Images to the Table.
paragraph = (IWParagraph)row1.Cells[2].AddParagraph();
imageStream = new FileStream(basePath + @"/images/DocIO/Hot Soup.png", FileMode.Open, FileAccess.Read);
paragraph.AppendPicture(imageStream);
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
row1.Cells[2].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row1.Cells[2].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
row1.Cells[2].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(217, 223, 239);
sno++;
#endregion Table with Images
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
}
#endregion FormatTable
}

Просмотреть файл

@ -1,284 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
string[] products = { "Mango", "Orange", "Grape", "Banana", "Apple", "Green Apple", "Water Melon", "Pine apple", "Guava", "Plums" };
string[] forms = { "Delicious", "Frequent Item" };
IWSection section1;
IWParagraph paragraph = null;
IWTextRange textRange = null;
#region FormatText
public ActionResult FormatText(string Group1)
{
if (Group1 == null)
return View();
//Random number generator.
Random r = new Random();
// List of FontNames.
string[] fontNames = { "Arial" , "Times New Roman" , "Monotype Corsiva" , " Book Antiqua " ,
"Bitstream Vera Sans" , "Comic Sans MS" , "Microsoft Sans Serif" , "Batang" };
// Create a new document.
WordDocument document = new WordDocument();
// Adding a new section to the document.
IWSection section = document.AddSection();
// Adding a new paragraph to the section.
IWParagraph paragraph = section.AddParagraph();
paragraph.AppendText("This sample demonstrates various text and paragraph formatting support.");
section.AddParagraph();
section.AddParagraph();
section = document.AddSection();
section.BreakCode = SectionBreakCode.NoBreak;
//Adding two columns to the section.
section.AddColumn(250, 20);
section.AddColumn(250, 20);
#region Text Formatting
//Create a TextRange
IWTextRange text = null;
// Writing Text with different Formatting styles.
for (int i = 8, j = 0, k = 0; i <= 20; i++, j++, k++)
{
if (j >= fontNames.Length) j = 0;
paragraph = section.AddParagraph();
text = paragraph.AppendText("This is " + "[" + fontNames[j] + "]");
text.CharacterFormat.FontName = fontNames[j];
text.CharacterFormat.UnderlineStyle = (UnderlineStyle)k;
text.CharacterFormat.FontSize = i;
text.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
}
// More formatting options.
section.AddParagraph();
paragraph.ParagraphFormat.ColumnBreakAfter = true;
paragraph = section.AddParagraph();
text = paragraph.AppendText("More formatting Options List...");
text.CharacterFormat.FontName = fontNames[2];
text.CharacterFormat.FontSize = 18;
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.AppendText("AllCaps \n\n").CharacterFormat.AllCaps = true;
paragraph.AppendText("Bold \n\n").CharacterFormat.Bold = true;
paragraph.AppendText("DoubleStrike \n\n").CharacterFormat.DoubleStrike = true;
paragraph.AppendText("Emboss \n\n").CharacterFormat.Emboss = true;
paragraph.AppendText("Engrave \n\n").CharacterFormat.Engrave = true;
paragraph.AppendText("Italic \n\n").CharacterFormat.Italic = true;
paragraph.AppendText("Shadow \n\n").CharacterFormat.Shadow = true;
paragraph.AppendText("SmallCaps \n\n").CharacterFormat.SmallCaps = true;
paragraph.AppendText("Strikeout \n\n").CharacterFormat.Strikeout = true;
paragraph.AppendText("Some Text");
paragraph.AppendText("SubScript \n\n").CharacterFormat.SubSuperScript = SubSuperScript.SubScript;
paragraph.AppendText("Some Text");
paragraph.AppendText("SuperScript \n\n").CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
paragraph.AppendText("TextBackgroundColor \n\n").CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.LightBlue;
#endregion
#region Paragraph formattings
section = document.AddSection();
section.BreakCode = SectionBreakCode.NewPage;
paragraph = section.AddParagraph();
paragraph.AppendText("Following paragraphs illustrates various paragraph formattings");
paragraph = section.AddParagraph();
paragraph.AppendText("We will use this paragraph to illustrate several Microsoft Word features using Essential DocIO. It will be used to illustrate Space Before, Space After, and Line Spacing. Space Before tells Microsoft Word how much space to leave before the paragraph. Space After tells Microsoft Word how much space to leave after the paragraph. Line Spacing sets the space between lines within a paragraph.It also explains about first line indentation,backcolor and paragraph border.");
paragraph.ParagraphFormat.BeforeSpacing = 20f;
paragraph.ParagraphFormat.AfterSpacing = 30f;
paragraph.ParagraphFormat.BackColor = Syncfusion.Drawing.Color.LightGray;
paragraph.ParagraphFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
paragraph.ParagraphFormat.FirstLineIndent = 20f;
paragraph.ParagraphFormat.LineSpacing = 20f;
paragraph = section.AddParagraph();
paragraph.AppendText("This is a sample paragraph. It is used to illustrate alignment. Left-justified text is aligned on the left. Right-justified text is aligned with on the right. Centered text is centered between the left and right margins. You can use Center to center your titles. Justified text is flush on both sides.");
paragraph.ParagraphFormat.LineSpacing = 20f;
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
paragraph.ParagraphFormat.LineSpacingRule = LineSpacingRule.Exactly;
section.AddParagraph();
//Adding a new paragraph to the section.
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.Keep = true;
paragraph.AppendText("KEEP TOGETHER").CharacterFormat.Bold = true;
paragraph.AppendText("This is a sample paragraph. It is used to illustrate Keep together of MsWord. You can control where Microsoft Word positions automatic page breaks (page break: The point at which one page ends and another begins. Microsoft Word inserts an 'automatic' (or soft) page break for you, or you can force a page break at a specific location by inserting a 'manual' (or hard) page break.) by setting pagination options.It keeps the lines in a paragraph together when there is page break").CharacterFormat.FontSize = 12f;
for (int i = 0; i < 10; i++)
{
paragraph.AppendText("Text Body_Text Body_Text Body_Text Body_Text Body_Text Body_Text Body").CharacterFormat.FontSize = 12f;
paragraph.ParagraphFormat.LineSpacing = 20f;
}
paragraph.AppendText("KEEP TOGETHER END").CharacterFormat.Bold = true;
#endregion
#region Bullets and Numbering
// Adding a new section to the document.
section = document.AddSection();
// Adding a new paragraph to the document.
paragraph = section.AddParagraph();
// Writing text to the current paragraph.
paragraph.AppendText("This document demonstrates the Bullets and Numbering functionality available in Essential DocIO");
//Add a new section
section1 = document.AddSection();
//Adding two columns to the section.
section1.Columns.Add(new Column(document));
section1.Columns.Add(new Column(document));
//Set the columns to be of equal width.
section1.MakeColumnsEqual();
// Set section break code as NoBreak.
section1.BreakCode = SectionBreakCode.NoBreak;
// Set formatting.
ProductDetailsInBullets();
// Set Formatting.
ProductDetailsInNumbers();
#endregion Bullets and Numbering
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#region ProductDetailsInBullets
private void ProductDetailsInBullets()
{
// Adding a new paragraph to the document.
section1.AddParagraph();
paragraph = section1.AddParagraph();
// Writing text to the document with formatting.
textRange = paragraph.AppendText("List of Fruits.");
paragraph.ListFormat.ApplyDefBulletStyle();
textRange.CharacterFormat.FontName = "Monotype Corsiva";
textRange.CharacterFormat.FontSize = 15;
// Writing Product details to the document with the specified list type.
section1.AddParagraph();
foreach (string s in products)
{
section1.AddParagraph();
paragraph = section1.AddParagraph();
paragraph.AppendText(s);
paragraph.ListFormat.ContinueListNumbering();
paragraph.ListFormat.ListLevelNumber = 1;
section1.AddParagraph();
foreach (string s1 in forms)
{
if (String.Equals(s, "Plums"))
{
paragraph = section1.AddParagraph();
paragraph.AppendText(s1);
paragraph.ListFormat.ContinueListNumbering();
paragraph.ListFormat.ListLevelNumber = 2;
break;
}
else
{
paragraph = section1.AddParagraph();
paragraph.AppendText(s1);
paragraph.ListFormat.ContinueListNumbering();
paragraph.ListFormat.ListLevelNumber = 2;
}
}
}
}
#endregion
#region ProductDetailsInNumbers
private void ProductDetailsInNumbers()
{
// Adding a new paragraph to the document.
section1.AddParagraph();
paragraph = section1.AddParagraph();
// Writing text to the document with formatting.
textRange = paragraph.AppendText("List of Fruits.");
paragraph.ListFormat.ApplyDefNumberedStyle();
textRange.CharacterFormat.FontName = "Monotype Corsiva";
textRange.CharacterFormat.FontSize = 15;
// Writing Product details to the document with the specified list type.
section1.AddParagraph();
foreach (string s in products)
{
section1.AddParagraph();
paragraph = section1.AddParagraph();
paragraph.AppendText(s);
paragraph.ListFormat.ContinueListNumbering();
paragraph.ListFormat.ListLevelNumber = 1;
section1.AddParagraph();
foreach (string s1 in forms)
{
if (String.Equals(s, "Plums"))
{
paragraph = section1.AddParagraph();
paragraph.AppendText(s1);
paragraph.ListFormat.ContinueListNumbering();
paragraph.ListFormat.ListLevelNumber = 2;
break;
}
else
{
paragraph = section1.AddParagraph();
paragraph.AppendText(s1);
paragraph.ListFormat.ContinueListNumbering();
paragraph.ListFormat.ListLevelNumber = 2;
}
}
}
}
#endregion
#endregion FormatText
}
}

Просмотреть файл

@ -1,295 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
public ActionResult Forms(string Group1)
{
if (Group1 == null)
return View();
#region CreateForm
// Create a new document.
WordDocument document = new WordDocument();
// Adding a new section to the document.
IWSection section = document.AddSection();
// Adding a new paragraph to the section.
IWParagraph paragraph = section.AddParagraph();
#region Document formatting
//Set background color.
document.Background.Gradient.Color1 = Syncfusion.Drawing.Color.FromArgb(232, 232, 232);
document.Background.Gradient.Color2 = Syncfusion.Drawing.Color.FromArgb(255, 255, 255);
document.Background.Type = BackgroundType.Gradient;
document.Background.Gradient.ShadingStyle = GradientShadingStyle.Horizontal;
document.Background.Gradient.ShadingVariant = GradientShadingVariant.ShadingDown;
section.PageSetup.Margins.All = 30f;
section.PageSetup.PageSize = new Syncfusion.Drawing.SizeF(600, 600f);
#endregion
#region Title Section
IWTable table = section.Body.AddTable();
table.ResetCells(1, 2);
WTableRow row = table.Rows[0];
row.Height = 25f;
IWParagraph cellPara = row.Cells[0].AddParagraph();
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Image.jpg", FileMode.Open, FileAccess.Read);
IWPicture pic = cellPara.AppendPicture(imageStream);
pic.Height = 80;
pic.Width = 180;
cellPara = row.Cells[1].AddParagraph();
row.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
row.Cells[1].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(173, 215, 255);
IWTextRange txt = cellPara.AppendText("Job Application Form");
cellPara.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
txt.CharacterFormat.Bold = true;
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 18f;
row.Cells[0].Width = 200;
row.Cells[1].Width = 300;
//row.Cells[1].CellFormat.FitText = true;
row.Cells[1].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Hairline;
#endregion
section.AddParagraph();
#region General Information
table = section.Body.AddTable();
table.TableFormat.Paddings.All = 5.4f;
table.ResetCells(2, 1);
row = table.Rows[0];
row.Height = 20;
row.Cells[0].Width = 500;
cellPara = row.Cells[0].AddParagraph();
row.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Thick;
row.Cells[0].CellFormat.Borders.Color = Syncfusion.Drawing.Color.FromArgb(155, 205, 255);
row.Cells[0].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(198, 227, 255);
row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
txt = cellPara.AppendText(" General Information");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.Bold = true;
txt.CharacterFormat.FontSize = 11f;
row = table.Rows[1];
cellPara = row.Cells[0].AddParagraph();
row.Cells[0].Width = 500;
row.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Hairline;
row.Cells[0].CellFormat.Borders.Color = Syncfusion.Drawing.Color.FromArgb(155, 205, 255);
row.Cells[0].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(222, 239, 255);
txt = cellPara.AppendText("\n Full Name:\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 11f;
WTextFormField txtField = cellPara.AppendTextFormField("John");
txtField.TextRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
txtField.TextRange.CharacterFormat.FontName = "Arial";
txtField.TextRange.CharacterFormat.FontSize = 11f;
txt = cellPara.AppendText("\n\n Birth Date:\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 11f;
txtField = cellPara.AppendTextFormField("BirthDayField", DateTime.Now.ToString("M/d/yyyy"));
txtField.StringFormat = "M/d/yyyy";
txtField.Type = TextFormFieldType.DateText;
txtField.TextRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
txtField.TextRange.CharacterFormat.FontName = "Arial";
txtField.TextRange.CharacterFormat.FontSize = 11f;
txtField.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
txtField.CharacterFormat.FontName = "Arial";
txtField.CharacterFormat.FontSize = 11f;
txt = cellPara.AppendText("\n\n Address:\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 11f;
txtField = cellPara.AppendTextFormField("221b Baker Street");
txtField.Type = TextFormFieldType.RegularText;
txtField.TextRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
txtField.TextRange.CharacterFormat.FontName = "Arial";
txtField.TextRange.CharacterFormat.FontSize = 11f;
txt = cellPara.AppendText("\n\n Phone:\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 11f;
txtField = cellPara.AppendTextFormField("(206)555-3412");
txtField.TextRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
txtField.TextRange.CharacterFormat.FontName = "Arial";
txtField.TextRange.CharacterFormat.FontSize = 11f;
txt = cellPara.AppendText("\n\n Email:\t\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 11f;
txtField = cellPara.AppendTextFormField("John@company.com");
txtField.TextRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
txtField.TextRange.CharacterFormat.FontName = "Arial";
txtField.TextRange.CharacterFormat.FontSize = 11f;
cellPara.AppendText("\n");
#endregion
section.AddParagraph();
#region Educational Qualification
table = section.Body.AddTable();
table.ResetCells(2, 1);
table.TableFormat.Paddings.All = 5.4f;
row = table.Rows[0];
row.Height = 20;
row.Cells[0].Width = 500;
cellPara = row.Cells[0].AddParagraph();
row.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Thick;
row.Cells[0].CellFormat.Borders.Color = Syncfusion.Drawing.Color.FromArgb(155, 205, 255);
row.Cells[0].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(198, 227, 255);
row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
txt = cellPara.AppendText(" Educational Qualification");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.Bold = true;
txt.CharacterFormat.FontSize = 11f;
row = table.Rows[1];
cellPara = row.Cells[0].AddParagraph();
row.Cells[0].Width = 500;
row.Cells[0].CellFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Hairline;
row.Cells[0].CellFormat.Borders.Color = Syncfusion.Drawing.Color.FromArgb(155, 205, 255);
row.Cells[0].CellFormat.BackColor = Syncfusion.Drawing.Color.FromArgb(222, 239, 255);
txt = cellPara.AppendText("\n Type:\t\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 11f;
WDropDownFormField dropField = cellPara.AppendDropDownFormField();
dropField.DropDownItems.Add("Higher");
dropField.DropDownItems.Add("Vocational");
dropField.DropDownItems.Add("Universal");
dropField.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
dropField.CharacterFormat.FontName = "Arial";
dropField.CharacterFormat.FontSize = 11f;
txt = cellPara.AppendText("\n\n Institution:\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 11f;
txtField = cellPara.AppendTextFormField("Michigan University");
txtField.TextRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
txtField.TextRange.CharacterFormat.FontName = "Arial";
txtField.CharacterFormat.FontSize = 11f;
txt = cellPara.AppendText("\n\n Programming Languages:");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 11f;
txt = cellPara.AppendText("\n\n\t C#:\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 9f;
dropField = cellPara.AppendDropDownFormField();
dropField.DropDownItems.Add("Perfect");
dropField.DropDownItems.Add("Good");
dropField.DropDownItems.Add("Excellent");
dropField.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
dropField.CharacterFormat.FontName = "Arial";
dropField.CharacterFormat.FontSize = 11f;
txt = cellPara.AppendText("\n\n\t VB:\t\t\t\t");
txt.CharacterFormat.FontName = "Arial";
txt.CharacterFormat.FontSize = 9f;
dropField = cellPara.AppendDropDownFormField();
dropField.DropDownItems.Add("Perfect");
dropField.DropDownItems.Add("Good");
dropField.DropDownItems.Add("Excellent");
dropField.CharacterFormat.TextColor = Syncfusion.Drawing.Color.MidnightBlue;
dropField.CharacterFormat.FontName = "Arial";
dropField.CharacterFormat.FontSize = 11f;
#endregion
//Protect document
document.ProtectionType = ProtectionType.AllowOnlyFormFields;
MemoryStream st = new MemoryStream();
document.Save(st, FormatType.Doc);
st.Seek(0, SeekOrigin.Begin);
#endregion CreateForm
#region FillForm
// Create a new document.
WordDocument document1 = new WordDocument(st, FormatType.Doc);
IWSection sec = document1.LastSection;
WTextFormField textFF;
WDropDownFormField dropFF;
//Access the text field
textFF = sec.Body.FormFields[0] as WTextFormField;
//Fill value for the textfield
textFF.TextRange.Text = "John";
//Access the form field with feild name
textFF = sec.Body.FormFields["BirthDayField"] as WTextFormField;
textFF.TextRange.Text = "5.13.1980";
textFF = sec.Body.FormFields[2] as WTextFormField;
textFF.TextRange.Text = "221b Baker Street";
textFF = sec.Body.FormFields[3] as WTextFormField;
textFF.TextRange.Text = "(206)555-3412";
textFF = sec.Body.FormFields[4] as WTextFormField;
textFF.TextRange.Text = "John@company.com";
dropFF = sec.Body.FormFields[5] as WDropDownFormField;
//Set the value
dropFF.DropDownSelectedIndex = 1;
textFF = sec.Body.FormFields[6] as WTextFormField;
textFF.TextRange.Text = "Michigan University";
dropFF = sec.Body.FormFields[7] as WDropDownFormField;
dropFF.DropDownSelectedIndex = 1;
dropFF = sec.Body.FormFields[8] as WDropDownFormField;
dropFF.DropDownSelectedIndex = 2;
//Allow only to fill the form.
document1.ProtectionType = ProtectionType.AllowOnlyFormFields;
#endregion FillForm
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
}
}

Просмотреть файл

@ -1,183 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.Reflection;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region HeaderandFooter
public ActionResult HeaderandFooter(string Group1)
{
if (Group1 == null)
return View();
// Creating a new document.
WordDocument doc = new WordDocument();
// Add a new section to the document.
IWSection section1 = doc.AddSection();
// Set the header/footer setup.
section1.PageSetup.DifferentFirstPage = true;
// Inserting Header Footer to first page
InsertFirstPageHeaderFooter(doc, section1);
// Inserting Header Footer to all pages
InsertPageHeaderFooter(doc, section1);
// Add text to the document body section.
IWParagraph par;
par = section1.AddParagraph();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/WinFAQ.txt";
//Insert Text into the word Document.
StreamReader reader = new StreamReader(new FileStream(dataPath,FileMode.Open),System.Text.Encoding.ASCII);
string text = reader.ReadToEnd();
par.AppendText(text);
reader.Dispose();
reader = null;
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
doc.Save(ms, type);
doc.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#region InsertFirstPageHeaderFooter
private void InsertFirstPageHeaderFooter(WordDocument doc, IWSection section)
{
// Add a new paragraph for header to the document.
IWParagraph headerPar = new WParagraph(doc);
// Add a new table to the header.
IWTable table = section.HeadersFooters.FirstPageHeader.AddTable();
RowFormat format = new RowFormat();
// Setting cleared table border style.
format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Cleared;
// Inserting table with a row and two columns.
table.ResetCells(1, 2, format, 265);
// Inserting logo image to the table first cell.
headerPar = table[0, 0].AddParagraph() as WParagraph;
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Northwind_logo.png", FileMode.Open, FileAccess.Read);
headerPar.AppendPicture(imageStream);
//Set Image size
(headerPar.Items[0] as WPicture).Width = 232.5f;
(headerPar.Items[0] as WPicture).Height = 54.75f;
// Inserting text to the table second cell.
headerPar = table[0, 1].AddParagraph() as WParagraph;
IWTextRange txt = headerPar.AppendText("Company Headquarters,\n2501 Aerial Center Parkway,\nSuite 110, Morrisville, NC 27560,\nTEL 1-888-936-8638.");
txt.CharacterFormat.FontSize = 12;
txt.CharacterFormat.CharacterSpacing = 1.7f;
headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
// Add a new paragraph to the header with address text.
headerPar = new WParagraph(doc);
headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
txt = headerPar.AppendText("\nFirst Page Header");
txt.CharacterFormat.CharacterSpacing = 1.7f;
section.HeadersFooters.FirstPageHeader.Paragraphs.Add(headerPar);
// Add a footer paragraph text to the document.
WParagraph footerPar = new WParagraph(doc);
footerPar.ParagraphFormat.Tabs.AddTab(523f, TabJustification.Right, TabLeader.NoLeader);
// Add text.
footerPar.AppendText("Copyright Northwind Inc. 2001 - 2017");
// Add page and Number of pages field to the document.
footerPar.AppendText("\tFirst Page ");
footerPar.AppendField("Page", FieldType.FieldPage);
section.HeadersFooters.FirstPageFooter.Paragraphs.Add(footerPar);
#region Page Number Settings
section.PageSetup.RestartPageNumbering = true;
section.PageSetup.PageStartingNumber = 1;
section.PageSetup.PageNumberStyle = PageNumberStyle.Arabic;
#endregion Page Number Settings
}
#endregion InsertFirstPageHeaderFooter
#region InsertPageHeaderFooter
private void InsertPageHeaderFooter(WordDocument doc, IWSection section1)
{
// Add a new paragraph for header to the document.
IWParagraph headerPar = new WParagraph(doc);
// Add a new table to the header
IWTable table = section1.HeadersFooters.Header.AddTable();
RowFormat format = new RowFormat();
// Setting Single table border style.
format.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.Single;
// Inserting table with a row and two columns.
table.ResetCells(1, 2, format, 265);
// Inserting logo image to the table first cell.
headerPar = table[0, 0].AddParagraph() as WParagraph;
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Northwind_logo.png", FileMode.Open, FileAccess.Read);
headerPar.AppendPicture(imageStream);
//Set Image size.
(headerPar.Items[0] as WPicture).Width = 232.5f;
(headerPar.Items[0] as WPicture).Height = 54.75f;
// Inserting text to the table second cell.
headerPar = table[0, 1].AddParagraph() as WParagraph;
IWTextRange txt = headerPar.AppendText("Company Headquarters,\n2501 Aerial Center Parkway,\nSuite 110, Morrisville, NC 27560,\nTEL 1-888-936-8638.");
txt.CharacterFormat.FontSize = 12;
txt.CharacterFormat.CharacterSpacing = 1.7f;
headerPar.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Right;
// Add a footer paragraph text to the document.
WParagraph footerPar = new WParagraph(doc);
footerPar.ParagraphFormat.Tabs.AddTab(523f, TabJustification.Right, TabLeader.NoLeader);
// Add text.
footerPar.AppendText("Copyright Northwind Inc. 2001 - 2017");
// Add page and Number of pages field to the document.
footerPar.AppendText("\tPage ");
IWField ff = footerPar.AppendField("Page", FieldType.FieldPage);
section1.HeadersFooters.Footer.Paragraphs.Add(footerPar);
#region Page Number Settings
section1.PageSetup.RestartPageNumbering = true;
section1.PageSetup.PageStartingNumber = 1;
section1.PageSetup.PageNumberStyle = PageNumberStyle.Arabic;
#endregion Page Number Settings
}
#endregion InsertPageHeaderFooter
#endregion HeaderandFooter
}
}

Просмотреть файл

@ -1,274 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.Drawing;
using System.IO;
using Microsoft.AspNetCore.Hosting;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public DocIOController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
// GET: /<controller>/
public IActionResult HelloWorld(string Group1)
{
if (Group1 == null)
return View();
//Get the current environment services to access the current physical path
// Creating a new document.
WordDocument document = new WordDocument();
//Adding a new section to the document.
WSection section = document.AddSection() as WSection;
//Set Margin of the section
section.PageSetup.Margins.All = 72;
//Set page size of the section
section.PageSetup.PageSize = new SizeF(612, 792);
//Create Paragraph styles
WParagraphStyle style = document.AddParagraphStyle("Normal") as WParagraphStyle;
style.CharacterFormat.FontName = "Calibri";
style.CharacterFormat.FontSize = 11f;
style.ParagraphFormat.BeforeSpacing = 0;
style.ParagraphFormat.AfterSpacing = 8;
style.ParagraphFormat.LineSpacing = 13.8f;
style = document.AddParagraphStyle("Heading 1") as WParagraphStyle;
style.ApplyBaseStyle("Normal");
style.CharacterFormat.FontName = "Calibri Light";
style.CharacterFormat.FontSize = 16f;
style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(46, 116, 181);
style.ParagraphFormat.BeforeSpacing = 12;
style.ParagraphFormat.AfterSpacing = 0;
style.ParagraphFormat.Keep = true;
style.ParagraphFormat.KeepFollow = true;
style.ParagraphFormat.OutlineLevel = OutlineLevel.Level1;
IWParagraph paragraph = section.HeadersFooters.Header.AddParagraph();
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/AdventureCycle.jpg", FileMode.Open, FileAccess.Read);
WPicture picture = paragraph.AppendPicture(imageStream) as WPicture;
picture.TextWrappingStyle = TextWrappingStyle.InFrontOfText;
picture.VerticalOrigin = VerticalOrigin.Margin;
picture.VerticalPosition = -45;
picture.HorizontalOrigin = HorizontalOrigin.Column;
picture.HorizontalPosition = 263.5f;
picture.WidthScale = 20;
picture.HeightScale = 15;
paragraph.ApplyStyle("Normal");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left;
WTextRange textRange = paragraph.AppendText("Adventure Works Cycles") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Calibri";
textRange.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Red;
//Appends paragraph.
paragraph = section.AddParagraph();
paragraph.ApplyStyle("Heading 1");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
textRange = paragraph.AppendText("Adventure Works Cycles") as WTextRange;
textRange.CharacterFormat.FontSize = 18f;
textRange.CharacterFormat.FontName = "Calibri";
//Appends paragraph.
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.FirstLineIndent = 36;
paragraph.BreakCharacterFormat.FontSize = 12f;
textRange = paragraph.AppendText("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.") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.FirstLineIndent = 36;
paragraph.BreakCharacterFormat.FontSize = 12f;
textRange = paragraph.AppendText("In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
paragraph = section.AddParagraph();
paragraph.ApplyStyle("Heading 1");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Left;
textRange = paragraph.AppendText("Product Overview") as WTextRange;
textRange.CharacterFormat.FontSize = 16f;
textRange.CharacterFormat.FontName = "Calibri";
//Appends table.
IWTable table = section.AddTable();
table.ResetCells(3, 2);
table.TableFormat.Borders.BorderType = Syncfusion.DocIO.DLS.BorderStyle.None;
table.TableFormat.IsAutoResized = true;
//Appends paragraph.
paragraph = table[0, 0].AddParagraph();
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.BreakCharacterFormat.FontSize = 12f;
//Appends picture to the paragraph.
imageStream = new FileStream(basePath + @"/images/DocIO/Mountain-200.jpg", FileMode.Open, FileAccess.Read);
picture = paragraph.AppendPicture(imageStream) as WPicture;
picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom;
picture.VerticalOrigin = VerticalOrigin.Paragraph;
picture.VerticalPosition = 4.5f;
picture.HorizontalOrigin = HorizontalOrigin.Column;
picture.HorizontalPosition = -2.15f;
picture.WidthScale = 79;
picture.HeightScale = 79;
//Appends paragraph.
paragraph = table[0, 1].AddParagraph();
paragraph.ApplyStyle("Heading 1");
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.ParagraphFormat.LineSpacing = 12f;
paragraph.AppendText("Mountain-200");
//Appends paragraph.
paragraph = table[0, 1].AddParagraph();
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.ParagraphFormat.LineSpacing = 12f;
paragraph.BreakCharacterFormat.FontSize = 12f;
paragraph.BreakCharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Product No: BK-M68B-38\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Size: 38\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Weight: 25\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Price: $2,294.99\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
//Appends paragraph.
paragraph = table[0, 1].AddParagraph();
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.ParagraphFormat.LineSpacing = 12f;
paragraph.BreakCharacterFormat.FontSize = 12f;
//Appends paragraph.
paragraph = table[1, 0].AddParagraph();
paragraph.ApplyStyle("Heading 1");
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.ParagraphFormat.LineSpacing = 12f;
paragraph.AppendText("Mountain-300 ");
//Appends paragraph.
paragraph = table[1, 0].AddParagraph();
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.ParagraphFormat.LineSpacing = 12f;
paragraph.BreakCharacterFormat.FontSize = 12f;
paragraph.BreakCharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Product No: BK-M47B-38\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Size: 35\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Weight: 22\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Price: $1,079.99\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
//Appends paragraph.
paragraph = table[1, 0].AddParagraph();
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.ParagraphFormat.LineSpacing = 12f;
paragraph.BreakCharacterFormat.FontSize = 12f;
//Appends paragraph.
paragraph = table[1, 1].AddParagraph();
paragraph.ApplyStyle("Heading 1");
paragraph.ParagraphFormat.LineSpacing = 12f;
//Appends picture to the paragraph.
imageStream = new FileStream(basePath + @"/images/DocIO/Mountain-300.jpg", FileMode.Open, FileAccess.Read);
picture = paragraph.AppendPicture(imageStream) as WPicture;
picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom;
picture.VerticalOrigin = VerticalOrigin.Paragraph;
picture.VerticalPosition = 8.2f;
picture.HorizontalOrigin = HorizontalOrigin.Column;
picture.HorizontalPosition = -14.95f;
picture.WidthScale = 75;
picture.HeightScale = 75;
//Appends paragraph.
paragraph = table[2, 0].AddParagraph();
paragraph.ApplyStyle("Heading 1");
paragraph.ParagraphFormat.LineSpacing = 12f;
//Appends picture to the paragraph.
imageStream = new FileStream(basePath + @"/images/DocIO/Road-550-W.jpg", FileMode.Open, FileAccess.Read);
picture = paragraph.AppendPicture(imageStream) as WPicture;
picture.TextWrappingStyle = TextWrappingStyle.TopAndBottom;
picture.VerticalOrigin = VerticalOrigin.Paragraph;
picture.VerticalPosition = 3.75f;
picture.HorizontalOrigin = HorizontalOrigin.Column;
picture.HorizontalPosition = -5f;
picture.WidthScale = 92;
picture.HeightScale = 92;
//Appends paragraph.
paragraph = table[2, 1].AddParagraph();
paragraph.ApplyStyle("Heading 1");
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.ParagraphFormat.LineSpacing = 12f;
paragraph.AppendText("Road-150 ");
//Appends paragraph.
paragraph = table[2, 1].AddParagraph();
paragraph.ParagraphFormat.AfterSpacing = 0;
paragraph.ParagraphFormat.LineSpacing = 12f;
paragraph.BreakCharacterFormat.FontSize = 12f;
paragraph.BreakCharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Product No: BK-R93R-44\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Size: 44\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Weight: 14\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
textRange = paragraph.AppendText("Price: $3,578.27\r") as WTextRange;
textRange.CharacterFormat.FontSize = 12f;
textRange.CharacterFormat.FontName = "Times New Roman";
//Appends paragraph.
paragraph = table[2, 1].AddParagraph();
paragraph.ApplyStyle("Heading 1");
paragraph.ParagraphFormat.LineSpacing = 12f;
//Appends paragraph.
section.AddParagraph();
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
}
}

Просмотреть файл

@ -1,110 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Reflection;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
string dataPath2;
#region ImageInsertion
public ActionResult ImageInsertion(string Group1)
{
if (Group1 == null)
return View();
//Create a new document
WordDocument document = new WordDocument();
//Adding a new section to the document.
IWSection section = document.AddSection();
//Adding a paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Writing text.
paragraph.AppendText("This sample demonstrates how to insert Vector and Scalar images inside a document.");
//Adding a new paragraph
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/yahoo.gif", FileMode.Open, FileAccess.Read);
//Inserting .gif .
WPicture picture = (WPicture)paragraph.AppendPicture(imageStream);
//Adding Image caption
picture.AddCaption("Yahoo [.gif Image]", CaptionNumberingFormat.Roman, CaptionPosition.AboveImage);
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
imageStream = new FileStream(basePath + @"/images/DocIO/Reports.bmp", FileMode.Open, FileAccess.Read);
//Inserting .bmp
picture = (WPicture)paragraph.AppendPicture(imageStream);
//Adding Image caption
picture.AddCaption("Reports [.bmp Image]", CaptionNumberingFormat.Roman, CaptionPosition.AboveImage);
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
imageStream = new FileStream(basePath + @"/images/DocIO/google.png", FileMode.Open, FileAccess.Read);
//Inserting .png
picture = (WPicture)paragraph.AppendPicture(imageStream);
//Adding Image caption
picture.AddCaption("Google [.png Image]", CaptionNumberingFormat.Roman, CaptionPosition.AboveImage);
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
imageStream = new FileStream(basePath + @"/images/DocIO/Square.tif", FileMode.Open, FileAccess.Read);
//Inserting .tif
picture = (WPicture)paragraph.AppendPicture(imageStream);
//Adding Image caption
picture.AddCaption("Square [.tif Image]", CaptionNumberingFormat.Roman, CaptionPosition.AboveImage);
//Adding a new paragraph.
paragraph = section.AddParagraph();
//Setting Alignment for the image.
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
imageStream = new FileStream(basePath + @"/images/DocIO/Ess chart.emf", FileMode.Open, FileAccess.Read);
//Inserting .wmf Image to the document.
WPicture mImage = (WPicture)paragraph.AppendPicture(imageStream);
//Scaling Image
mImage.HeightScale = 50f;
mImage.WidthScale = 50f;
//Adding Image caption
mImage.AddCaption("Chart Vector Image", CaptionNumberingFormat.Roman, CaptionPosition.AboveImage);
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion ImageInsertion
}
}

Просмотреть файл

@ -1,182 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Reflection;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region InsertBreak
public ActionResult InsertBreak(string Group1)
{
if (Group1 == null)
return View();
//Creating a new document
WordDocument document = new WordDocument();
//Adding a new section.
IWSection section = document.AddSection();
IWParagraph paragraph = section.AddParagraph();
paragraph = section.AddParagraph();
section.PageSetup.Margins.All = 20f;
IWTextRange text = paragraph.AppendText("Adventure products");
//Formatting Text
text.CharacterFormat.FontName = "Bitstream Vera Sans";
text.CharacterFormat.FontSize = 12f;
text.CharacterFormat.Bold = true;
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.LineSpacing = 20f;
paragraph.AppendText("In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group ");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;
#region Line break
paragraph.AppendBreak(BreakType.LineBreak);
paragraph.AppendBreak(BreakType.LineBreak);
#endregion Line break
section = document.AddSection();
section.BreakCode = SectionBreakCode.NoBreak;
section.PageSetup.Margins.All = 20f;
//Adding three columns to section.
section.AddColumn(100, 15);
section.AddColumn(100, 15);
section.AddColumn(100, 15);
//Set the columns to be of equal width.
section.MakeColumnsEqual();
//Adding a new paragraph to the section.
paragraph = section.AddParagraph();
//Adding text.
text = paragraph.AppendText("Mountain-200");
//Formatting Text
text.CharacterFormat.FontName = "Bitstream Vera Sans";
text.CharacterFormat.FontSize = 12f;
text.CharacterFormat.Bold = true;
//Adding a new paragraph to the section.
section.AddParagraph();
paragraph = section.AddParagraph();
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Mountain-200.jpg", FileMode.Open, FileAccess.Read);
//Inserting an Image.
WPicture picture = paragraph.AppendPicture(imageStream) as WPicture;
picture.Width = 120f;
picture.Height = 90f;
//Adding a new paragraph to the section.
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.LineSpacing = 20f;
//Adding text.
paragraph.AppendText(@"Product No:BK-M68B-38" + "\n" + "Size: 38" + "\n" + "Weight: 25\n" + "Price: $2,294.99");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;
// Set column break as true. It navigates the cursor position to the next Column.
paragraph.ParagraphFormat.ColumnBreakAfter = true;
paragraph = section.AddParagraph();
text = paragraph.AppendText("Mountain-300");
text.CharacterFormat.FontName = "Bitstream Vera Sans";
text.CharacterFormat.FontSize = 12f;
text.CharacterFormat.Bold = true;
section.AddParagraph();
paragraph = section.AddParagraph();
imageStream = new FileStream(basePath + @"/images/DocIO/Mountain-300.jpg", FileMode.Open, FileAccess.Read);
picture = paragraph.AppendPicture(imageStream) as WPicture;
picture.Width = 120f;
picture.Height = 90f;
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.LineSpacing = 20f;
paragraph.AppendText(@"Product No:BK-M4-38" + "\n" + "Size: 35\n" + "Weight: 22" + "\n" + "Price: $1,079.99");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;
paragraph.ParagraphFormat.ColumnBreakAfter = true;
paragraph = section.AddParagraph();
text = paragraph.AppendText("Road-150");
text.CharacterFormat.FontName = "Bitstream Vera Sans";
text.CharacterFormat.FontSize = 12f;
text.CharacterFormat.Bold = true;
section.AddParagraph();
paragraph = section.AddParagraph();
imageStream = new FileStream(basePath + @"/images/DocIO/Road-550-W.jpg", FileMode.Open, FileAccess.Read);
picture = paragraph.AppendPicture(imageStream) as WPicture;
picture.Width = 120f;
picture.Height = 90f;
section.AddParagraph();
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.LineSpacing = 20f;
paragraph.AppendText(@"Product No: BK-R93R-44" + "\n" + "Size: 44" + "\n" + "Weight: 14" + "\n" + "Price: $3,578.27");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;
section = document.AddSection();
section.BreakCode = SectionBreakCode.NoBreak;
section.PageSetup.Margins.All = 20f;
text = section.AddParagraph().AppendText("First Look\n");
//Formatting Text
text.CharacterFormat.FontName = "Bitstream Vera Sans";
text.CharacterFormat.FontSize = 12f;
text.CharacterFormat.Bold = true;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.LineSpacing = 20f;
paragraph.AppendText(@"Adventure Works Cycles, the fictitious company, 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.");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;
paragraph.ParagraphFormat.PageBreakAfter = true;
paragraph = section.AddParagraph();
text = paragraph.AppendText("Introduction\n");
//Formatting Text
text.CharacterFormat.FontName = "Bitstream Vera Sans";
text.CharacterFormat.FontSize = 12f;
text.CharacterFormat.Bold = true;
paragraph = section.AddParagraph();
paragraph.ParagraphFormat.LineSpacing = 20f;
paragraph.AppendText(@"In 2000, Adventure Works Cycles bought a small manufacturing plant, Importadores Neptuno, located in Mexico. Importadores Neptuno manufactures several critical subcomponents for the Adventure Works Cycles product line. These subcomponents are shipped to the Bothell location for final product assembly. In 2001, Importadores Neptuno, became the sole manufacturer and distributor of the touring bicycle product group.");
paragraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion InsertBreak
}
}

Просмотреть файл

@ -1,86 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region InsertOLEObject
public ActionResult InsertOLEObject(string Group1)
{
if (Group1 == null)
return View();
//Data folder path is resolved from requested page physical path.
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/OleTemplate.doc";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
WordDocument oleSource;
if (Group1 == ".doc")
//Open an existing word document
oleSource = new WordDocument(fileStream, FormatType.Doc);
else
//Open an existing word document
oleSource = new WordDocument(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
WordDocument dest = new WordDocument();
dest.EnsureMinimal();
// Get OLE object from source document
WOleObject oleObject = oleSource.LastParagraph.Items[0] as WOleObject;
WPicture pic = oleObject.OlePicture.Clone() as WPicture;
dest.LastParagraph.AppendText("OLE Object Demo");
dest.LastParagraph.ApplyStyle(BuiltinStyle.Heading1);
dest.LastParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center;
dest.Sections[0].AddParagraph();
dest.LastParagraph.AppendText("Adobe PDF object Inserted");
dest.LastParagraph.ApplyStyle(BuiltinStyle.Heading2);
dest.Sections[0].AddParagraph();
// AppendOLE object to the destination document
dest.LastParagraph.AppendOleObject(oleObject.Container, pic, OleLinkType.Embed);
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
dest.Save(ms, type);
dest.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion InsertOLEObject
}
}

Просмотреть файл

@ -1,197 +0,0 @@
#region Copyright
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Data;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Xml;
using System.Collections.Generic;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region MacroPreservation
public ActionResult MacroPreservation(string Button)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/MacroTemplate.dotm";
string contenttype1 = "application/msword";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Button == null)
return View();
if (Button == "View Template")
{
return File(fileStream, contenttype1, "MacroTemplate.dotm");
}
try
{
string dataPathMacro = basePath + @"/DocIO/MacroTemplate.dotm";
fileStream = new FileStream(dataPathMacro, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// Load the template.
WordDocument document = new WordDocument(fileStream,FormatType.Dotm);
fileStream.Dispose();
fileStream = null;
//Create MailMergeDataTable
MailMergeDataTable mailMergeDataTableProductListData = GetMailMergeDataTableProductListData();
// Execute Mail Merge with groups.
document.MailMerge.ExecuteGroup(mailMergeDataTableProductListData);
#region Document SaveOption
//Save as .docm format
FormatType type = FormatType.Word2013Docm;
string filename = "Sample.docm";
string contenttype = "application/msword";
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
catch (Exception)
{ }
return View();
}
#endregion MacroPreservation
/// <summary>
/// Gets the mail merge data table.
/// </summary>
private MailMergeDataTable GetMailMergeDataTableProductListData()
{
List<Products> product = new List<Products>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/ProductList.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "ProductList")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "ProductList")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Products":
product.Add(GetProductsDetails(reader));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "ProductList") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable = new MailMergeDataTable("Products", product);
reader.Dispose();
fs.Dispose();
return dataTable;
}
/// <summary>
/// Gets the products.
/// </summary>
/// <param name="reader">The reader.</param>
private Products GetProductsDetails(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Products")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
Products product = new Products();
while (reader.LocalName != "Products")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "ProductName":
product.ProductName = reader.ReadElementContentAsString();
break;
case "Binary":
product.Binary = reader.ReadElementContentAsString();
break;
case "Source":
product.Source = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Products") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return product;
}
}
public class Products
{
#region Fields
private string m_productName;
private string m_binary;
private string m_source;
#endregion
#region Properties
public string ProductName
{
get { return m_productName; }
set { m_productName = value; }
}
public string Binary
{
get { return m_binary; }
set { m_binary = value; }
}
public string Source
{
get { return m_source; }
set { m_source = value; }
}
#endregion
#region Constructor
public Products(string productName, string binary, string source)
{
m_productName = productName;
m_binary = binary;
m_source = source;
}
public Products()
{ }
#endregion
}
}

Просмотреть файл

@ -1,351 +0,0 @@
#region Copyright
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Data;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
public ActionResult MailMergeEvent(string Group1, string Button)
{
string basePath = _hostingEnvironment.WebRootPath;
string contenttype1 = "application/msword";
string dataPath = basePath + @"/DocIO/MailMergeEventTemplate.doc";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Group1 == null)
return View();
if (Button == "View Template")
{
return File(fileStream, contenttype1, "MailMergeEventTemplate.doc");
}
fileStream.Dispose();
fileStream = null;
try
{
// Load the template.
FileStream fileStreamPath = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
WordDocument document = new WordDocument(fileStreamPath, FormatType.Doc);
fileStreamPath.Dispose();
fileStreamPath = null;
// Using Merge events to do conditional formatting during runtime.
document.MailMerge.MergeField += new MergeFieldEventHandler(AlternateRows_MergeField);
document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_ProductImage);
//Create MailMergeDataTable
MailMergeDataTable mailMergeDataTablePriceList = GetMailMergeDataTablePriceList();
MailMergeDataTable mailMergeDataTableProductData = GetMailMergeDataTableProductData();
// Execute Mail Merge with groups.
document.MailMerge.ExecuteGroup(mailMergeDataTablePriceList);
document.MailMerge.ExecuteGroup(mailMergeDataTableProductData);
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
catch (Exception)
{ }
return View();
}
private void AlternateRows_MergeField(object sender, MergeFieldEventArgs args)
{
// Conditionally format data during Merge.
if (args.RowIndex % 2 == 0)
{
args.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(255, 102, 0);
}
}
private void MergeField_ProductImage(object sender, MergeImageFieldEventArgs args)
{
// Get the image from disk during Merge.
if (args.FieldName == "ProductImage")
{
string ProductFileName = args.FieldValue.ToString();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/images/DocIO/"+ ProductFileName, FileMode.Open, FileAccess.Read);
args.ImageStream = fs;
}
}
/// <summary>
/// Gets the mail merge data table.
/// </summary>
private MailMergeDataTable GetMailMergeDataTablePriceList()
{
List<Product_PriceList> product_PriceList = new List<Product_PriceList>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/ProductPriceList.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Products")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "Products")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Product_PriceList":
product_PriceList.Add(GetProduct_PriceList(reader));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Products") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable1 = new MailMergeDataTable("Product_PriceList", product_PriceList);
reader.Dispose();
fs.Dispose();
return dataTable1;
}
/// <summary>
/// Gets the product price list.
/// </summary>
/// <param name="reader">The reader.</param>
private Product_PriceList GetProduct_PriceList(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Product_PriceList")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
Product_PriceList product_PriceList = new Product_PriceList();
while (reader.LocalName != "Product_PriceList")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "ProductName":
product_PriceList.ProductName = reader.ReadElementContentAsString();
break;
case "Price":
product_PriceList.Price = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Product_PriceList") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return product_PriceList;
}
/// <summary>
/// Gets the mail merge data table.
/// </summary>
private MailMergeDataTable GetMailMergeDataTableProductData()
{
List<ProductDetail> productDetail = new List<ProductDetail>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/Product.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "ProductList")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "ProductList")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Products":
productDetail.Add(GetProductDetail(reader));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "ProductList") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable2 = new MailMergeDataTable("ProductDetail", productDetail);
reader.Dispose();
fs.Dispose();
return dataTable2;
}
/// <summary>
/// Gets the product details.
/// </summary>
/// <param name="reader">The reader.</param>
private ProductDetail GetProductDetail(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Products")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
ProductDetail productDetail = new ProductDetail();
while (reader.LocalName != "Products")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "SNO":
productDetail.SNO = reader.ReadElementContentAsString();
break;
case "ProductName":
productDetail.ProductName = reader.ReadElementContentAsString();
break;
case "ProductImage":
productDetail.ProductImage = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Products") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return productDetail;
}
}
public class Product_PriceList
{
#region Fields
private string m_productName;
private string m_price;
#endregion
#region Properties
public string ProductName
{
get { return m_productName; }
set { m_productName = value; }
}
public string Price
{
get { return m_price; }
set { m_price = value; }
}
#endregion
#region Constructor
public Product_PriceList(string productName, string price)
{
m_productName = productName;
m_price = price;
}
public Product_PriceList()
{ }
}
#endregion
public class ProductDetail
{
#region Fields
private string m_sNO;
private string m_productName;
private string m_productImage;
#endregion
#region Properties
public string SNO
{
get { return m_sNO; }
set { m_sNO = value; }
}
public string ProductName
{
get { return m_productName; }
set { m_productName = value; }
}
public string ProductImage
{
get { return m_productImage; }
set { m_productImage = value; }
}
#endregion
#region Constructor
public ProductDetail(string sNO, string productName, string productImage)
{
m_sNO = sNO;
m_productName = productName;
m_productImage = productImage;
}
public ProductDetail()
{ }
#endregion
}
}

Просмотреть файл

@ -1,813 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Collections;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.IO;
using System.Xml;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
// GET: /<controller>/
public IActionResult NestedMailMerge(string Group1, string Group2, string Group3, string Button)
{
if (Group1 == null || Group2 == null || Group3 == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
if (Group2 == "Report")
dataPath = basePath + @"/DocIO/Template_Report.doc";
else
dataPath = basePath + @"/DocIO/Template_Letter.doc";
string contenttype1 = "application/msword";
string dataPath1 = basePath + @"/DocIO/Template_Report.doc";
string dataPath2 = basePath + @"/DocIO/Template_Letter.doc";
FileStream fileStream1 = new FileStream(dataPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
FileStream fileStream2 = new FileStream(dataPath2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Button == "View Template")
{
if (Group2 == "Report")
return File(fileStream1,contenttype1, "Template_Report.doc");
else
return File(fileStream2, contenttype1, "Template_Letter.doc");
}
fileStream1.Dispose();
fileStream1 = null;
fileStream2.Dispose();
fileStream2 = null;
// Creating a new document.
WordDocument document = new WordDocument();
// Load template
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
#region Execute Mail merge
if (Group3 == "Explicit")
{
MailMergeDataSet dataSet = GetMailMergeDataSet(basePath);
List<DictionaryEntry> commands = new List<DictionaryEntry>();
//DictionaryEntry contain "Source table" (KEY) and "Command" (VALUE)
DictionaryEntry entry = new DictionaryEntry("Employees", string.Empty);
commands.Add(entry);
// To retrive customer details
entry = new DictionaryEntry("Customers", "EmployeeID = %Employees.EmployeeID%");
commands.Add(entry);
// To retrieve order details
entry = new DictionaryEntry("Orders", "CustomerID = %Customers.CustomerID%");
commands.Add(entry);
//Executes nested Mail merge using explicit relational data.
document.MailMerge.ExecuteNestedGroup(dataSet, commands);
}
else
{
MailMergeDataTable dataTable = GetMailMergeDataTable(basePath);
//Executes nested Mail merge using implicit relational data.
document.MailMerge.ExecuteNestedGroup(dataTable);
}
#endregion
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#region Mail merge data
/// <summary>
/// Gets the mail merge data set.
/// </summary>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private MailMergeDataSet GetMailMergeDataSet(string basePath)
{
List<EmployeeDetails> employees = new List<EmployeeDetails>();
List<CustomerDetails> customers = new List<CustomerDetails>();
List<OrderDetails> orders = new List<OrderDetails>();
FileStream stream = new FileStream(basePath + @"/DocIO/Employees.xml", FileMode.OpenOrCreate);
XmlReader reader = XmlReader.Create(stream);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "EmployeesList")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "EmployeesList")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Employees":
employees.Add(GetEmployee(reader, customers, orders));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "EmployeesList") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
reader.Dispose();
stream.Dispose();
MailMergeDataSet dataSet = new MailMergeDataSet();
dataSet.Add(new MailMergeDataTable("Employees", employees));
dataSet.Add(new MailMergeDataTable("Customers", customers));
dataSet.Add(new MailMergeDataTable("Orders", orders));
return dataSet;
}
/// <summary>
/// Gets the employee.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="customers">The customers.</param>
/// <param name="orders">The orders.</param>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private EmployeeDetails GetEmployee(XmlReader reader, List<CustomerDetails> customers, List<OrderDetails> orders)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Employees")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
EmployeeDetails employee = new EmployeeDetails();
while (reader.LocalName != "Employees")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "EmployeeID":
employee.EmployeeID = reader.ReadElementContentAsString();
break;
case "LastName":
employee.LastName = reader.ReadElementContentAsString();
break;
case "FirstName":
employee.FirstName = reader.ReadElementContentAsString();
break;
case "Address":
employee.Address = reader.ReadElementContentAsString();
break;
case "City":
employee.City = reader.ReadElementContentAsString();
break;
case "Country":
employee.Country = reader.ReadElementContentAsString();
break;
case "Extension":
employee.Extension = reader.ReadElementContentAsString();
break;
case "Customers":
customers.Add(GetCustomer(reader, orders));
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Employees") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return employee;
}
/// <summary>
/// Gets the customer.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="orders">The orders.</param>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private CustomerDetails GetCustomer(XmlReader reader, List<OrderDetails> orders)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Customers")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
CustomerDetails customer = new CustomerDetails();
while (reader.LocalName != "Customers")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "EmployeeID":
customer.EmployeeID = reader.ReadElementContentAsString();
break;
case "CustomerID":
customer.CustomerID = reader.ReadElementContentAsString();
break;
case "CompanyName":
customer.CompanyName = reader.ReadElementContentAsString();
break;
case "ContactName":
customer.ContactName = reader.ReadElementContentAsString();
break;
case "City":
customer.City = reader.ReadElementContentAsString();
break;
case "Country":
customer.Country = reader.ReadElementContentAsString();
break;
case "Orders":
orders.Add(GetOrders(reader));
break;
}
reader.Read();
}
else
{
reader.Read();
if ((reader.LocalName == "Customers") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return customer;
}
/// <summary>
/// Gets the mail merge data table.
/// </summary>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private MailMergeDataTable GetMailMergeDataTable(string basePath)
{
List<EmployeeDetailsImplicit> employees = new List<EmployeeDetailsImplicit>();
FileStream stream = new FileStream(basePath + @"/DocIO/Employees.xml", FileMode.OpenOrCreate);
XmlReader reader = XmlReader.Create(stream);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "EmployeesList")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "EmployeesList")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Employees":
employees.Add(GetEmployee(reader));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "EmployeesList") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
reader.Dispose();
stream.Dispose();
MailMergeDataTable dataTable = new MailMergeDataTable("Employees", employees);
return dataTable;
}
/// <summary>
/// Gets the employee.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private EmployeeDetailsImplicit GetEmployee(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Employees")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
EmployeeDetailsImplicit employee = new EmployeeDetailsImplicit();
while (reader.LocalName != "Employees")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "EmployeeID":
employee.EmployeeID = reader.ReadElementContentAsString();
break;
case "LastName":
employee.LastName = reader.ReadElementContentAsString();
break;
case "FirstName":
employee.FirstName = reader.ReadElementContentAsString();
break;
case "Address":
employee.Address = reader.ReadElementContentAsString();
break;
case "City":
employee.City = reader.ReadElementContentAsString();
break;
case "Country":
employee.Country = reader.ReadElementContentAsString();
break;
case "Extension":
employee.Extension = reader.ReadElementContentAsString();
break;
case "Customers":
employee.Customers.Add(GetCustomer(reader));
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Employees") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return employee;
}
/// <summary>
/// Gets the customer.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private CustomerDetailsImplicit GetCustomer(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Customers")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
CustomerDetailsImplicit customer = new CustomerDetailsImplicit();
while (reader.LocalName != "Customers")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "EmployeeID":
customer.EmployeeID = reader.ReadElementContentAsString();
break;
case "CustomerID":
customer.CustomerID = reader.ReadElementContentAsString();
break;
case "CompanyName":
customer.CompanyName = reader.ReadElementContentAsString();
break;
case "ContactName":
customer.ContactName = reader.ReadElementContentAsString();
break;
case "City":
customer.City = reader.ReadElementContentAsString();
break;
case "Country":
customer.Country = reader.ReadElementContentAsString();
break;
case "Orders":
customer.Orders.Add(GetOrders(reader));
break;
}
reader.Read();
}
else
{
reader.Read();
if ((reader.LocalName == "Customers") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return customer;
}
/// <summary>
/// Gets the orders.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private OrderDetails GetOrders(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Orders")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
OrderDetails order = new OrderDetails();
while (reader.LocalName != "Orders")
{
if (reader.NodeType != XmlNodeType.EndElement)
{
switch (reader.LocalName)
{
case "OrderID":
order.OrderID = reader.ReadElementContentAsString();
break;
case "CustomerID":
order.CustomerID = reader.ReadElementContentAsString();
break;
case "OrderDate":
order.OrderDate = reader.ReadElementContentAsString();
break;
case "RequiredDate":
order.RequiredDate = reader.ReadElementContentAsString();
break;
case "ShippedDate":
order.ShippedDate = reader.ReadElementContentAsString();
break;
}
reader.Read();
}
else
{
reader.Read();
if ((reader.LocalName == "Orders") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return order;
}
#endregion
}
#region Mailmerge data objects
public class EmployeeDetailsImplicit
{
#region Fields
private string m_employeeID;
private string m_lastName;
private string m_firstName;
private string m_address;
private string m_city;
private string m_country;
private string m_extension;
private List<CustomerDetailsImplicit> m_customers;
#endregion
#region Properties
public string EmployeeID
{
get { return m_employeeID; }
set { m_employeeID = value; }
}
public string LastName
{
get { return m_lastName; }
set { m_lastName = value; }
}
public string FirstName
{
get { return m_firstName; }
set { m_firstName = value; }
}
public string Address
{
get { return m_address; }
set { m_address = value; }
}
public string City
{
get { return m_city; }
set { m_city = value; }
}
public string Country
{
get { return m_country; }
set { m_country = value; }
}
public string Extension
{
get { return m_extension; }
set { m_extension = value; }
}
public List<CustomerDetailsImplicit> Customers
{
get
{
if (m_customers == null)
m_customers = new List<CustomerDetailsImplicit>();
return m_customers;
}
set
{
m_customers = value;
}
}
#endregion
#region Constructor
public EmployeeDetailsImplicit()
{
m_customers = new List<CustomerDetailsImplicit>();
}
#endregion
}
public class CustomerDetailsImplicit
{
#region Fields
private string m_employeeID;
private string m_customerID;
private string m_companyName;
private string m_city;
private string m_country;
private List<OrderDetails> m_orders;
#endregion
#region Properties
public List<OrderDetails> Orders
{
get
{
if (m_orders == null)
m_orders = new List<OrderDetails>();
return m_orders;
}
set
{
m_orders = value;
}
}
public string EmployeeID
{
get { return m_employeeID; }
set { m_employeeID = value; }
}
public string CustomerID
{
get { return m_customerID; }
set { m_customerID = value; }
}
public string CompanyName
{
get { return m_companyName; }
set { m_companyName = value; }
}
public string ContactName
{
get { return m_companyName; }
set { m_companyName = value; }
}
public string City
{
get { return m_city; }
set { m_city = value; }
}
public string Country
{
get { return m_country; }
set { m_country = value; }
}
#endregion
#region Constructor
public CustomerDetailsImplicit()
{
m_orders = new List<OrderDetails>();
}
#endregion
}
public class EmployeeDetails
{
#region Fields
private string m_employeeID;
private string m_lastName;
private string m_firstName;
private string m_address;
private string m_city;
private string m_country;
private string m_extension;
#endregion
#region Properties
public string EmployeeID
{
get { return m_employeeID; }
set { m_employeeID = value; }
}
public string LastName
{
get { return m_lastName; }
set { m_lastName = value; }
}
public string FirstName
{
get { return m_firstName; }
set { m_firstName = value; }
}
public string Address
{
get { return m_address; }
set { m_address = value; }
}
public string City
{
get { return m_city; }
set { m_city = value; }
}
public string Country
{
get { return m_country; }
set { m_country = value; }
}
public string Extension
{
get { return m_extension; }
set { m_extension = value; }
}
#endregion
}
public class CustomerDetails
{
#region Fields
private string m_employeeID;
private string m_customerID;
private string m_companyName;
private string m_city;
private string m_country;
#endregion
#region Properties
public string EmployeeID
{
get { return m_employeeID; }
set { m_employeeID = value; }
}
public string CustomerID
{
get { return m_customerID; }
set { m_customerID = value; }
}
public string CompanyName
{
get { return m_companyName; }
set { m_companyName = value; }
}
public string ContactName
{
get { return m_companyName; }
set { m_companyName = value; }
}
public string City
{
get { return m_city; }
set { m_city = value; }
}
public string Country
{
get { return m_country; }
set { m_country = value; }
}
#endregion
}
public class OrderDetails
{
#region Fields
private string m_orderID;
private string m_customerID;
private string m_orderDate;
private string m_requiredDate;
private string m_shippedDate;
#endregion
#region Properties
public string OrderID
{
get { return m_orderID; }
set { m_orderID = value; }
}
public string CustomerID
{
get { return m_customerID; }
set { m_customerID = value; }
}
public string OrderDate
{
get { return m_orderDate; }
set { m_orderDate = value; }
}
public string RequiredDate
{
get { return m_requiredDate; }
set { m_requiredDate = value; }
}
public string ShippedDate
{
get { return m_shippedDate; }
set { m_shippedDate = value; }
}
#endregion
}
#endregion
}

Просмотреть файл

@ -1,302 +0,0 @@
#region Copyright
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.OfficeChart;
using System.Data;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Xml;
using System;
using Syncfusion.DocIORenderer;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Pie Chart
public ActionResult PieChart(string Group1)
{
if (Group1 == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string datapath = basePath + @"/DocIO/PieChart.docx";
//A new document is created.
FileStream fileStream = new FileStream(datapath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
WordDocument document = new WordDocument(fileStream,FormatType.Docx);
//Create MailMergeDataTable
MailMergeDataTable mailMergeDataTable = GetMailMergeDataTableProductDetails();
//Merge the product table in the Word document
document.MailMerge.ExecuteGroup(mailMergeDataTable);
//Find the Placeholder of Pie chart to insert
TextSelection selection = document.Find("<Pie Chart>", false, false);
WParagraph paragraph = selection.GetAsOneRange().OwnerParagraph;
paragraph.ChildEntities.Clear();
//Create and Append chart to the paragraph
WChart pieChart = paragraph.AppendChart(446, 270);
//Set chart data
pieChart.ChartType = OfficeChartType.Pie;
pieChart.ChartTitle = "Best Selling Products";
pieChart.ChartTitleArea.FontName = "Calibri (Body)";
pieChart.ChartTitleArea.Size = 14;
GetChartData(pieChart, 0);
//Create a new chart series with the name “Sales”
IOfficeChartSerie pieSeries = pieChart.Series.Add("Sales");
pieSeries.Values = pieChart.ChartData[2, 2, 11, 2];
//Setting data label
pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsPercentage = true;
pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside;
//Setting background color
pieChart.ChartArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242);
pieChart.PlotArea.Fill.ForeColor = Syncfusion.Drawing.Color.FromArgb(242, 242, 242);
pieChart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None;
pieChart.PrimaryCategoryAxis.CategoryLabels = pieChart.ChartData[2, 1, 11, 1];
string filename = "";
string contenttype = "";
MemoryStream ms = new MemoryStream();
#region Document SaveOption
if (Group1 == "WordDocx")
{
filename = "Sample.docx";
contenttype = "application/msword";
document.Save(ms, FormatType.Docx);
}
else if (Group1 == "WordML")
{
filename = "Sample.xml";
contenttype = "application/msword";
document.Save(ms, FormatType.WordML);
}
else
{
filename = "Sample.pdf";
contenttype = "application/pdf";
DocIORenderer renderer = new DocIORenderer();
renderer.ConvertToPDF(document).Save(ms);
}
#endregion Document SaveOption
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion
/// <summary>
/// Gets the mail merge data table.
/// </summary>
private MailMergeDataTable GetMailMergeDataTableProductDetails()
{
List<Product> product = new List<Product>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/Products.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Products")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "Products")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Product":
product.Add(GetProduct(reader));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Products") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable = new MailMergeDataTable("Product", product);
reader.Dispose();
fs.Dispose();
return dataTable;
}
/// <summary>
/// Gets the products.
/// </summary>
/// <param name="reader">The reader.</param>
private Product GetProduct(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Product")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
Product product = new Product();
while (reader.LocalName != "Product")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "SNO":
product.SNO = reader.ReadElementContentAsString();
break;
case "ProductName":
product.ProductName = reader.ReadElementContentAsString();
break;
case "Sum":
product.Sum = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Product") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return product;
}
/// <summary>
/// Gets the mail merge data table.
/// </summary>
private void GetChartData(WChart pieChart, int i)
{
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/Products.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Products")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "Products")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Product":
GetProductData(reader,pieChart,ref i);
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Products") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
}
/// <summary>
/// Gets the products.
/// </summary>
/// <param name="reader">The reader.</param>
private void GetProductData(XmlReader reader,WChart pieChart,ref int i)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Product")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "Product")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "ProductName":
pieChart.ChartData.SetValue(i + 2, 1, reader.ReadElementContentAsString());
break;
case "Sum":
pieChart.ChartData.SetValue(i + 2, 2, Convert.ToDouble(reader.ReadElementContentAsString()));
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Product") && reader.NodeType == XmlNodeType.EndElement)
{
i++;
break;
}
}
}
}
}
public class Product
{
#region Fields
private string m_sNo;
private string m_productName;
private string m_sum;
#endregion
#region Properties
public string SNO
{
get { return m_sNo; }
set { m_sNo = value; }
}
public string ProductName
{
get { return m_productName; }
set { m_productName = value; }
}
public string Sum
{
get { return m_sum; }
set { m_sum = value; }
}
#endregion
#region Constructor
public Product(string sNO, string productName, string sum)
{
m_sNo = sNO;
m_productName = productName;
m_sum = sum;
}
public Product()
{ }
#endregion
}
}

Просмотреть файл

@ -1,76 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.IO;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region RTF to Doc
public ActionResult RTFToDoc(string Group1)
{
if (Group1 == null)
return View();
if (Request.Form.Files != null)
{
var extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();
if (extension == ".rtf")
{
MemoryStream stream = new MemoryStream();
Request.Form.Files[0].CopyTo(stream);
WordDocument document = new WordDocument(stream, FormatType.Rtf);
stream.Dispose();
stream = null;
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
else
{
ViewBag.Message = string.Format("Please choose RTF document to convert to Word document");
}
}
else
{
ViewBag.Message = string.Format("Browse a RTF document and then click the button to convert as a Word document");
}
return View();
}
#endregion RTF to Doc
}
}

Просмотреть файл

@ -1,72 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region RTL Support
public ActionResult RTLSupport(string Group1)
{
if (Group1 == null)
return View();
// Creating a new document.
WordDocument document = new WordDocument();
document.EnsureMinimal();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/Arabic.txt";
// Reading Arabic text from text file.
StreamReader s = new StreamReader(new FileStream(dataPath, FileMode.Open), System.Text.Encoding.ASCII);
string text = s.ReadToEnd();
s.Dispose();
s = null;
// Appending Arabic text to the document.
document.LastParagraph.ParagraphFormat.Bidi = true;
IWTextRange txtRange = document.LastParagraph.AppendText(text);
txtRange.CharacterFormat.Bidi = true;
// Set the RTL text font size.
txtRange.CharacterFormat.FontSizeBidi = 16;
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion RTL SUpport
}
}

Просмотреть файл

@ -1,706 +0,0 @@
#region Copyright
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections;
using System.Data;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.IO;
using Syncfusion.Pdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Data.SqlClient;
using System.Xml;
using System.Collections.Generic;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
public ActionResult SalesInvoice(int id, string SaveOption, string Button)
{
ArrayList orderID = GetTestOrderID();
ViewData.Add("id", new SelectList(orderID));
if (SaveOption == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/SalesInvoiceDemo.doc";
string contenttype1 = "application/msword";
FileStream fileStreamPath = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Button == "View Template")
return File(fileStreamPath, contenttype1, "SalesInvoiceDemo.doc");
// Create a new document
WordDocument doc = new WordDocument();
// Load the template.
string dataPathSales = basePath + @"/DocIO/SalesInvoiceDemo.doc";
FileStream fileStream = new FileStream(dataPathSales, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
doc.Open(fileStream, FormatType.Automatic);
//Create MailMergeDataTable
MailMergeDataTable mailMergeDataTableOrder = GetTestOrder(id);
MailMergeDataTable mailMergeDataTableOrderTotals = GetTestOrderTotals(id);
MailMergeDataTable mailMergeDataTableOrderDetails = GetTestOrderDetails(id);
// Execute Mail Merge with groups.
doc.MailMerge.ExecuteGroup(mailMergeDataTableOrder);
doc.MailMerge.ExecuteGroup(mailMergeDataTableOrderTotals);
// Using Merge events to do conditional formatting during runtime.
doc.MailMerge.MergeField += new MergeFieldEventHandler(MailMerge_MergeField);
doc.MailMerge.ExecuteGroup(mailMergeDataTableOrderDetails);
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (SaveOption == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (SaveOption == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
doc.Save(ms, type);
doc.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
private void MailMerge_MergeField(object sender, MergeFieldEventArgs args)
{
// Conditionally format data during Merge.
if (args.RowIndex % 2 == 0)
{
args.CharacterFormat.TextColor = Syncfusion.Drawing.Color.DarkBlue;
}
}
private MailMergeDataTable GetTestOrder(int TestOrderId)
{
List<TestOrder> orders = new List<TestOrder>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/TestOrder.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "TestOrders")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "TestOrders")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "TestOrder":
TestOrder testOrder = GetTestOrder(reader);
if (testOrder.OrderID == TestOrderId.ToString())
{
orders.Add(testOrder);
break;
}
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "TestOrders") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable = new MailMergeDataTable("Orders", orders);
reader.Dispose();
fs.Dispose();
return dataTable;
}
private MailMergeDataTable GetTestOrderDetails(int TestOrderId)
{
List<TestOrderDetail> orders = new List<TestOrderDetail>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/TestOrderDetails.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "TestOrderDetails")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "TestOrderDetails")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "TestOrderDetail":
TestOrderDetail testOrder = GetTestOrderDetail(reader);
if (testOrder.OrderID == TestOrderId.ToString())
{
orders.Add(testOrder);
break;
}
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "TestOrderDetails") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable = new MailMergeDataTable("Order", orders);
reader.Dispose();
fs.Dispose();
return dataTable;
}
private MailMergeDataTable GetTestOrderTotals(int TestOrderId)
{
List<TestOrderTotal> orders = new List<TestOrderTotal>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/OrderTotals.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "TestOrderTotals")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "TestOrderTotals")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "TestOrderTotal":
TestOrderTotal testOrder = GetTestOrderTotal(reader);
if (testOrder.OrderID == TestOrderId.ToString())
{
orders.Add(testOrder);
break;
}
break;
}
reader.Read();
}
else
{
reader.Read();
if ((reader.LocalName == "TestOrderTotals") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable = new MailMergeDataTable("OrderTotals", orders);
reader.Dispose();
fs.Dispose();
return dataTable;
}
private TestOrder GetTestOrder(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "TestOrder")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
TestOrder testOrder = new TestOrder();
while (reader.LocalName != "TestOrder")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "ShipName":
testOrder.ShipName = reader.ReadElementContentAsString();
break;
case "ShipAddress":
testOrder.ShipAddress = reader.ReadElementContentAsString();
break;
case "ShipCity":
testOrder.ShipCity = reader.ReadElementContentAsString();
break;
case "ShipPostalCode":
testOrder.ShipPostalCode = reader.ReadElementContentAsString();
break;
case "ShipCountry":
testOrder.ShipCountry = reader.ReadElementContentAsString();
break;
case "PostalCode":
testOrder.PostalCode = reader.ReadElementContentAsString();
break;
case "CustomerID":
testOrder.CustomerID = reader.ReadElementContentAsString();
break;
case "Customers.CompanyName":
testOrder.Customers_CompanyName = reader.ReadElementContentAsString();
break;
case "HomePage":
testOrder.Salesperson = reader.ReadElementContentAsString();
break;
case "Address":
testOrder.Address = reader.ReadElementContentAsString();
break;
case "City":
testOrder.City = reader.ReadElementContentAsString();
break;
case "Country":
testOrder.Country = reader.ReadElementContentAsString();
break;
case "OrderID":
testOrder.OrderID = reader.ReadElementContentAsString();
break;
case "OrderDate":
testOrder.OrderDate = reader.ReadElementContentAsString();
break;
case "RequiredDate":
testOrder.RequiredDate = reader.ReadElementContentAsString();
break;
case "ShippedDate":
testOrder.ShippedDate = reader.ReadElementContentAsString();
break;
case "Shippers.CompanyName":
testOrder.Shippers_CompanyName = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "TestOrders") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return testOrder;
}
private ArrayList GetTestOrderID()
{
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/TestOrder.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "TestOrders")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
ArrayList orderId = new ArrayList();
while (reader.LocalName != "TestOrders")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "OrderID":
orderId.Add(reader.ReadElementContentAsString());
break;
default:
break;
}
reader.Read();
}
else
{
reader.Read();
if ((reader.LocalName == "TestOrders") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return orderId;
}
private TestOrderDetail GetTestOrderDetail(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "TestOrderDetail")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
TestOrderDetail testOrderDetail = new TestOrderDetail();
while (reader.LocalName != "TestOrderDetail")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "OrderID":
testOrderDetail.OrderID = reader.ReadElementContentAsString();
break;
case "ProductID":
testOrderDetail.ProductID = reader.ReadElementContentAsString();
break;
case "ProductName":
testOrderDetail.ProductName = reader.ReadElementContentAsString();
break;
case "UnitPrice":
testOrderDetail.UnitPrice = reader.ReadElementContentAsString();
break;
case "Quantity":
testOrderDetail.Quantity = reader.ReadElementContentAsString();
break;
case "Discount":
testOrderDetail.Discount = reader.ReadElementContentAsString();
break;
case "ExtendedPrice":
testOrderDetail.ExtendedPrice = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "TestOrderDetail") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return testOrderDetail;
}
private TestOrderTotal GetTestOrderTotal(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "TestOrderTotal")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
TestOrderTotal testOrderTotal = new TestOrderTotal();
while (reader.LocalName != "TestOrderTotal")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "OrderID":
testOrderTotal.OrderID = reader.ReadElementContentAsString();
break;
case "Subtotal":
testOrderTotal.Subtotal = reader.ReadElementContentAsString();
break;
case "Freight":
testOrderTotal.Freight = reader.ReadElementContentAsString();
break;
case "Total":
testOrderTotal.Total = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "TestOrderTotal") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return testOrderTotal;
}
}
public class TestOrderDetail
{
#region Fields
private string m_orderID;
private string m_productID;
private string m_productName;
private string m_unitPrice;
private string m_quantity;
private string m_discount;
private string m_extendedPrice;
#endregion
#region Properties
public string OrderID
{
get { return m_orderID; }
set { m_orderID = value; }
}
public string ProductID
{
get { return m_productID; }
set { m_productID = value; }
}
public string ProductName
{
get { return m_productName; }
set { m_productName = value; }
}
public string UnitPrice
{
get { return m_unitPrice; }
set { m_unitPrice = value; }
}
public string Quantity
{
get { return m_quantity; }
set { m_quantity = value; }
}
public string Discount
{
get { return m_discount; }
set { m_discount = value; }
}
public string ExtendedPrice
{
get { return m_extendedPrice; }
set { m_extendedPrice = value; }
}
#endregion
#region Constructor
public TestOrderDetail()
{ }
#endregion
}
public class TestOrderTotal
{
#region Fields
private string m_orderID;
private string m_subTotal;
private string m_freight;
private string m_total;
#endregion
#region Properties
public string OrderID
{
get { return m_orderID; }
set { m_orderID = value; }
}
public string Subtotal
{
get { return m_subTotal; }
set { m_subTotal = value; }
}
public string Freight
{
get { return m_freight; }
set { m_freight = value; }
}
public string Total
{
get { return m_total; }
set { m_total = value; }
}
#endregion
#region Constructor
public TestOrderTotal()
{ }
#endregion
}
public class TestOrder
{
#region Fields
private string m_orderID;
private string m_shipName;
private string m_shipAddress;
private string m_shipCity;
private string m_shipPostalCode;
private string m_shipCountry;
private string m_customerID;
private string m_address;
private string m_postalCode;
private string m_city;
private string m_country;
private string m_salesPerson;
private string m_customersCompanyName;
private string m_orderDate;
private string m_requiredDate;
private string m_shippedDate;
private string m_shippersCompanyName;
#endregion
#region Properties
public string ShipName
{
get { return m_shipName; }
set { m_shipName = value; }
}
public string ShipAddress
{
get { return m_shipAddress; }
set { m_shipAddress = value; }
}
public string ShipCity
{
get { return m_shipCity; }
set { m_shipCity = value; }
}
public string ShipPostalCode
{
get { return m_shipPostalCode; }
set { m_shipPostalCode = value; }
}
public string PostalCode
{
get { return m_postalCode; }
set { m_postalCode = value; }
}
public string ShipCountry
{
get { return m_shipCountry; }
set { m_shipCountry = value; }
}
public string CustomerID
{
get { return m_customerID; }
set { m_customerID = value; }
}
public string Customers_CompanyName
{
get { return m_customersCompanyName; }
set { m_customersCompanyName = value; }
}
public string Address
{
get { return m_address; }
set { m_address = value; }
}
public string City
{
get { return m_city; }
set { m_city = value; }
}
public string Country
{
get { return m_country; }
set { m_country = value; }
}
public string Salesperson
{
get { return m_salesPerson; }
set { m_salesPerson = value; }
}
public string OrderID
{
get { return m_orderID; }
set { m_orderID = value; }
}
public string OrderDate
{
get { return m_orderDate; }
set { m_orderDate = value; }
}
public string RequiredDate
{
get { return m_requiredDate; }
set { m_requiredDate = value; }
}
public string ShippedDate
{
get { return m_shippedDate; }
set { m_shippedDate = value; }
}
public string Shippers_CompanyName
{
get { return m_shippersCompanyName; }
set { m_shippersCompanyName = value; }
}
#endregion
#region Constructor
public TestOrder()
{ }
#endregion
}
}

Просмотреть файл

@ -1,87 +0,0 @@
#region Copyright
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.Pdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
public ActionResult SimpleReplace(string Group1, string Button, string MatchCase, string MatchWholeWord,
string FindText, string ReplaceText, string ReplaceFirst)
{
if (Group1 == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath1 = basePath + @"/DocIO/Adventure.docx";
string contenttype1 = "application/vnd.ms-word.document.12";
FileStream fileStream = new FileStream(dataPath1, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Button == "View Template")
return File(fileStream, contenttype1, "Adventure.docx");
fileStream.Dispose();
fileStream = null;
try
{
string dataPath2 = basePath + @"/DocIO/Adventure.docx";
FileStream fileStream1 = new FileStream(dataPath2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Load template document
WordDocument doc = new WordDocument(fileStream1,FormatType.Docx);
fileStream1.Dispose();
fileStream1 = null;
//Replaces only the first occurrence of the text
if (ReplaceFirst == "ReplaceFirst")
doc.ReplaceFirst = true;
//Replace the text that matches the case and whole word
doc.Replace(FindText, ReplaceText, MatchCase == "MatchCase", MatchWholeWord == "MatchWholeWord");
try
{
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
doc.Save(ms, type);
doc.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
catch (Exception)
{ }
}
catch (Exception)
{ }
return View();
}
}
}

Просмотреть файл

@ -1,303 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.Drawing;
using System.IO;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Styles
public ActionResult Styles(string Group1, string Group2)
{
if (Group1 == null)
return View();
WordDocument document = null;
#region Built-in Style
if (Group1 == "Built-in")
{
document = new WordDocument();
WSection section = document.AddSection() as WSection;
WParagraph para = section.AddParagraph() as WParagraph;
section.AddColumn(100, 100);
section.AddColumn(100, 100);
section.MakeColumnsEqual();
#region List Style
//List
//para = section.AddParagraph() as WParagraph;
para.AppendText("This para is written with style List").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.List);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
//List5 style
para = section.AddParagraph() as WParagraph;
para.AppendText("\nThis para is written with style List5").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.List5);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
#endregion
#region ListNumber Style
//List Number style
para = section.AddParagraph() as WParagraph;
para.AppendText("\nThis para is written with style ListNumber").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.ListNumber);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
//List Number5 style
para = section.AddParagraph() as WParagraph;
para.AppendText("\nThis para is written with style ListNumber5").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.ListNumber5);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
#endregion
#region TOA Heading Style
//TOA Heading
para = section.AddParagraph() as WParagraph;
para.ParagraphFormat.AfterSpacing = 10;
para.AppendText("\nThis para is written with style TOA Heading").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.ToaHeading);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
#endregion
section.BreakCode = SectionBreakCode.NewColumn;
#region ListBullet Style
//ListBullet
para = section.AddParagraph() as WParagraph;
para.AppendText("\nThis para is written with style ListBullet").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.ListBullet);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
//ListBullet5
para = section.AddParagraph() as WParagraph;
para.AppendText("\nThis para is written with style ListBullet5").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.ListBullet5);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
#endregion
#region List Continue Style
//ListContinue
para = section.AddParagraph() as WParagraph;
para.AppendText("\nThis para is written with style ListContinue").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.ListContinue);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
//ListContinue5
para = section.AddParagraph() as WParagraph;
para.AppendText("\nThis para is written with style ListContinue5").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.ListContinue5);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
#endregion
#region HTMLSample Style
//HtmlSample
para = section.AddParagraph() as WParagraph;
para.AppendText("\nThis para is written with style HtmlSample").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.HtmlSample);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
#endregion
section = document.AddSection() as WSection;
section.BreakCode = SectionBreakCode.NoBreak;
#region Document Map Style
//Docuemnt Map
para = section.AddParagraph() as WParagraph;
para.AppendText("This para is written with style DocumentMap\n").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.DocumentMap);
para.AppendText("Google Chrome\n").CharacterFormat.TextColor = Syncfusion.Drawing.Color.White;
para.AppendText("Mozilla Firefox\n").CharacterFormat.TextColor = Syncfusion.Drawing.Color.White;
para.AppendText("Internet Explorer").CharacterFormat.TextColor = Syncfusion.Drawing.Color.White;
#endregion
#region Heading Styles
//Heading Styles
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading1);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading2);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading3);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading4);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading5);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading6);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading7);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading8);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.Heading9);
para.AppendText("Hello World. This para is written with style " + para.StyleName.ToString());
#endregion
#region MessageHeaderStyle
//MessageHeader
para = section.AddParagraph() as WParagraph;
para = section.AddParagraph() as WParagraph;
para.AppendText("This para is written with style MessageHeader\n").CharacterFormat.UnderlineStyle = UnderlineStyle.Double;
para = section.AddParagraph() as WParagraph;
para.ApplyStyle(BuiltinStyle.MessageHeader);
para.AppendText("Google Chrome\n");
para.AppendText("Mozilla Firefox\n");
para.AppendText("Internet Explorer");
#endregion
}
#endregion Built-in Style
#region Custom Style
else
{
document = new WordDocument();
IWParagraphStyle style = null;
// Adding a new section to the document.
WSection section = document.AddSection() as WSection;
//Set Margin of the section
section.PageSetup.Margins.All = 72;
IWParagraph par = document.LastSection.AddParagraph();
WTextRange range = par.AppendText("Using CustomStyles") as WTextRange;
range.CharacterFormat.TextBackgroundColor = Syncfusion.Drawing.Color.Red;
range.CharacterFormat.TextColor = Syncfusion.Drawing.Color.White;
range.CharacterFormat.FontSize = 18f;
document.LastParagraph.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Center; // Create Paragraph styles
style = document.AddParagraphStyle("MyStyle_Normal");
style.CharacterFormat.FontName = "Bitstream Vera Serif";
style.CharacterFormat.FontSize = 10f;
style.ParagraphFormat.HorizontalAlignment = Syncfusion.DocIO.DLS.HorizontalAlignment.Justify;
style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(0, 21, 84);
style = document.AddParagraphStyle("MyStyle_Low");
style.CharacterFormat.FontName = "Times New Roman";
style.CharacterFormat.FontSize = 16f;
style.CharacterFormat.Bold = true;
style = document.AddParagraphStyle("MyStyle_Medium");
style.CharacterFormat.FontName = "Monotype Corsiva";
style.CharacterFormat.FontSize = 18f;
style.CharacterFormat.Bold = true;
style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(51, 66, 125);
style = document.AddParagraphStyle("Mystyle_High");
style.CharacterFormat.FontName = "Bitstream Vera Serif";
style.CharacterFormat.FontSize = 20f;
style.CharacterFormat.Bold = true;
style.CharacterFormat.TextColor = Syncfusion.Drawing.Color.FromArgb(242, 151, 50);
IWParagraph paragraph = null;
for (int i = 0; i < document.Styles.Count; i++)
{
//Skip to apply the document default styles and also paragraph style.
if (document.Styles[i].Name == "Normal" || document.Styles[i].Name == "Default Paragraph Font"
|| document.Styles[i].StyleType != StyleType.ParagraphStyle)
continue;
// Getting styles from Document.
style = (IWParagraphStyle)document.Styles[i];
// Adding a new paragraph
section.AddParagraph();
paragraph = section.AddParagraph();
// Applying styles to the current paragraph.
paragraph.ApplyStyle(style.Name);
// Writing Text with the current style and formatting.
paragraph.AppendText("Northwind Database with [" + style.Name + "] Style");
// Adding a new paragraph
section.AddParagraph();
paragraph = section.AddParagraph();
// Applying another style to the current paragraph.
paragraph.ApplyStyle("MyStyle_Normal");
// Writing text with current style.
paragraph.AppendText("The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases. Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data.");
}
}
#endregion Custom Style
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group2 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group2 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion Styles
}
}

Просмотреть файл

@ -1,466 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Xml;
using System;
using Syncfusion.Drawing;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Table Styles
public ActionResult TableStyles(string Group1, string Group2)
{
if (Group1 == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/DocIO/TemplateTableStyle.doc";
WordDocument document = new WordDocument();
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
document.Open(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
//Create MailMergeDataTable
MailMergeDataTable mailMergeDataTable = GetMailMergeDataTable();
// Execute Mail Merge with groups.
document.MailMerge.ExecuteGroup(mailMergeDataTable);
#region Built-in Style
if (Group1 == "Built-in")
{
//Get table to apply style.
WTable table = (WTable)document.LastSection.Tables[0];
//Apply built-in table style to the table.
table.ApplyStyle(BuiltinTableStyle.MediumShading1Accent5);
}
#endregion Built-in Style
#region Custom Style
else
{
#region Custom table styles
//Get table to apply style
WTable table = (WTable)document.LastSection.Tables[0];
//Apply custom table style to the table
#region Apply Table style
WTableStyle tableStyle = document.AddTableStyle("Tablestyle") as WTableStyle;
Color borderColor = Color.WhiteSmoke;
Color firstRowBackColor = Color.Blue;
Color backColor = Color.WhiteSmoke;
ConditionalFormattingStyle firstRowStyle, lastRowStyle, firstColumnStyle, lastColumnStyle, oddColumnBandingStyle, oddRowBandingStyle, evenRowBandingStyle;
#region Table Properties
tableStyle.TableProperties.RowStripe = 1;
tableStyle.TableProperties.ColumnStripe = 1;
tableStyle.TableProperties.LeftIndent = 0;
tableStyle.TableProperties.Paddings.Top = 0;
tableStyle.TableProperties.Paddings.Bottom = 0;
tableStyle.TableProperties.Paddings.Left = 5.4f;
tableStyle.TableProperties.Paddings.Right = 5.4f;
tableStyle.TableProperties.Borders.Top.BorderType = BorderStyle.Single;
tableStyle.TableProperties.Borders.Top.LineWidth = 1f;
tableStyle.TableProperties.Borders.Top.Color = Color.AliceBlue;
tableStyle.TableProperties.Borders.Top.Space = 0;
tableStyle.TableProperties.Borders.Bottom.BorderType = BorderStyle.Single;
tableStyle.TableProperties.Borders.Bottom.LineWidth = 1f;
tableStyle.TableProperties.Borders.Bottom.Color = borderColor;
tableStyle.TableProperties.Borders.Bottom.Space = 0;
tableStyle.TableProperties.Borders.Left.BorderType = BorderStyle.Single;
tableStyle.TableProperties.Borders.Left.LineWidth = 1f;
tableStyle.TableProperties.Borders.Left.Color = borderColor;
tableStyle.TableProperties.Borders.Left.Space = 0;
tableStyle.TableProperties.Borders.Right.BorderType = BorderStyle.Single;
tableStyle.TableProperties.Borders.Right.LineWidth = 1f;
tableStyle.TableProperties.Borders.Right.Color = borderColor;
tableStyle.TableProperties.Borders.Right.Space = 0;
tableStyle.TableProperties.Borders.Horizontal.BorderType = BorderStyle.Single;
tableStyle.TableProperties.Borders.Horizontal.LineWidth = 1f;
tableStyle.TableProperties.Borders.Horizontal.Color = borderColor;
tableStyle.TableProperties.Borders.Horizontal.Space = 0;
#endregion
#region Conditional Formatting Properties
#region First Row Conditional Formatting Style
firstRowStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.FirstRow);
#region Character format
firstRowStyle.CharacterFormat.Bold = true;
firstRowStyle.CharacterFormat.BoldBidi = true;
firstRowStyle.CharacterFormat.TextColor = Color.FromArgb(255, 255, 255, 255);
#endregion
#region Table Cell Properties
firstRowStyle.CellProperties.Borders.Top.BorderType = BorderStyle.Single;
firstRowStyle.CellProperties.Borders.Top.LineWidth = 1f;
firstRowStyle.CellProperties.Borders.Top.Color = borderColor;
firstRowStyle.CellProperties.Borders.Top.Space = 0;
firstRowStyle.CellProperties.Borders.Bottom.BorderType = BorderStyle.Single;
firstRowStyle.CellProperties.Borders.Bottom.LineWidth = 1f;
firstRowStyle.CellProperties.Borders.Bottom.Color = borderColor;
firstRowStyle.CellProperties.Borders.Bottom.Space = 0;
firstRowStyle.CellProperties.Borders.Left.BorderType = BorderStyle.Single;
firstRowStyle.CellProperties.Borders.Left.LineWidth = 1f;
firstRowStyle.CellProperties.Borders.Left.Color = borderColor;
firstRowStyle.CellProperties.Borders.Left.Space = 0;
firstRowStyle.CellProperties.Borders.Right.BorderType = BorderStyle.Single;
firstRowStyle.CellProperties.Borders.Right.LineWidth = 1f;
firstRowStyle.CellProperties.Borders.Right.Color = borderColor;
firstRowStyle.CellProperties.Borders.Right.Space = 0;
firstRowStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;
firstRowStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;
firstRowStyle.CellProperties.BackColor = firstRowBackColor;
firstRowStyle.CellProperties.ForeColor = Color.FromArgb(0, 255, 255, 255);
firstRowStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
#endregion
#endregion
#region Last Row Conditional Formatting Style
lastRowStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.LastRow);
#region Character format
lastRowStyle.CharacterFormat.Bold = true;
lastRowStyle.CharacterFormat.BoldBidi = true;
#endregion
#region Table Cell Properties
lastRowStyle.CellProperties.Borders.Top.BorderType = BorderStyle.Double;
lastRowStyle.CellProperties.Borders.Top.LineWidth = .75f;
lastRowStyle.CellProperties.Borders.Top.Color = borderColor;
lastRowStyle.CellProperties.Borders.Top.Space = 0;
lastRowStyle.CellProperties.Borders.Bottom.BorderType = BorderStyle.Single;
lastRowStyle.CellProperties.Borders.Bottom.LineWidth = 1f;
lastRowStyle.CellProperties.Borders.Bottom.Color = borderColor;
lastRowStyle.CellProperties.Borders.Bottom.Space = 0;
lastRowStyle.CellProperties.Borders.Left.BorderType = BorderStyle.Single;
lastRowStyle.CellProperties.Borders.Left.LineWidth = 1f;
lastRowStyle.CellProperties.Borders.Left.Color = borderColor;
lastRowStyle.CellProperties.Borders.Left.Space = 0;
lastRowStyle.CellProperties.Borders.Right.BorderType = BorderStyle.Single;
lastRowStyle.CellProperties.Borders.Right.LineWidth = 1f;
lastRowStyle.CellProperties.Borders.Right.Color = borderColor;
lastRowStyle.CellProperties.Borders.Right.Space = 0;
lastRowStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;
lastRowStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;
#endregion
#endregion
#region First Column Conditional Formatting Style
firstColumnStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.FirstColumn);
#region Character format
firstColumnStyle.CharacterFormat.Bold = true;
firstColumnStyle.CharacterFormat.BoldBidi = true;
#endregion
#endregion
#region Last Column Conditional Formatting Style
lastColumnStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.LastColumn);
#region Character format
lastColumnStyle.CharacterFormat.Bold = true;
lastColumnStyle.CharacterFormat.BoldBidi = true;
#endregion
#endregion
#region Odd Column Banding Conditional Formatting Style
oddColumnBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.OddColumnBanding);
#region Table Cell Properties
oddColumnBandingStyle.CellProperties.BackColor = backColor;
oddColumnBandingStyle.CellProperties.ForeColor = Color.FromArgb(0, 255, 255, 255);
oddColumnBandingStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
#endregion
#endregion
#region Odd Row Banding Conditional Formatting Style
oddRowBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.OddRowBanding);
#region Table Cell Properties
oddRowBandingStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;
oddRowBandingStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;
oddRowBandingStyle.CellProperties.BackColor = backColor;
oddRowBandingStyle.CellProperties.ForeColor = Color.FromArgb(0, 255, 255, 255);
oddRowBandingStyle.CellProperties.TextureStyle = TextureStyle.TextureNone;
#endregion
#endregion
#region Even Row Banding Conditional Formatting Style
evenRowBandingStyle = tableStyle.ConditionalFormattingStyles.Add(ConditionalFormattingType.EvenRowBanding);
#region Table Cell Properties
evenRowBandingStyle.CellProperties.Borders.Horizontal.BorderType = BorderStyle.Cleared;
evenRowBandingStyle.CellProperties.Borders.Vertical.BorderType = BorderStyle.Cleared;
#endregion
#endregion
#endregion
#endregion
table.ApplyStyle("Tablestyle");
#endregion
}
#endregion Custom Style
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .xml format
if (Group2 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion Table Styles
/// <summary>
/// Gets the mail merge data table.
/// </summary>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private MailMergeDataTable GetMailMergeDataTable()
{
List<Suppliers> suppliers = new List<Suppliers>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/Suppliers.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "SuppliersList")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "SuppliersList")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "Suppliers":
suppliers.Add(GetSupplier(reader));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "SuppliersList") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable = new MailMergeDataTable("Suppliers", suppliers);
reader.Dispose();
fs.Dispose();
return dataTable;
}
/// <summary>
/// Gets the suppliers.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns></returns>
/// <exception cref="System.Exception">reader</exception>
/// <exception cref="XmlException">Unexpected xml tag + reader.LocalName</exception>
private Suppliers GetSupplier(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "Suppliers")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
Suppliers supplier = new Suppliers();
while (reader.LocalName != "Suppliers")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "SupplierID":
supplier.SupplierID = reader.ReadElementContentAsString();
break;
case "CompanyName":
supplier.CompanyName = reader.ReadElementContentAsString();
break;
case "ContactName":
supplier.ContactName = reader.ReadElementContentAsString();
break;
case "ContactTitle":
supplier.ContactTitle = reader.ReadElementContentAsString();
break;
case "Region":
supplier.Region = reader.ReadElementContentAsString();
break;
case "PostalCode":
supplier.PostalCode = reader.ReadElementContentAsString();
break;
case "Phone":
supplier.Phone = reader.ReadElementContentAsString();
break;
case "Fax":
supplier.Fax = reader.ReadElementContentAsString();
break;
case "HomePage":
supplier.HomePage = reader.ReadElementContentAsString();
break;
case "Address":
supplier.Address = reader.ReadElementContentAsString();
break;
case "City":
supplier.City = reader.ReadElementContentAsString();
break;
case "Country":
supplier.Country = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "Suppliers") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return supplier;
}
}
public class Suppliers
{
#region Fields
private string m_id;
private string m_companyName;
private string m_contactName;
private string m_address;
private string m_city;
private string m_country;
private string m_contactTitle;
private string m_region;
private string m_postalCode;
private string m_phone;
private string m_fax;
private string m_homePage;
#endregion
#region Properties
public string SupplierID
{
get { return m_id; }
set { m_id = value; }
}
public string CompanyName
{
get { return m_companyName; }
set { m_companyName = value; }
}
public string ContactName
{
get { return m_contactName; }
set { m_contactName = value; }
}
public string ContactTitle
{
get { return m_contactTitle; }
set { m_contactTitle = value; }
}
public string Region
{
get { return m_region; }
set { m_region = value; }
}
public string PostalCode
{
get { return m_postalCode; }
set { m_postalCode = value; }
}
public string Phone
{
get { return m_phone; }
set { m_phone = value; }
}
public string Fax
{
get { return m_fax; }
set { m_fax = value; }
}
public string HomePage
{
get { return m_homePage; }
set { m_homePage = value; }
}
public string Address
{
get { return m_address; }
set { m_address = value; }
}
public string City
{
get { return m_city; }
set { m_city = value; }
}
public string Country
{
get { return m_country; }
set { m_country = value; }
}
#endregion
#region Constructor
public Suppliers(string id, string companyName, string contantName, string address, string city, string country)
{
m_id = id;
m_companyName = companyName;
m_contactName = contantName;
m_address = address;
m_city = city;
m_country = country;
}
public Suppliers()
{ }
#endregion
}
}

Просмотреть файл

@ -1,226 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System.Data;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.Pdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Update Fields
public ActionResult UpdateFields(string Group1, string Button)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/TemplateUpdateFields.docx";
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (Group1 == null)
return View();
string contenttype1 = "application/vnd.ms-word.document.12";
if (Button == "View Template")
{
return File(fileStream, contenttype1, "TemplateUpdateFields.docx");
}
//Loads the template document.
string dataPathField = basePath + @"/DocIO/TemplateUpdateFields.docx";
FileStream fileStreamField = new FileStream(dataPathField, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
WordDocument document = new WordDocument(fileStreamField,FormatType.Docx);
fileStreamField.Dispose();
fileStreamField = null;
//Create MailMergeDataTable
MailMergeDataTable mailMergeDataTableStock = GetMailMergeDataTableStock();
// Execute Mail Merge with groups.
document.MailMerge.ExecuteGroup(mailMergeDataTableStock);
//Update fields in the document.
document.UpdateDocumentFields();
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#endregion Update Fields
/// <summary>
/// Gets the mail merge data table.
/// </summary>
private MailMergeDataTable GetMailMergeDataTableStock()
{
List<StockDetails> stockDetails = new List<StockDetails>();
FileStream fs = new FileStream(_hostingEnvironment.WebRootPath + @"/DocIO/StockDetails.xml", FileMode.Open, FileAccess.Read);
XmlReader reader = XmlReader.Create(fs);
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "StockMarket")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
while (reader.LocalName != "StockMarket")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "StockDetails":
stockDetails.Add(GetStockDetails(reader));
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "StockMarket") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
MailMergeDataTable dataTable = new MailMergeDataTable("StockDetails", stockDetails);
reader.Dispose();
fs.Dispose();
return dataTable;
}
/// <summary>
/// Gets the StockDetails.
/// </summary>
/// <param name="reader">The reader.</param>
private StockDetails GetStockDetails(XmlReader reader)
{
if (reader == null)
throw new Exception("reader");
while (reader.NodeType != XmlNodeType.Element)
reader.Read();
if (reader.LocalName != "StockDetails")
throw new XmlException("Unexpected xml tag " + reader.LocalName);
reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace)
reader.Read();
StockDetails stockDetails = new StockDetails();
while (reader.LocalName != "StockDetails")
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.LocalName)
{
case "TradeNo":
stockDetails.TradeNo = reader.ReadElementContentAsString();
break;
case "CompanyName":
stockDetails.CompanyName = reader.ReadElementContentAsString();
break;
case "CostPrice":
stockDetails.CostPrice = reader.ReadElementContentAsString();
break;
case "SharesCount":
stockDetails.SharesCount = reader.ReadElementContentAsString();
break;
case "SalesPrice":
stockDetails.SalesPrice = reader.ReadElementContentAsString();
break;
default:
reader.Skip();
break;
}
}
else
{
reader.Read();
if ((reader.LocalName == "StockDetails") && reader.NodeType == XmlNodeType.EndElement)
break;
}
}
return stockDetails;
}
}
public class StockDetails
{
#region Fields
private string m_tradeNo;
private string m_companyName;
private string m_costPrice;
private string m_sharesCount;
private string m_salesPrice;
#endregion
#region Properties
public string TradeNo
{
get { return m_tradeNo; }
set { m_tradeNo = value; }
}
public string CompanyName
{
get { return m_companyName; }
set { m_companyName = value; }
}
public string CostPrice
{
get { return m_costPrice; }
set { m_costPrice = value; }
}
public string SharesCount
{
get { return m_sharesCount; }
set { m_sharesCount = value; }
}
public string SalesPrice
{
get { return m_salesPrice; }
set { m_salesPrice = value; }
}
#endregion
#region Constructor
public StockDetails(string tradeNo, string companyName, string costPrice, string sharesCount, string salesPrice)
{
m_tradeNo = tradeNo;
m_companyName = companyName;
m_costPrice = costPrice;
m_sharesCount = sharesCount;
m_salesPrice = salesPrice;
}
public StockDetails()
{ }
#endregion
}
}

Просмотреть файл

@ -1,88 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Reflection;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
public ActionResult Watermark(string Group1, string Group2)
{
if (Group2 == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = basePath + @"/DocIO/Watermark.doc";
//Open an existing word document
FileStream fileStream = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
WordDocument doc = new WordDocument(fileStream, FormatType.Doc);
fileStream.Dispose();
fileStream = null;
if (Group2 != "Picture")
{
//Add text watermark.
TextWatermark textWatermark = new TextWatermark("Demo", "Arial", 160, 160);
doc.Watermark = textWatermark;
//Set the color for the watermark text.
textWatermark.Color = Syncfusion.Drawing.Color.Gray;
//Set the size.
textWatermark.Size = 120;
}
else
{
//Add Picture watermark to the word document.
PictureWatermark picWatermark = new PictureWatermark();
doc.Watermark = picWatermark;
FileStream imageStream = new FileStream(basePath + @"/images/DocIO/Northwind_logo.png", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(imageStream);
byte[] image = br.ReadBytes((int)imageStream.Length);
//Set the picture.
picWatermark.LoadPicture(image);
//Set the properties for the watermark.
picWatermark.Scaling = 100.0f;
picWatermark.Washout = false;
}
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
doc.Save(ms, type);
doc.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
}
}

Просмотреть файл

@ -1,74 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System.IO;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region WordML to Word
public ActionResult WordMLToWord(string Group1)
{
if (Group1 == null)
return View();
if (Request.Form.Files != null)
{
var extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();
if (extension == ".xml")
{
MemoryStream stream = new MemoryStream();
Request.Form.Files[0].CopyTo(stream);
WordDocument document = new WordDocument(stream, FormatType.WordML);
stream.Dispose();
stream = null;
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
#region Document SaveOption
//Save as .doc format
if (Group1 == "WordDoc")
{
type = FormatType.Doc;
filename = "Sample.doc";
contenttype = "application/msword";
}
//Save as .xml format
else if (Group1 == "WordML")
{
type = FormatType.WordML;
filename = "Sample.xml";
contenttype = "application/msword";
}
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
else
{
ViewBag.Message = string.Format("Please choose WordML document to convert to Word Document");
}
}
else
{
ViewBag.Message = string.Format("Browse a WordML document and then click the button to convert as a Word document");
}
return View();
}
#endregion WordML to Word
}
}

Просмотреть файл

@ -1,80 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
using Syncfusion.DocIORenderer;
using Syncfusion.Pdf;
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
public IActionResult WordToPDF(string button, string renderingMode1, string renderingMode2, string renderingMode3, string renderingMode4)
{
if (button == null)
return View();
if (Request.Form.Files != null)
{
// Gets the extension from file.
string extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();
// Compares extension with supported extensions.
if (extension == ".doc" || extension == ".docx" || extension == ".dot" || extension == ".dotx" || extension == ".dotm" || extension == ".docm"
|| extension == ".xml" || extension == ".rtf")
{
MemoryStream stream = new MemoryStream();
Request.Form.Files[0].CopyTo(stream);
try
{
// Loads document from stream.
WordDocument document = new WordDocument(stream, FormatType.Automatic);
stream.Dispose();
stream = null;
// Creates a new instance of DocIORenderer class.
DocIORenderer render = new DocIORenderer();
if (renderingMode1 == "PreserveStructureTags")
render.Settings.AutoTag = true;
if (renderingMode2 == "PreserveFormFields")
render.Settings.PreserveFormFields = true;
render.Settings.ExportBookmarks = renderingMode3 == "PreserveWordHeadingsToPDFBookmarks"
? Syncfusion.DocIO.ExportBookmarkType.Headings
: Syncfusion.DocIO.ExportBookmarkType.Bookmarks;
if(renderingMode4 == "ShowRevisions")
document.RevisionOptions.ShowMarkup = RevisionType.Deletions | RevisionType.Formatting | RevisionType.Insertions;
// Converts Word document into PDF document.
PdfDocument pdf = render.ConvertToPDF(document);
MemoryStream memoryStream = new MemoryStream();
// Save the PDF document.
pdf.Save(memoryStream);
render.Dispose();
pdf.Close();
document.Close();
memoryStream.Position = 0;
return File(memoryStream, "application/pdf", "WordToPDF.pdf");
}
catch (Exception ex)
{
ViewBag.Message = string.Format("The input document could not be processed completely, Could you please email the document to support@syncfusion.com for troubleshooting.");
}
}
else
{
ViewBag.Message = string.Format("Please choose Word format document to convert to PDF");
}
}
else
{
ViewBag.Message = string.Format("Browse a Word document and then click the button to convert as a PDF document");
}
return View();
}
}
}

Просмотреть файл

@ -1,77 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.IO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
#region Word to WordML
public ActionResult WordToWordML(string button)
{
if (button == null)
return View();
if (Request.Form.Files != null)
{
var extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();
if (extension == ".doc" || extension == ".docx" || extension == ".dot" || extension == ".dotx" || extension == ".dotm" || extension == ".docm"
|| extension == ".xml" || extension == ".rtf")
{
MemoryStream stream = new MemoryStream();
Request.Form.Files[0].CopyTo(stream);
WordDocument document = new WordDocument(stream, FormatType.Automatic);
stream.Dispose();
stream = null;
//Convert word document into WordML document
try
{
#region Document SaveOption
//Save as .xml format
FormatType type = FormatType.WordML;
string filename = "WordToWordML.xml";
string contenttype = "application/msword";
#endregion Document SaveOption
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
catch (Exception)
{
}
finally
{
}
}
else
{
ViewBag.Message = string.Format("Please choose Word format document to convert to WordML");
}
}
else
{
ViewBag.Message = string.Format("Browse a Word document and then click the button to convert as a WordML document");
}
return View();
}
#endregion Word to WordML
}
}

Просмотреть файл

@ -1,235 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.Drawing;
using System;
using System.IO;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers.DocIO
{
public partial class DocIOController : Controller
{
// GET: /<controller>/
public IActionResult XMLMapping(string Group)
{
if (Group == null)
return View();
string basePath = _hostingEnvironment.WebRootPath;
// Load Template document stream.
FileStream inputStream = new FileStream(basePath + @"/DocIO/Employees.xml", FileMode.Open, FileAccess.Read);
// Create a new document.
WordDocument document = new WordDocument();
//Add a section & a paragraph in the empty document.
document.EnsureMinimal();
//Loads XML file into the customXML part of the Word document.
CustomXMLPart docIOxmlPart = new CustomXMLPart(document);
docIOxmlPart.Load(inputStream);
//Insert content controls and maps Employees details to it.
InsertAndMapEmployees(document, "EmployeesList", docIOxmlPart);
FormatType type = FormatType.Docx;
string filename = "Sample.docx";
string contenttype = "application/vnd.ms-word.document.12";
MemoryStream ms = new MemoryStream();
document.Save(ms, type);
document.Close();
ms.Position = 0;
return File(ms, contenttype, filename);
}
#region Helper Method
/// <summary>
/// Insert and Maps CustomXMLPart to content control based on XPath.
/// </summary>
/// <param name="paragraph">Paragraph instance to append content control.</param>
/// <param name="XPath">XPath of the CustomXMLNode to be mapped</param>
/// <param name="custXMLPart">CustomXMLPart of the CustomXMLNode</param>
private void MapCustomXMLPart(IWParagraph paragraph, string XPath, CustomXMLPart custXMLPart)
{
IInlineContentControl contentControl = paragraph.AppendInlineContentControl(ContentControlType.Text);
contentControl.ContentControlProperties.XmlMapping.SetMapping(XPath, string.Empty, custXMLPart);
}
/// <summary>
/// Inserts content control and maps the employees details to it.
/// </summary>
/// <param name="document">Word document instance.</param>
/// <param name="xmlRootPath">Custom XML root Xpath.</param>
/// <param name="docIOxmlPart">CustomXMLPart instance.</param>
private void InsertAndMapEmployees(WordDocument document, string xmlRootPath, CustomXMLPart docIOxmlPart)
{
//Retrieving CustomXMLNode from xmlRootPath.
CustomXMLNode parentNode = docIOxmlPart.SelectSingleNode(xmlRootPath);
int empIndex = 1;
foreach (CustomXMLNode employeeNode in parentNode.ChildNodes)
{
if (employeeNode.HasChildNodes())
{
//Adds new paragraph to the section
IWParagraph paragraph = document.LastSection.AddParagraph();
paragraph.ParagraphFormat.BackColor = Color.Gray;
IWTextRange textrange = paragraph.AppendText("Employee");
textrange.CharacterFormat.TextColor = Color.White;
textrange.CharacterFormat.Bold = true;
textrange.CharacterFormat.FontSize = 14;
//Insert content controls and maps Employee details to it.
InsertAndMapEmployee(document, employeeNode, xmlRootPath, docIOxmlPart, empIndex);
}
empIndex++;
}
}
/// <summary>
/// Inserts content control and maps the employee details to it.
/// </summary>
/// <param name="document">Word document instance.</param>
/// <param name="employeesNode">CustomXMLNode of employee.</param>
/// <param name="rootXmlPath">Custom XML root Xpath.</param>
/// <param name="docIOxmlPart">CustomXMLPart instance.</param>
/// <param name="empIndex">Current employee index.</param>
private void InsertAndMapEmployee(WordDocument document, CustomXMLNode employeesNode, string rootXmlPath, CustomXMLPart docIOxmlPart, int empIndex)
{
//Column names of Employee element.
string[] employeesDetails = { "FirstName", "LastName", "EmployeeID", "Extension", "Address", "City", "Country" };
int empChildIndex = 0;
int customerIndex = 1;
// Append current empolyee XPath with root XPath.
string empPath = "/" + rootXmlPath + "/Employees[" + empIndex + "]/";
// Iterating child elements of Employee
foreach (CustomXMLNode employeeChild in employeesNode.ChildNodes)
{
IWParagraph paragraph = document.LastParagraph;
if (employeeChild.HasChildNodes())
{
//Insert a content controls and maps Customer details to it.
InsertAndMapCustomer(document, employeeChild, docIOxmlPart, empPath, customerIndex);
customerIndex++;
}
else
{
if (empChildIndex != 1)
{
//Insert a content controls and maps Employee details other than Customer details to it.
paragraph = document.LastSection.AddParagraph();
if (empChildIndex == 0)
paragraph.AppendText("Name:");
else
paragraph.AppendText(employeesDetails[empChildIndex] + ":");
}
MapCustomXMLPart(paragraph, empPath + employeesDetails[empChildIndex], docIOxmlPart);
}
empChildIndex++;
}
}
/// <summary>
/// Insert a content controls and maps Customer details to it.
/// </summary>
/// <param name="document">Word document instance.</param>
/// <param name="customerNode">CustomXMLNode of customer.</param>
/// <param name="docIOxmlPart">CustomXMLPart instance.</param>
/// <param name="empPath">Current employee index.</param>
/// <param name="custIndex">Current customer index.</param>
private void InsertAndMapCustomer(WordDocument document, CustomXMLNode customerNode, CustomXMLPart docIOxmlPart, string empPath, int custIndex)
{
//Column names of Customer element.
string[] customersDetails = { "CustomerID", "EmployeeID", "CompanyName", "ContactName", "City", "Country" };
document.LastSection.AddParagraph();
//Adds new paragraph to the section
IWParagraph paragraph = document.LastSection.AddParagraph();
paragraph.ParagraphFormat.BackColor = Color.Green;
paragraph.ParagraphFormat.LeftIndent = 72;
IWTextRange textrange = paragraph.AppendText("Customers");
textrange.CharacterFormat.TextColor = Color.White;
textrange.CharacterFormat.Bold = true;
textrange.CharacterFormat.FontSize = 14;
int orderIndex = 1;
int custChild = 0;
bool isFirstOrder = true;
string customerXpath = empPath + "Customers[" + custIndex + "]/";
foreach (CustomXMLNode customerChild in customerNode.ChildNodes)
{
if (customerChild.HasChildNodes())
{
//Insert a content controls and maps Orders details to it.
InsertAndMapOrders(document, customerChild, docIOxmlPart, customerXpath, orderIndex, isFirstOrder);
document.LastSection.AddParagraph();
isFirstOrder = false;
orderIndex++;
}
else
{
//Insert a content controls and maps Customer details other than Order details to it.
paragraph = document.LastSection.AddParagraph();
paragraph.ParagraphFormat.LeftIndent = 72;
paragraph.AppendText(customersDetails[custChild] + ":");
MapCustomXMLPart(paragraph, customerXpath + customersDetails[custChild], docIOxmlPart);
}
custChild++;
}
}
/// <summary>
/// Insert a content controls and maps Orders details to it.
/// </summary>
/// <param name="document">Word document instance.</param>
/// <param name="orderNode">CustomXMLNode of order.</param>
/// <param name="docIOxmlPart">CustomXMLPart instance.</param>
/// <param name="custPath">Current customer index</param>
/// <param name="orderIndex">Current order index</param>
/// <param name="isFirst">Indicates whether it is the first order of the customer.</param>
private void InsertAndMapOrders(WordDocument document, CustomXMLNode orderNode, CustomXMLPart docIOxmlPart, string custPath, int orderIndex, bool isFirst)
{
//Column names of order element.
string[] ordersDetails = { "OrderID", "CustomerID", "OrderDate", "ShippedDate", "RequiredDate" };
IWParagraph paragraph = null;
IWTextRange textrange = null;
if (isFirst)
{
document.LastSection.AddParagraph();
//Adds new paragraph to the section
paragraph = document.LastSection.AddParagraph();
paragraph.ParagraphFormat.BackColor = Color.Red;
paragraph.ParagraphFormat.LeftIndent = 128;
textrange = paragraph.AppendText("Orders");
textrange.CharacterFormat.TextColor = Color.White;
textrange.CharacterFormat.Bold = true;
textrange.CharacterFormat.FontSize = 14;
}
int orderChildIndex = 0;
string customerXpath = custPath + "Orders[" + orderIndex + "]/";
foreach (CustomXMLNode orderChild in orderNode.ChildNodes)
{
//Adds new paragraph to the section
paragraph = document.LastSection.AddParagraph();
paragraph.ParagraphFormat.LeftIndent = 128;
paragraph.AppendText(ordersDetails[orderChildIndex] + ":");
MapCustomXMLPart(paragraph, customerXpath + "/" + ordersDetails[orderChildIndex], docIOxmlPart);
orderChildIndex++;
}
}
#endregion
}
}

Просмотреть файл

@ -1,24 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace MVCsamplebrowser.Controllers
{
public class IntroductionController : Controller
{
public ActionResult Index()
{
return View();
}
}
}

Просмотреть файл

@ -1,161 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
using System.Data;
using System.IO;
using System.Xml.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Syncfusion.Drawing;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
#region Private Members
#endregion
//
// GET: /AdventureCycle/
public ActionResult AdventureCycle()
{
List<string> styleList = new List<string>();
foreach (var style in Enum.GetValues(typeof(PdfGridBuiltinStyle)))
{
styleList.Add(style.ToString());
}
ViewData.Add("styleName", new SelectList(styleList));
return View();
}
[HttpPost]
public ActionResult AdventureCycle(string styleName, string Header, string Bandedrow, string Bandedcolumn, string Firstcolumn, string Lastcolumn, string Lastrow, string InsideBrowser)
{
if (styleName == "" || styleName == null)
styleName = "GridTable4";
//Create PDF document
PdfDocument doc = new PdfDocument();
//Set font
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
//Create Pdf ben for drawing broder
PdfPen borderPen = new PdfPen(PdfBrushes.DarkBlue);
borderPen.Width = 0;
//Create DataTable for source
PdfPage page = doc.Pages.Add();
//Use DataTable as source
PdfGrid grid = new PdfGrid();
//Create dataset with the "Customers" table from Norwind database
IEnumerable<Orders> orders = Provider.GetOrdersData(_hostingEnvironment.WebRootPath);
grid.Style.AllowHorizontalOverflow = true;
//Set Data source
grid.DataSource = orders;
#region PdfGridBuiltinStyleSettings
PdfGridBuiltinStyleSettings setting = new PdfGridBuiltinStyleSettings();
setting.ApplyStyleForHeaderRow = Header != null ? true : false;
setting.ApplyStyleForBandedRows = Bandedrow != null ? true : false;
setting.ApplyStyleForBandedColumns = Bandedcolumn != null ? true : false;
setting.ApplyStyleForFirstColumn = Firstcolumn != null ? true : false;
setting.ApplyStyleForLastColumn = Lastcolumn != null ? true : false;
setting.ApplyStyleForLastRow = Lastrow != null ? true : false;
#endregion
//Set layout properties
PdfLayoutFormat format = new PdfLayoutFormat();
format.Break = PdfLayoutBreakType.FitElement;
format.Layout = PdfLayoutType.Paginate;
PdfGridBuiltinStyle style = ConvertToPdfGridBuiltStyle(styleName);
grid.ApplyBuiltinStyle(style, setting);
grid.Style.Font = font;
grid.Style.CellPadding.All = 2;
grid.Style.AllowHorizontalOverflow = false;
//Draw table
grid.Draw(page, PointF.Empty, format);
MemoryStream stream = new MemoryStream();
//Save the PDF document
doc.Save(stream);
//Close the PDF document
doc.Close(true);
stream.Position = 0;
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = "AdventureCycle.pdf";
return fileStreamResult;
}
# region Helpher Methods
private PdfGridBuiltinStyle ConvertToPdfGridBuiltStyle(string styleName)
{
PdfGridBuiltinStyle value = (PdfGridBuiltinStyle)Enum.Parse(typeof(PdfGridBuiltinStyle), styleName);
return value;
}
internal sealed class Provider
{
public static IEnumerable<Orders> GetOrdersData(string webRootPath)
{
string dataPath = webRootPath + @"/PDF/";
//Read the file
FileStream xmlStream = new FileStream(dataPath + "Orders.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader reader = new StreamReader(xmlStream, true))
{
string data = reader.ReadToEnd();
data = data.Replace(" xmlns=\"http://www.tempuri.org/DataSet1.xsd\"", "");
return XElement.Parse(data)
.Elements("Orders")
.Select(c => new Orders
{
OrderID = c.Element("OrderID") != null ? c.Element("OrderID").Value : "",
CustomerID = c.Element("CustomerID") != null ? c.Element("CustomerID").Value : "",
ShipName = c.Element("ShipName") != null ? c.Element("ShipName").Value : "",
ShipAddress = c.Element("ShipAddress") != null ? c.Element("ShipAddress").Value : "",
ShipCity = c.Element("ShipCity") != null ? c.Element("ShipCity").Value : "",
ShipPostalCode = c.Element("ShipPostalCode") != null ? c.Element("ShipPostalCode").Value : "",
ShipCountry = c.Element("ShipCountry") != null ? c.Element("ShipCountry").Value : "",
});
}
}
}
#endregion
}
public class Orders
{
public string OrderID { get; set; }
public string CustomerID { get; set; }
public string ShipName { get; set; }
public string ShipAddress { get; set; }
public string ShipCity { get; set; }
public string ShipPostalCode { get; set; }
public string ShipCountry { get; set; }
}
}

Просмотреть файл

@ -1,299 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using Syncfusion.Pdf.Parsing;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /AnnotationFlatten/
public ActionResult AnnotationFlatten()
{
return View();
}
[HttpPost]
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;
}
}
}

Просмотреть файл

@ -1,155 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /Attachments/
public ActionResult Attachments()
{
return View();
}
[HttpPost]
public ActionResult Attachments(string Browser)
{
//Creates a new PDF document.
PdfDocument doc = new PdfDocument();
//Add a page
PdfPage page = doc.Pages.Add();
//Set the font
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 18f, PdfFontStyle.Bold);
//Create new PDF color
PdfColor orangeColor = new PdfColor(255, 255, 167, 73);
//Draw the text
page.Graphics.DrawString("Attachments", font, PdfBrushes.Black, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), new PdfStringFormat(PdfTextAlignment.Center));
//Create font
font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular);
page.Graphics.DrawString("This PDF document contains image and text file as attachment.", font, PdfBrushes.Black, new PointF(0, 30));
font = new PdfStandardFont(PdfFontFamily.Helvetica, 8f, PdfFontStyle.Regular);
page.Graphics.DrawString("Click to open the attachment:", font, PdfBrushes.Black, new PointF(0, 50));
page.Graphics.DrawString("Click to open the attachment:", font, PdfBrushes.Black, new PointF(0, 70));
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//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.ModificationDate = DateTime.Now;
attachment.Description = "About Syncfusion";
attachment.MimeType = "application/txt";
//Adds the attachment to the document
doc.Attachments.Add(attachment);
file = new FileStream(dataPath + "Autumn Leaves.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Creates an attachment
attachment = new PdfAttachment("Autumn Leaves.jpg",file);
attachment.ModificationDate = DateTime.Now;
attachment.Description = "Autumn Leaves Image";
attachment.MimeType = "application/jpg";
doc.Attachments.Add(attachment);
file = new FileStream(dataPath + "Text2.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Creates an attachment
attachment = new PdfAttachment("Text2.txt",file);
attachment.ModificationDate = DateTime.Now;
attachment.Description = "List of Syncfusion Control";
attachment.MimeType = "application/txt";
doc.Attachments.Add(attachment);
//Set document viewerpreference.
doc.ViewerPreferences.HideWindowUI = false;
doc.ViewerPreferences.HideMenubar = false;
doc.ViewerPreferences.HideToolbar = false;
doc.ViewerPreferences.FitWindow = false;
doc.ViewerPreferences.DisplayTitle = false;
doc.ViewerPreferences.PageMode = PdfPageMode.UseAttachments;
//Disable the default appearance.
doc.Form.SetDefaultAppearance(false);
//Create pdfbuttonfield.
PdfButtonField openSpecificationButton = new PdfButtonField(page, "openSpecification");
openSpecificationButton.Bounds = new RectangleF(105, 50, 62, 10);
openSpecificationButton.TextAlignment = PdfTextAlignment.Left;
openSpecificationButton.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
openSpecificationButton.BorderStyle = PdfBorderStyle.Underline;
openSpecificationButton.BorderColor = orangeColor;
openSpecificationButton.BackColor = new PdfColor(255, 255, 255);
openSpecificationButton.ForeColor = orangeColor;
openSpecificationButton.Text = "Autumn Leaves.jpg";
openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Autumn Leaves.jpg', nLaunch: 2 });");
doc.Form.Fields.Add(openSpecificationButton);
openSpecificationButton = new PdfButtonField(page, "openSpecification");
openSpecificationButton.Bounds = new RectangleF(105, 70, 30, 10);
openSpecificationButton.TextAlignment = PdfTextAlignment.Left;
openSpecificationButton.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
openSpecificationButton.BorderStyle = PdfBorderStyle.Underline;
openSpecificationButton.BorderColor = orangeColor;
openSpecificationButton.BackColor = new PdfColor(255, 255, 255);
openSpecificationButton.ForeColor = orangeColor;
openSpecificationButton.Text = "Text1.txt";
openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Text1.txt', nLaunch: 2 });");
doc.Form.Fields.Add(openSpecificationButton);
//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 = "Attachments.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,147 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//Declaring necessary objects.
public ActionResult Autotag()
{
return View();
}
[HttpPost]
public ActionResult Autotag(string Browser)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
#region content string
string toc = "\r\n What can I do with C#? ..................................................................................................................................... 3 \r\n \r\n What is .NET? .................................................................................................................................................... 3 \r\n \r\n Writing, Running, and Deploying a C# Program .............................................................................................. 3 \r\n \r\n Starting a New Program..................................................................................................................................... 3";
string Csharp = "Welcome to C# Succinctly. True to the Succinctly series concept, this book is very focused on a single topic: the C# programming language. I might briefly mention some technologies that you can write with C# or explain how a feature fits into those technologies, but the whole of this book is about helping you become familiar with C# syntax. \r\n \r\n In this chapter, Ill start with some introductory information and then jump straight into a simple C# program.";
string whatToD0 = "C# is a general purpose, object-oriented, component-based programming language. As a general purpose language, you have a number of ways to apply C# to accomplish many different tasks. You can build web applications with ASP.NET, desktop applications with Windows Presentation Foundation (WPF), or build mobile applications for Windows Phone. Other applications include code that runs in the cloud via Windows Azure, and iOS, Android, and Windows Phone support with the Xamarin platform. There might be times when you need a different language, like C or C++, to communicate with hardware or real-time systems. However, from a general programming perspective, you can do a lot with C#.";
string dotnet = "The runtime is more formally named the Common Language Runtime (CLR). Programming languages that target the CLR compile to an Intermediate Language (IL). The CLR itself is a virtual machine that runs IL and provides many services such as memory management, garbage collection, exception management, security, and more.\r\n \r\n The Framework Class Library (FCL) is a set of reusable code that provides both general services and technology-specific platforms. The general services include essential types such as collections, cryptography, networking, and more. In addition to general classes, the FCL includes technology-specific platforms like ASP.NET, WPF, web services, and more. The value the FCL offers is to have common components available for reuse, saving time and money without needing to write that code yourself. \r\n \r\n There is a huge ecosystem of open-source and commercial software that relies on and supports .NET. If you visit CodePlex, GitHub, or any other open-source code repository site, you will see a multitude of projects written in C#. Commercial offerings include tools and services that help you build code, manage systems, and offer applications. Syncfusion is part of this ecosystem, offering reusable components for many of the .NET technologies I have mentioned.";
string prog = "The previous section described plenty of great things you can do with C#, but most of them are so detailed that they require their own book. To stay focused on the C# programming language, the code in this book will be for the console application. A console application runs on the command line, which you will learn about in this section. You can write your code with any editor, but this book uses Visual Studio.";
#endregion
//Create a new PDF document.
PdfDocument document = new PdfDocument();
//Auto Tag the document
document.AutoTag = true;
document.DocumentInformation.Title = "AutoTag";
#region page1
//Add a page to the document.
PdfPage page1 = document.Pages.Add();
//Load the image from the disk.
FileStream fileStream1 = new FileStream(dataPath+"AutoTag.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfBitmap image = new PdfBitmap(fileStream1);
//Draw the image
page1.Graphics.DrawImage(image, 0, 0, page1.GetClientSize().Width, page1.GetClientSize().Height - 20);
#endregion
#region page2
PdfPage page2 = document.Pages.Add();
PdfFont fontnormal = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);
PdfFont fontTitle = new PdfStandardFont(PdfFontFamily.TimesRoman, 22, PdfFontStyle.Bold);
PdfFont fontHead = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Bold);
PdfFont fontHead2 = new PdfStandardFont(PdfFontFamily.TimesRoman, 16, PdfFontStyle.Bold);
page2.Graphics.DrawString("Table of Contents", fontTitle, PdfBrushes.Black, new PointF(300, 0));
page2.Graphics.DrawLine(new PdfPen(PdfBrushes.Black, 0.5f), new PointF(0, 40), new PointF(page2.GetClientSize().Width, 40));
page2.Graphics.DrawString("Chapter 1 Introducing C# and .NET .............................................................................................................. 3 \r\n ", fontHead, PdfBrushes.Black, new PointF(0, 60));
page2.Graphics.DrawString(toc, fontnormal, PdfBrushes.Black, new PointF(0, 80));
#endregion
#region page3
PdfPage page3 = document.Pages.Add();
page3.Graphics.DrawString("C# Succinctly", new PdfStandardFont(PdfFontFamily.TimesRoman, 32, PdfFontStyle.Bold), PdfBrushes.Black, new PointF(160, 0));
page3.Graphics.DrawLine(PdfPens.Black, new PointF(0, 40), new PointF(page3.GetClientSize().Width, 40));
page3.Graphics.DrawString("Chapter 1 Introducing C# and .NET", fontTitle, PdfBrushes.Black, new PointF(160, 60));
PdfTextElement element1 = new PdfTextElement(Csharp, fontnormal);
element1.Brush = new PdfSolidBrush(Color.Black);
element1.Draw(page3, new RectangleF(0, 100, page3.GetClientSize().Width, 80));
page3.Graphics.DrawString("What can I do with C#?", fontHead2, PdfBrushes.Black, new PointF(0, 180));
PdfTextElement element2 = new PdfTextElement(whatToD0, fontnormal);
element2.Brush = new PdfSolidBrush(Color.Black);
element2.Draw(page3, new RectangleF(0, 210, page3.GetClientSize().Width, 80));
page3.Graphics.DrawString("What is .Net", fontHead2, PdfBrushes.Black, new PointF(0, 300));
PdfTextElement element3 = new PdfTextElement(dotnet, fontnormal);
element3.Brush = new PdfSolidBrush(Color.Black);
element3.Draw(page3, new RectangleF(0, 330, page3.GetClientSize().Width, 180));
page3.Graphics.DrawString("Writing, Running, and Deploying a C# Program", fontHead2, PdfBrushes.Black, new PointF(0, 520));
PdfTextElement element4 = new PdfTextElement(prog, fontnormal);
element4.Brush = new PdfSolidBrush(Color.Black);
element4.Draw(page3, new RectangleF(0, 550, page3.GetClientSize().Width, 60));
FileStream fileStream2 = new FileStream(dataPath + "autotagSmall.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfBitmap img = new PdfBitmap(fileStream2);
page3.Graphics.DrawImage(img, new PointF(0, 630));
page3.Graphics.DrawString("Note: The code samples in this book can be downloaded at", fontnormal, PdfBrushes.DarkBlue, new PointF(20, 630));
page3.Graphics.DrawString("https://bitbucket.org/syncfusiontech/c-succinctly", fontnormal, PdfBrushes.Blue, new PointF(20, 640));
SizeF linkSize = fontnormal.MeasureString("https://bitbucket.org/syncfusiontech/c-succinctly");
RectangleF rectangle = new RectangleF(20, 640, linkSize.Width, linkSize.Height);
//Creates a new Uri Annotation
PdfUriAnnotation uriAnnotation = new PdfUriAnnotation(rectangle, "https://bitbucket.org/syncfusiontech/c-succinctly");
uriAnnotation.Color = new PdfColor(255, 255, 255);
//Adds this annotation to a new page
page3.Annotations.Add(uriAnnotation);
#endregion
//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 = "Autotag.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,367 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Barcode;
using Syncfusion.Pdf.Graphics;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /Barcode/
public ActionResult Barcode()
{
return View();
}
[HttpPost]
public ActionResult Barcode(string InsideBrowser)
{
//Create a new instance of PdfDocument class.
PdfDocument document = new PdfDocument();
//Add a new page to the document.
PdfPage page = document.Pages.Add();
//Create Pdf graphics for the page
PdfGraphics g = page.Graphics;
//Create a solid brush
PdfBrush brush = PdfBrushes.Black;
# region 2D Barcode
//Set the font
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 15f, PdfFontStyle.Bold);
PdfPen pen = new PdfPen(brush, 0.5f);
float width = page.GetClientSize().Width;
float xPos = page.GetClientSize().Width / 2;
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
// Draw String
g.DrawString("2D Barcodes", font, brush, new PointF(xPos, 10), format);
#region QR Barcode
font = new PdfStandardFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
g.DrawString("QR Barcode", font, brush, new PointF(10, 90));
PdfQRBarcode qrBarcode = new PdfQRBarcode();
// Sets the Input mode to Binary mode
qrBarcode.InputMode = InputMode.BinaryMode;
// Automatically select the Version
qrBarcode.Version = QRCodeVersion.Auto;
// Set the Error correction level to high
qrBarcode.ErrorCorrectionLevel = PdfErrorCorrectionLevel.High;
// Set dimension for each block
qrBarcode.XDimension = 4;
qrBarcode.Text = "Syncfusion Essential Studio Enterprise edition $995";
// Draw the QR barcode
qrBarcode.Draw(page, new PointF(25, 120));
font = new PdfStandardFont(PdfFontFamily.TimesRoman, 9, PdfFontStyle.Regular);
g.DrawString("Input Type : Eight Bit Binary", font, brush, new PointF(250, 160));
g.DrawString("Encoded Data : Syncfusion Essential Studio Enterprise edition $995", font, brush, new PointF(250, 180));
g.DrawLine(pen, new PointF(0, 320), new PointF(width, 320));
#endregion
#region Datamatrix
font = new PdfStandardFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
g.DrawString("DataMatrix Barcode", font, brush, new PointF(10, 340));
PdfDataMatrixBarcode dataMatrixBarcode = new PdfDataMatrixBarcode("5575235 Win7 4GB 64bit 7Jun2010");
// Set dimension for each block
dataMatrixBarcode.XDimension = 4;
// Draw the barcode
dataMatrixBarcode.Draw(page, new PointF(25, 540));
font = new PdfStandardFont(PdfFontFamily.TimesRoman, 9, PdfFontStyle.Regular);
g.DrawString("Symbol Type : Square", font, brush, new PointF(250, 590));
g.DrawString("Encoded Data : 5575235 Win7 4GB 64bit 7Jun2010", font, brush, new PointF(250, 610));
pen = new PdfPen(brush, 0.5f);
g.DrawLine(pen, new PointF(0, 700), new PointF(width, 700));
string text = "TYPE 3523 - ETWS/N FE- SDFHW 06/08";
dataMatrixBarcode = new PdfDataMatrixBarcode(text);
// rectangular matrix
dataMatrixBarcode.Size = PdfDataMatrixSize.Size16x48;
dataMatrixBarcode.XDimension = 4;
dataMatrixBarcode.Draw(page, new PointF(25, 400));
g.DrawString("Symbol Type : Rectangle", font, brush, new PointF(250, 420));
g.DrawString("Encoded Data : " + text, font, brush, new PointF(250, 440));
pen = new PdfPen(brush, 0.5f);
#endregion
# endregion
# region 1D Barcode
page = document.Pages.Add();
g = page.Graphics;
//Set the font
font = new PdfStandardFont(PdfFontFamily.Helvetica, 15f, PdfFontStyle.Bold);
// Draw String
g.DrawString("1D/Linear Barcodes", font, brush, new PointF(150, 10));
// Set string format.
format = new PdfStringFormat();
format.WordWrap = PdfWordWrapType.Word;
#region Code39
// Drawing Code39 barcode
PdfCode39Barcode barcode = new PdfCode39Barcode();
// Setting height of the barcode
barcode.BarHeight = 45;
barcode.Text = "CODE39$";
//Printing barcode on to the Pdf.
barcode.Draw(page, new PointF(25, 70));
font = new PdfStandardFont(PdfFontFamily.TimesRoman, 9, PdfFontStyle.Regular);
g.DrawString("Type : Code39", font, brush, new PointF(215, 80));
g.DrawString("Allowed Characters : 0-9, A-Z,a dash(-),a dot(.),$,/,+,%, SPACE", font, brush, new PointF(215, 100));
g.DrawLine(pen, new PointF(0, 150), new PointF(width, 150));
#endregion
#region Code39Extended
// Drawing Code39Extended barcode
PdfCode39ExtendedBarcode barcodeExt = new PdfCode39ExtendedBarcode();
// Setting height of the barcode
barcodeExt.BarHeight = 45;
barcodeExt.Text = "CODE39Ext";
//Printing barcode on to the Pdf.
barcodeExt.Draw(page, new PointF(25, 200));
font = new PdfStandardFont(PdfFontFamily.TimesRoman, 9, PdfFontStyle.Regular);
g.DrawString("Type : Code39Ext", font, brush, new PointF(215, 210));
g.DrawString("Allowed Characters : 0-9 A-Z a-z ", font, brush, new PointF(215, 230));
g.DrawLine(pen, new PointF(0, 270), new PointF(width, 270));
#endregion
#region Code11Barcode
// Drawing Code11 barcode
PdfCode11Barcode barcode11 = new PdfCode11Barcode();
// Setting height of the barcode
barcode11.BarHeight = 45;
barcode11.Text = "012345678";
barcode11.EncodeStartStopSymbols = true;
//Printing barcode on to the Pdf.
barcode11.Draw(page, new PointF(25, 300));
font = new PdfStandardFont(PdfFontFamily.TimesRoman, 9, PdfFontStyle.Regular);
g.DrawString("Type : Code 11", font, brush, new PointF(215, 310));
g.DrawString("Allowed Characters : 0-9, a dash(-) ", font, brush, new PointF(215, 330));
g.DrawLine(pen, new PointF(0, 370), new PointF(width, 370));
#endregion
#region Codabar
// Drawing CodaBarcode
PdfCodabarBarcode codabar = new PdfCodabarBarcode();
// Setting height of the barcode
codabar.BarHeight = 45;
codabar.Text = "0123";
//Printing barcode on to the Pdf.
codabar.Draw(page, new PointF(25, 400));
font = new PdfStandardFont(PdfFontFamily.TimesRoman, 9, PdfFontStyle.Regular);
g.DrawString("Type : Codabar", font, brush, new PointF(215, 410));
g.DrawString("Allowed Characters : A,B,C,D,0-9,-$,:,/,a dot(.),+ ", font, brush, new PointF(215, 430));
g.DrawLine(pen, new PointF(0, 470), new PointF(width, 470));
#endregion
#region Code32
PdfCode32Barcode code32 = new PdfCode32Barcode();
code32.Font = font;
// Setting height of the barcode
code32.BarHeight = 45;
code32.Text = "01234567";
code32.TextDisplayLocation = TextLocation.Bottom;
code32.EnableCheckDigit = true;
code32.ShowCheckDigit = true;
//Printing barcode on to the Pdf.
code32.Draw(page, new PointF(25, 500));
g.DrawString("Type : Code32", font, brush, new PointF(215, 500));
g.DrawString("Allowed Characters : 1 2 3 4 5 6 7 8 9 0 ", font, brush, new PointF(215, 520));
g.DrawLine(pen, new PointF(0, 580), new PointF(width, 580));
#endregion
#region Code93
PdfCode93Barcode code93 = new PdfCode93Barcode();
// Setting height of the barcode
code93.BarHeight = 45;
code93.Text = "ABC 123456789";
//Printing barcode on to the Pdf.
code93.Draw(page, new PointF(25, 600));
g.DrawString("Type : Code93", font, brush, new PointF(215, 600));
g.DrawString("Allowed Characters : 1 2 3 4 5 6 7 8 9 0 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - . $ / + % SPACE ", font, brush, new RectangleF(215, 620, 300, 200), format);
g.DrawLine(pen, new PointF(0, 680), new PointF(width, 680));
#endregion
#region Code93Extended
PdfCode93ExtendedBarcode code93ext = new PdfCode93ExtendedBarcode();
//Setting height of the barcode
code93ext.BarHeight = 45;
code93ext.EncodeStartStopSymbols = true;
code93ext.Text = "(abc) 123456";
//Printing barcode on to the Pdf.
page = document.Pages.Add();
code93ext.Draw(page, new PointF(25, 50));
g = page.Graphics;
g.DrawString("Type : Code93 Extended", font, brush, new PointF(200, 50));
g.DrawString("Allowed Characters : All 128 ASCII characters ", font, brush, new PointF(200, 70));
g.DrawLine(pen, new PointF(0, 120), new PointF(width, 120));
#endregion
#region Code128
PdfCode128ABarcode barcode128A = new PdfCode128ABarcode();
// Setting height of the barcode
barcode128A.BarHeight = 45;
barcode128A.Text = "ABCD 12345";
barcode128A.EnableCheckDigit = true;
barcode128A.EncodeStartStopSymbols = true;
barcode128A.ShowCheckDigit = true;
//Printing barcode on to the Pdf.
barcode128A.Draw(page, new PointF(25, 135));
g.DrawString("Type : Code128 A", font, brush, new PointF(200, 135));
g.DrawString("Allowed Characters : NUL (0x00) SOH (0x01) STX (0x02) ETX (0x03) EOT (0x04) ENQ (0x05) ACK (0x06) BEL (0x07) BS (0x08) HT (0x09) LF (0x0A) VT (0x0B) FF (0x0C) CR (0x0D) SO (0x0E) SI (0x0F) DLE (0x10) DC1 (0x11) DC2 (0x12) DC3 (0x13) DC4 (0x14) NAK (0x15) SYN (0x16) ETB (0x17) CAN (0x18) EM (0x19) SUB (0x1A) ESC (0x1B) FS (0x1C) GS (0x1D) RS (0x1E) US (0x1F) SPACE (0x20) \" ! # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ / ]^ _ ", font, brush, new RectangleF(200, 155, 300, 200), format);
g.DrawLine(pen, new PointF(0, 250), new PointF(width, 250));
PdfCode128BBarcode barcode128B = new PdfCode128BBarcode();
// Setting height of the barcode
barcode128B.BarHeight = 45;
barcode128B.Text = "12345 abcd";
barcode128B.EnableCheckDigit = true;
barcode128B.EncodeStartStopSymbols = true;
barcode128B.ShowCheckDigit = true;
//Printing barcode on to the Pdf.
barcode128B.Draw(page, new PointF(25, 280));
g.DrawString("Type : Code128 B", font, brush, new PointF(200, 280));
g.DrawString("Allowed Characters : SPACE (0x20) ! \" # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ / ]^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ DEL (\x7F) ", font, brush, new RectangleF(200, 300, 300, 200), format);
g.DrawLine(pen, new PointF(0, 350), new PointF(width, 350));
PdfCode128CBarcode barcode128C = new PdfCode128CBarcode();
// Setting height of the barcode
barcode128C.BarHeight = 45;
barcode128C.Text = "001122334455";
barcode128C.EnableCheckDigit = true;
barcode128C.EncodeStartStopSymbols = true;
barcode128C.ShowCheckDigit = true;
//Printing barcode on to the Pdf.
barcode128C.Draw(page, new PointF(25, 370));
g.DrawString("Type : Code128 C", font, brush, new PointF(200, 370));
g.DrawString("Allowed Characters : 0 1 2 3 4 5 6 7 8 9 ", font, brush, new PointF(200, 390));
g.DrawLine(pen, new PointF(0, 440), new PointF(width, 440));
#endregion
#region UPC-A
// Drawing UPC-A barcode
PdfCodeUpcBarcode upcBarcode = new PdfCodeUpcBarcode();
// Setting height of the barcode
upcBarcode.BarHeight = 45;
upcBarcode.Text = "01234567890";
//Printing barcode on to the Pdf.
upcBarcode.Draw(page, new PointF(25, 460));
font = new PdfStandardFont(PdfFontFamily.TimesRoman, 9, PdfFontStyle.Regular);
g.DrawString("Type : UPC-A", font, brush, new PointF(200, 460));
g.DrawString("Allowed Characters : 0-9", font, brush, new PointF(200, 480));
g.DrawLine(pen, new PointF(0, 530), new PointF(width, 530));
#endregion
#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;
document.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
fileStreamResult.FileDownloadName = "Barcode.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,75 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /Booklet/
public ActionResult Booklet()
{
return View();
}
[HttpPost]
public ActionResult Booklet(string PageHeight, string PageWidth, string CheckBoxDoubleSide, string InsideBrowser)
{
try
{
if (PageWidth == String.Empty || PageHeight == String.Empty)
{
ViewData["Error"] = "Please ensure the width and height for the page to be updated.";
}
else
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Read the file as stream
FileStream file = new FileStream(dataPath + "Essential_Pdf.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Load a PDF document
PdfLoadedDocument ldoc = new PdfLoadedDocument(file);
//Create booklet with two sides
PdfDocument pdf = PdfBookletCreator.CreateBooklet(ldoc, new SizeF(float.Parse(PageWidth), float.Parse(PageHeight)), (CheckBoxDoubleSide == "DoubleSide") ? true : false);
//Save the PDF to the MemoryStream
MemoryStream ms = new MemoryStream();
pdf.Save(ms);
//If the position is not set to '0' then the PDF will be empty.
ms.Position = 0;
//Close the PDF document.
pdf.Close(true);
ldoc.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
fileStreamResult.FileDownloadName = "Booklet.pdf";
return fileStreamResult;
}
}
catch (Exception ex)
{
ViewData["Error"] = ex.ToString();
}
return View();
}
}
}

Просмотреть файл

@ -1,129 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /Bookmarks/
public ActionResult Bookmarks()
{
return View();
}
# region Methods
public PdfBookmark AddBookmark1(PdfDocument document,PdfPage page, string title, PointF point, PdfFont font)
{
PdfGraphics graphics = page.Graphics;
//Add bookmark in PDF document
PdfBookmark bookmarks = document.Bookmarks.Add(title);
PdfBrush brush = new PdfSolidBrush(Color.Red);
//Draw the content in the PDF page
graphics.DrawString(title, font, brush, new PointF(point.X, point.Y));
bookmarks.Destination = new PdfDestination(page);
bookmarks.Destination.Location = point;
return bookmarks;
}
public PdfBookmark AddSection1(PdfBookmark bookmark, PdfPage page, string title, PointF point, bool isSubSection, PdfFont font)
{
PdfGraphics graphics = page.Graphics;
//Add bookmark in PDF document
PdfBookmark bookmarks = bookmark.Add(title);
PdfBrush brush = new PdfSolidBrush(Color.Green);
if (bookmark.Title.StartsWith("Section"))
{
brush = new PdfSolidBrush(Color.Blue);
}
//Draw the content in the PDF page
graphics.DrawString(title, font, brush, new PointF(point.X, point.Y));
bookmarks.Destination = new PdfDestination(page);
bookmarks.Destination.Location = point;
return bookmarks;
}
#endregion
[HttpPost]
public ActionResult Bookmarks(string Browser)
{
//Creates a new PDF document.
PdfDocument document = new PdfDocument();
//Set the Font
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
//Set PdfBrush
PdfBrush brush = new PdfSolidBrush(Color.Black);
for (int i = 1; i <= 3; i++)
{
PdfPage pages = document.Pages.Add();
//Add bookmark in PDF document
PdfBookmark bookmark = AddBookmark1(document,pages, "Chapter " + i, new PointF(10, 10), font);
bookmark.Color = Color.Red;
//Add sections to bookmark
PdfBookmark section1 = AddSection1(bookmark, pages, "Section " + i + ".1", new PointF(30, 30), false, font);
section1.Color = Color.Green;
PdfBookmark section2 = AddSection1(bookmark, pages, "Section " + i + ".2", new PointF(30, 400), false, font);
section2.Color = Color.Green;
//Add subsections to section
PdfBookmark subsection1 = AddSection1(section1, pages, "Paragraph " + i + ".1.1", new PointF(50, 50), true, font);
subsection1.Color = Color.Blue;
PdfBookmark subsection2 = AddSection1(section1, pages, "Paragraph " + i + ".1.2", new PointF(50, 150), true, font);
subsection2.Color = Color.Blue;
PdfBookmark subsection3 = AddSection1(section1, pages, "Paragraph " + i + ".1.3", new PointF(50, 250), true, font);
subsection3.Color = Color.Blue;
PdfBookmark subsection4 = AddSection1(section2, pages, "Paragraph " + i + ".2.1", new PointF(50, 420), true, font);
subsection4.Color = Color.Blue;
PdfBookmark subsection5 = AddSection1(section2, pages, "Paragraph " + i + ".2.2", new PointF(50, 560), true, font);
subsection5.Color = Color.Blue;
PdfBookmark subsection6 = AddSection1(section2, pages, "Paragraph " + i + ".2.3", new PointF(50, 680), true, font);
subsection6.Color = Color.Blue;
}
//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;
document.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
fileStreamResult.FileDownloadName = "Bookmarks.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,136 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Lists;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /BulletsandLists/
public ActionResult BulletsandLists()
{
return View();
}
[HttpPost]
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;
}
}
}

Просмотреть файл

@ -1,104 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
using Syncfusion.Pdf.Interactive;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /Conformance/
public ActionResult Conformance()
{
return View();
}
[HttpPost]
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
PdfPage page = document.Pages.Add();
//create PDF graphicsfor 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_Ab.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,314 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Grid;
using Syncfusion.Pdf.Interactive;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//Declaring necessary objects.
public ActionResult Customtag()
{
return View();
}
[HttpPost]
public ActionResult Customtag(string Browser)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
PdfFont fontnormal = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);
PdfFont fontTitle = new PdfStandardFont(PdfFontFamily.TimesRoman, 22, PdfFontStyle.Bold);
PdfFont fontHead = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Bold);
PdfFont fontHead2 = new PdfStandardFont(PdfFontFamily.TimesRoman, 16, PdfFontStyle.Bold);
#region content string
string pdfChapter = "We<57>ll begin with a conceptual overview of a simple PDF document. This chapter is designed to be a brief orientation before diving in and creating a real document from scratch \r\n \r\n A PDF file can be divided into four parts: a header, body, cross-reference table, and trailer. The header marks the file as a PDF, the body defines the visible document, the cross-reference table lists the location of everything in the file, and the trailer provides instructions for how to start reading the file.";
string header = "The header is simply a PDF version number and an arbitrary sequence of binary data.The binary data prevents na<6E>ve applications from processing the PDF as a text file. This would result in a corrupted file, since a PDF typically consists of both plain text and binary data (e.g., a binary font file can be directly embedded in a PDF).";
string body = "The page tree serves as the root of the document. In the simplest case, it is just a list of the pages in the document. Each page is defined as an independent entity with metadata (e.g., page dimensions) and a reference to its resources and content, which are defined separately. Together, the page tree and page objects create the <20>paper<65> that composes the document.\r\n \r\n Resources are objects that are required to render a page. For example, a single font is typically used across several pages, so storing the font information in an external resource is much more efficient. A content object defines the text and graphics that actually show up on the page. Together, content objects and resources define theappearance of an individual page. \r\n \r\n Finally, the document<6E>s catalog tells applications where to start reading the document. Often, this is just a pointer to the root page tree.";
string resource = "The third object is a resource defining a font configuration. \r\n \r\n The /Font key contains a whole dictionary, opposed to the name/value pairs we<77>ve seen previously (e.g., /Type /Page). The font we configured is called /F0, and the font face we selected is /Times-Roman. The /Subtype is the format of the font file, and /Type1 refers to the PostScript type 1 file format. The specification defines 14 <20>standard<72> fonts that all PDF applications should support.";
string resource2 = "Any of these values can be used for the /BaseFont in a /Font dictionary. Nonstandard fonts can be embedded in a PDF document, but it is not easy to do manually. We will put off custom fonts until we can use iTextSharp<72>s high-level framework.";
string crossRef = "After the header and the body comes the cross-reference table. It records the byte location of each object in the body of the file. This enables random-access of the document, so when rendering a page, only the objects required for that page are read from the file. This makes PDFs much faster than their PostScript predecessors, which had to read in the entire file before processing it.";
string trailer = "Finally, we come to the last component of a PDF document. The trailer tells applications how to start reading the file. At minimum, it contains three things: \r\n 1. A reference to the catalog which links to the root of the document. \r\n 2. The location of the cross-reference table. \r\n 3. The size of the cross-reference table. \r\n \r\n Since a trailer is all you need to begin processing a document, PDFs are typically read back-to-front: first, the end of the file is found, and then you read backwards until you arrive at the beginning of the trailer. After that, you should have all the information you need to load any page in the PDF.";
#endregion
//Create a new PDF document.
PdfDocument document = new PdfDocument();
document.DocumentInformation.Title = "CustomTag";
#region page1
//Add a page to the document.
PdfPage page1 = document.Pages.Add();
//Load the image from the disk.
FileStream fileStream1 = new FileStream(dataPath + "CustomTag.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfBitmap image = new PdfBitmap(fileStream1);
PdfStructureElement imageElement = new PdfStructureElement(PdfTagType.Figure);
imageElement.AlternateText = "PDF Succintly image";
//adding tag to the PDF image
image.PdfTag = imageElement;
//Draw the image
page1.Graphics.DrawImage(image, 0, 0, page1.GetClientSize().Width, page1.GetClientSize().Height - 20);
#endregion
#region page2
PdfPage page2 = document.Pages.Add();
PdfStructureElement hTextElement1 = new PdfStructureElement(PdfTagType.Heading);
PdfStructureElement headingFirstLevel = new PdfStructureElement(PdfTagType.HeadingLevel1);
headingFirstLevel.Parent = hTextElement1;
PdfTextElement headerElement1 = new PdfTextElement("Chapter 1 Conceptual Overview", fontTitle, PdfBrushes.Black);
headerElement1.PdfTag = headingFirstLevel;
headerElement1.Draw(page2, new PointF(100, 0));
//Initialize the structure element with tag type paragraph.
PdfStructureElement textElement1 = new PdfStructureElement(PdfTagType.Paragraph);
textElement1.Parent = headingFirstLevel;
textElement1.ActualText = pdfChapter;
PdfTextElement element1 = new PdfTextElement(pdfChapter, fontnormal);
element1.PdfTag = textElement1;
element1.Brush = new PdfSolidBrush(Color.Black);
element1.Draw(page2, new RectangleF(0, 40, page2.GetClientSize().Width, 70));
PdfStructureElement hTextElement2 = new PdfStructureElement(PdfTagType.HeadingLevel2);
hTextElement2.Parent = hTextElement1;
hTextElement2.ActualText = "Header";
PdfTextElement headerElement2 = new PdfTextElement("Header", fontHead2, PdfBrushes.Black);
headerElement2.PdfTag = hTextElement1;
headerElement2.Draw(page2, new PointF(0, 140));
PdfStructureElement textElement2 = new PdfStructureElement(PdfTagType.Paragraph);
textElement2.Parent = hTextElement2;
textElement2.ActualText = header;
PdfTextElement element2 = new PdfTextElement(header, fontnormal);
element2.PdfTag = textElement2;
element2.Brush = new PdfSolidBrush(Color.Black);
element2.Draw(page2, new RectangleF(0, 170, page2.GetClientSize().Width, 40));
PdfStructureElement hTextElement3 = new PdfStructureElement(PdfTagType.HeadingLevel2);
hTextElement3.Parent = hTextElement1;
hTextElement3.ActualText = "Body";
PdfTextElement headerElement3 = new PdfTextElement("Body", fontHead2, PdfBrushes.Black);
headerElement3.PdfTag = hTextElement1;
headerElement3.Draw(page2, new PointF(0, 210));
PdfStructureElement textElement3 = new PdfStructureElement(PdfTagType.Paragraph);
textElement3.Parent = hTextElement3;
textElement3.ActualText = body;
PdfTextElement element3 = new PdfTextElement(body, fontnormal);
element3.PdfTag = textElement3;
element3.Brush = new PdfSolidBrush(Color.Black);
element3.Draw(page2, new RectangleF(0, 240, page2.GetClientSize().Width, 120));
PdfStructureElement hTextElement6 = new PdfStructureElement(PdfTagType.HeadingLevel2);
hTextElement6.Parent = hTextElement1;
hTextElement6.ActualText = "Cross-Reference Table";
PdfTextElement headerElement5 = new PdfTextElement("Cross-Reference Table", fontHead2, PdfBrushes.Black);
headerElement5.PdfTag = hTextElement6;
headerElement5.Draw(page2, new PointF(0, 380));
PdfStructureElement textElement6 = new PdfStructureElement(PdfTagType.Paragraph);
textElement6.Parent = hTextElement6;
textElement6.ActualText = crossRef;
PdfTextElement element6 = new PdfTextElement(crossRef, fontnormal);
element6.PdfTag = textElement6;
element6.Brush = new PdfSolidBrush(Color.Black);
element6.Draw(page2, new RectangleF(0, 410, page2.GetClientSize().Width, 50));
PdfStructureElement hTextElement7 = new PdfStructureElement(PdfTagType.HeadingLevel2);
hTextElement7.Parent = hTextElement1;
hTextElement7.ActualText = "Trailer";
PdfTextElement headerElement6 = new PdfTextElement("Trailer", fontHead2, PdfBrushes.Black);
headerElement6.PdfTag = hTextElement7;
headerElement6.Draw(page2, new PointF(0, 470));
PdfStructureElement textElement7 = new PdfStructureElement(PdfTagType.Paragraph);
textElement7.Parent = hTextElement7;
textElement7.ActualText = trailer;
PdfTextElement element7 = new PdfTextElement(trailer, fontnormal);
element7.PdfTag = textElement7;
element7.Brush = new PdfSolidBrush(Color.Black);
element7.Draw(page2, new RectangleF(0, 500, page2.GetClientSize().Width, 110));
#endregion
#region page3
PdfPage page3 = document.Pages.Add();
PdfStructureElement hTextElement4 = new PdfStructureElement(PdfTagType.HeadingLevel2);
hTextElement4.Parent = hTextElement1;
hTextElement4.ActualText = "Resource";
PdfTextElement headerElement4 = new PdfTextElement("Resource", fontHead2, PdfBrushes.Black);
headerElement4.PdfTag = hTextElement1;
headerElement4.Draw(page3, new PointF(0, 0));
PdfStructureElement textElement4 = new PdfStructureElement(PdfTagType.Paragraph);
textElement4.Parent = hTextElement4;
textElement4.ActualText = resource;
PdfTextElement element4 = new PdfTextElement(resource, fontnormal);
element4.PdfTag = textElement4;
element4.Brush = new PdfSolidBrush(Color.Black);
element4.Draw(page3, new RectangleF(0, 40, page2.GetClientSize().Width, 70));
//Create a new PdfGrid.
PdfGrid pdfGrid = new PdfGrid();
PdfStructureElement element = new PdfStructureElement(PdfTagType.Table);
//Adding tag to PDF grid.
pdfGrid.PdfTag = element;
//Add three columns.
pdfGrid.Columns.Add(3);
PdfGridRow[] headerRow = pdfGrid.Headers.Add(3);
PdfGridRow pdfGridHeader = pdfGrid.Headers[0];
pdfGridHeader.PdfTag = new PdfStructureElement(PdfTagType.TableRow);
PdfGridCellStyle headerStyle = new PdfGridCellStyle();
headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 13);
pdfGridHeader.ApplyStyle(headerStyle);
pdfGridHeader.Cells[0].Value = "Times Roman Family";
pdfGridHeader.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableHeader);
pdfGridHeader.Cells[1].Value = "Helvetica Family";
pdfGridHeader.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableHeader);
pdfGridHeader.Cells[2].Value = "Courier Family";
pdfGridHeader.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableHeader);
PdfGridRow pdfGridRow1 = pdfGrid.Rows.Add();
pdfGridRow1.PdfTag = new PdfStructureElement(PdfTagType.TableRow);
pdfGridRow1.Cells[0].Value = "Times roman";
pdfGridRow1.Cells[1].Value = "Helvetica";
pdfGridRow1.Cells[2].Value = "Courier";
pdfGridRow1.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGridRow1.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGridRow1.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
PdfGridRow pdfGridRow2 = pdfGrid.Rows.Add();
pdfGridRow2.PdfTag = new PdfStructureElement(PdfTagType.TableRow);
pdfGridRow2.Cells[0].Value = "Times-Bold";
pdfGridRow2.Cells[1].Value = "Helvetica-Bold";
pdfGridRow2.Cells[2].Value = "Courier-Bold";
pdfGridRow2.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGridRow2.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGridRow2.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
PdfGridRow pdfGridRow3 = pdfGrid.Rows.Add();
pdfGridRow3.PdfTag = new PdfStructureElement(PdfTagType.TableRow);
pdfGridRow3.Cells[0].Value = "Times-Italic";
pdfGridRow3.Cells[1].Value = "Helvetica-Oblique";
pdfGridRow3.Cells[2].Value = "Courier-Oblique";
pdfGridRow3.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGridRow3.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGridRow3.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
PdfGridRow pdfGridRow4 = pdfGrid.Rows.Add();
pdfGridRow4.PdfTag = new PdfStructureElement(PdfTagType.TableRow);
pdfGridRow4.Cells[0].Value = "Times-BoldItalic";
pdfGridRow4.Cells[1].Value = "Helvetica-BoldOblique";
pdfGridRow4.Cells[2].Value = "Courier-BoldOblique";
pdfGridRow4.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGridRow4.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGridRow4.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
pdfGrid.BeginCellLayout += PdfGrid_BeginCellLayout;
pdfGrid.Draw(page3, new PointF(20, 130));
page3.Graphics.DrawRectangle(PdfPens.Black, new RectangleF(20, 120, 490, 90));
#endregion
//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 = "Customtag.pdf";
return fileStreamResult;
}
private void PdfGrid_BeginCellLayout(object sender, PdfGridBeginCellLayoutEventArgs args)
{
// setting transparent color pen as table BorderPen.
PdfPen transparentPen = new PdfPen(new PdfColor(Color.FromArgb(Color.Transparent.A, Color.Transparent.R, Color.Transparent.G, Color.Transparent.B)), .3f);
PdfGridCellStyle pdfGridCellStyle = new PdfGridCellStyle();
pdfGridCellStyle.Borders.All = transparentPen;
args.Style = pdfGridCellStyle;
args.Style.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
}
}
}

Просмотреть файл

@ -1,177 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public PdfController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
//Declaring necessary objects.
Color gray = Color.FromArgb(255, 77, 77, 77);
Color black = Color.FromArgb(255, 0, 0, 0);
Color white = Color.FromArgb(255, 255, 255, 255);
Color violet = Color.FromArgb(255, 151, 108, 174);
public ActionResult Default()
{
return View();
}
[HttpPost]
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;
}
private PdfLayoutResult BodyContent(string text, float yPosition, PdfPage page)
{
float headerBulletsXposition = 35;
PdfTextElement txtElement = new PdfTextElement("3");
txtElement.Font = new PdfStandardFont(PdfFontFamily.ZapfDingbats, 16);
txtElement.Brush = new PdfSolidBrush(violet);
txtElement.StringFormat = new PdfStringFormat();
txtElement.StringFormat.WordWrap = PdfWordWrapType.Word;
txtElement.StringFormat.LineLimit = true;
txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition, yPosition, 320, 100));
txtElement = new PdfTextElement(text);
txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 17);
txtElement.Brush = new PdfSolidBrush(white);
txtElement.StringFormat = new PdfStringFormat();
txtElement.StringFormat.WordWrap = PdfWordWrapType.Word;
txtElement.StringFormat.LineLimit = true;
PdfLayoutResult result = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 25, yPosition, 450, 130));
return result;
}
private PdfLayoutResult HeaderPoints(string text, float yPosition, PdfPage page)
{
float headerBulletsXposition = 220;
PdfTextElement txtElement = new PdfTextElement("l");
txtElement.Font = new PdfStandardFont(PdfFontFamily.ZapfDingbats, 10);
txtElement.Brush = new PdfSolidBrush(violet);
txtElement.StringFormat = new PdfStringFormat();
txtElement.StringFormat.WordWrap = PdfWordWrapType.Word;
txtElement.StringFormat.LineLimit = true;
txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition, yPosition, 300, 100));
txtElement = new PdfTextElement(text);
txtElement.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11);
txtElement.Brush = new PdfSolidBrush(white);
txtElement.StringFormat = new PdfStringFormat();
txtElement.StringFormat.WordWrap = PdfWordWrapType.Word;
txtElement.StringFormat.LineLimit = true;
PdfLayoutResult result = txtElement.Draw(page, new Syncfusion.Drawing.RectangleF(headerBulletsXposition + 20, yPosition, 320, 100));
return result;
}
}
}

Просмотреть файл

@ -1,124 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;
using Syncfusion.Pdf.Security;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Microsoft.AspNetCore.Http;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /DigitalSignature/
public ActionResult DigitalSignature()
{
return View();
}
[HttpPost]
public ActionResult DigitalSignature(string Browser, string password, string Reason, string Location, string Contact, string RadioButtonList2, string NewPDF, string submit, IFormFile file, IFormFile certificate)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
if (submit == "Sign PDF")
{
if (file != null && file.Length > 0 && certificate != null && certificate.Length > 0 && certificate.FileName.Contains(".pfx") && password != null && Location != null && Reason != null && Contact != null)
{
PdfLoadedDocument ldoc = new PdfLoadedDocument(file.OpenReadStream());
PdfCertificate pdfCert = new PdfCertificate(certificate.OpenReadStream(), password);
FileStream jpgFile = new FileStream(dataPath + "PDFDemo.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfBitmap bmp = new PdfBitmap(jpgFile);
PdfPageBase page = ldoc.Pages[0];
PdfSignature signature = new PdfSignature(ldoc, page, pdfCert, "Signature");
signature.Bounds = new RectangleF(new PointF(5, 5), bmp.PhysicalDimension);
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, "password123");
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 = "johndoe@owned.us";
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();
}
}
}
}

Просмотреть файл

@ -1,96 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Xmp;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /DocumentSettings/
public ActionResult DocumentSettings()
{
return View();
}
[HttpPost]
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;
}
}
}

Просмотреть файл

@ -1,282 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /DrawingShapes/
public ActionResult DrawingShapes()
{
return View();
}
[HttpPost]
public ActionResult DrawingShapes(string InsideBrowser)
{
// Create a new PDF document.
PdfDocument doc = new PdfDocument();
int i;
// Create a new page.
PdfPage page = doc.Pages.Add();
// Obtain PdfGraphics object.
PdfGraphics g = page.Graphics;
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold);
#region Polygon
PdfPen pen = new PdfPen(Color.Black);
pen.Width = 3;
PointF p1 = new PointF(05, 10);
PointF p2 = new PointF(05, 10);
PointF p3 = new PointF(60, 70);
PointF p4 = new PointF(40, 70);
PointF[] points = { p1, p2, p3, p4 };
int pointNum = 16;
points = new PointF[pointNum];
double f = 360.0 / pointNum * Math.PI / 180.0;
const double r = 100;
PointF center = new PointF(140, 140);
for (i = 0; i < pointNum; ++i)
{
PointF p = new PointF();
double theta = i * f;
p.Y = (float)(Math.Sin(theta) * r + center.Y);
p.X = (float)(Math.Cos(theta) * r + center.X);
points[i] = p;
}
PdfSolidBrush brush = new PdfSolidBrush(Color.Green);
pen.Color = Color.Brown;
pen.Width = 10;
pen.LineJoin = PdfLineJoin.Round;
g.DrawString("Polygon", font, PdfBrushes.DarkBlue, new PointF(50, 0));
g.DrawPolygon(pen, brush, points);
#endregion
#region Pie
RectangleF rect = new RectangleF(200, 50, 200, 200);
brush.Color = Color.Green;
pen.Color = Color.Brown;
pen.Width = 10;
rect.Location = new PointF(20, 280);
pen.LineJoin = PdfLineJoin.Round;
g.DrawString("Pie shape", font, PdfBrushes.DarkBlue, new PointF(50, 250));
g.DrawPie(pen, brush, rect, 180, 60);
g.DrawPie(pen, brush, rect, 360 - 60, 60);
g.DrawPie(pen, brush, rect, 60, 60);
#endregion
#region Arc
g.DrawString("Arcs", font, PdfBrushes.DarkBlue, new PointF(330, 0));
pen = new PdfPen(Color.Black);
pen.Width = 11;
pen.LineCap = PdfLineCap.Round;
pen.Color = Color.Brown;
rect = new RectangleF(310, 40, 200, 200);
g.DrawArc(pen, rect, 0, 90);
pen.Color = Color.DarkGreen;
rect.X -= 10;
g.DrawArc(pen, rect, 90, 90);
pen.Color = Color.Brown;
rect.Y -= 10;
g.DrawArc(pen, rect, 180, 90);
pen.Color = Color.DarkGreen;
rect.X += 10;
g.DrawArc(pen, rect, 270, 90);
#endregion
#region Rectangle
rect = new RectangleF(310, 280, 200, 100);
brush.Color = Color.Green;
pen.Color = Color.Brown;
g.DrawString("Simple Rectangle", font, PdfBrushes.DarkBlue, new PointF(310, 255));
g.DrawRectangle(pen, brush, rect);
#endregion
#region ellipse
pen = new PdfPen(Color.Black);
rect = new RectangleF(270, 400, 160, 1000);
g.DrawString("Shape with pagination", font, PdfBrushes.DarkBlue, new PointF(300, 390));
PdfEllipse ellipse = new PdfEllipse(rect);
PdfLayoutFormat format = new PdfLayoutFormat();
format.Break = PdfLayoutBreakType.FitPage;
format.Layout = PdfLayoutType.Paginate;
ellipse.Brush = PdfBrushes.Brown;
ellipse.Draw(page, 20, 20, format);
brush = new PdfSolidBrush(Color.Black);
ellipse.Brush = PdfBrushes.DarkGreen;
ellipse.Draw(page, 40, 40, format);
#endregion
#region Transaparency
page = doc.Pages[1];
g = page.Graphics;
g.DrawString("Transparent Rectangles", font, PdfBrushes.DarkBlue, new PointF(50, 80));
PdfBrush gBrush;
rect = new RectangleF(10, 150, 100, 100);
pen = new PdfPen(Color.Black);
gBrush = new PdfSolidBrush(Color.DarkGreen);
g.DrawRectangle(pen, gBrush, rect);
gBrush = new PdfSolidBrush(Color.Brown);
rect.X += 20;
rect.Y += 20;
pen = new PdfPen(Color.Brown);
g.SetTransparency(0.7f);
g.DrawRectangle(pen, gBrush, rect);
rect.X += 20;
rect.Y += 20;
gBrush = new PdfLinearGradientBrush(rect, Color.DarkGreen, Color.Brown, PdfLinearGradientMode.BackwardDiagonal);
g.SetTransparency(0.5f);
g.DrawRectangle(pen, gBrush, rect);
rect.X += 20;
rect.Y += 20;
pen = new PdfPen(Color.Blue);
gBrush = new PdfSolidBrush(Color.Gray);
g.SetTransparency(0.25f);
g.DrawRectangle(pen, gBrush, rect);
rect.X += 20;
rect.Y += 20;
pen = new PdfPen(Color.Black);
gBrush = new PdfSolidBrush(Color.Green);
g.SetTransparency(0.1f);
g.DrawRectangle(pen, gBrush, rect);
#endregion
#region Rectangle with Color space
PointF location = new PointF(10, 50);
page = doc.Pages.Add();
g = page.Graphics;
doc.ColorSpace = (PdfColorSpace)i;
// SolidBrush
gBrush = new PdfSolidBrush(Color.Red);
DrawRectangles(location, g, font, gBrush, pen, doc);
// LinearGradient
location = new PointF(180, 50);
PointF point2 = location;
point2.X += 180;
gBrush = new PdfLinearGradientBrush(location, point2, Color.Blue, Color.Red);
DrawRectangles(location, g, font, gBrush, pen, doc);
// Raidal Gradient
location = new PointF(360, 50);
point2 = location;
point2 = new PointF(location.X + 50, location.Y + 50);
//point2.Y += 250;
//point2.X = 150;
gBrush = new PdfRadialGradientBrush(point2, 0, point2, 100, Color.Blue, Color.Red);
(gBrush as PdfRadialGradientBrush).Extend = PdfExtend.Both;
DrawRectangles(location, g, font, gBrush, pen, doc);
g.DrawString("Rectangle with color spaces", font, PdfBrushes.DarkBlue, new PointF(150, 0));
#endregion
//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 = "Shapes.pdf";
return fileStreamResult;
}
# region Helpher Methods
/// <summary>
/// Draws rectangle
/// </summary>
/// <param name="startPoint"></param>
/// <param name="g"></param>
/// <param name="font"></param>
/// <param name="brush"></param>
/// <param name="pen"></param>
private void DrawRectangles(PointF startPoint, PdfGraphics g, PdfFont font, PdfBrush brush, PdfPen pen, PdfDocument doc)
{
PdfBrush textBrush = new PdfSolidBrush(Color.Black);
RectangleF rect = new RectangleF(startPoint.X, startPoint.Y, 100, 100);
g.Save();
g.DrawString("Default: " + doc.ColorSpace.ToString(), font, textBrush, rect.Location);
rect.Y += 20;
g.DrawRectangle(pen, brush, rect);
rect.Y += 106;
doc.ColorSpace = PdfColorSpace.RGB;
g.DrawString("RGB color space.", font, textBrush, rect.Location);
rect.Y += 20;
g.DrawRectangle(pen, brush, rect);
rect.Y += 106;
doc.ColorSpace = PdfColorSpace.CMYK;
g.DrawString("CMYK color space.", font, textBrush, rect.Location);
rect.Y += 20;
g.DrawRectangle(pen, brush, rect);
rect.Y += 106;
doc.ColorSpace = PdfColorSpace.GrayScale;
g.DrawString("Gray scale color space.", font, textBrush, rect.Location);
rect.Y += 20;
g.DrawRectangle(pen, brush, rect);
rect.Y += 106;
g.Restore();
}
# endregion
}
}

Просмотреть файл

@ -1,104 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using Syncfusion.Pdf.Security;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using System;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
public ActionResult Encryption()
{
return View();
}
[HttpPost]
public ActionResult Encryption(string InsideBrowser, string encryptionType)
{
PdfDocument document = new PdfDocument();
PdfPage page = document.Pages.Add();
PdfGraphics graphics = page.Graphics;
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Bold);
PdfBrush brush = PdfBrushes.Black;
PdfForm form = document.Form;
//Document security
PdfSecurity security = document.Security;
//Specify key size and encryption algorithm
if (encryptionType == "40_RC4")
{
//use 40 bits key in RC4 mode
security.KeySize = PdfEncryptionKeySize.Key40Bit;
}
else if (encryptionType == "128_RC4")
{
//use 128 bits key in RC4 mode
security.KeySize = PdfEncryptionKeySize.Key128Bit;
security.Algorithm = PdfEncryptionAlgorithm.RC4;
}
else if (encryptionType == "128_AES")
{
//use 128 bits key in AES mode
security.KeySize = PdfEncryptionKeySize.Key128Bit;
security.Algorithm = PdfEncryptionAlgorithm.AES;
}
else if (encryptionType == "256_AES")
{
//use 256 bits key in AES mode
security.KeySize = PdfEncryptionKeySize.Key256Bit;
security.Algorithm = PdfEncryptionAlgorithm.AES;
}
else if (encryptionType == "256_AES_Revision_6")
{
security.KeySize = PdfEncryptionKeySize.Key256BitRevision6;
security.Algorithm = PdfEncryptionAlgorithm.AES;
}
security.OwnerPassword = "syncfusion";
security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;
security.UserPassword = "password";
string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" +
"UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm);
if (encryptionType == "256_AES_Revision_6")
{
text += String.Format("\n\nRevision: {0}", "Revision 6");
}
else if (encryptionType == "256_AES")
{
text += String.Format("\n\nRevision: {0}", "Revision 5");
}
graphics.DrawString("Document is Encrypted with following settings", font, brush, PointF.Empty);
font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Bold);
graphics.DrawString(text, font, brush, new PointF(0, 40));
//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 = "Secure.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,58 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using Syncfusion.Pdf.Parsing;
using samplebrowser.Models;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
// GET: /ExtractText/
public IActionResult ExtractText()
{
return View();
}
[HttpPost]
public IActionResult ExtractText(string ViewTemplate, string Extract)
{
string basePath = _hostingEnvironment.WebRootPath;
FileStream fileStreamInput = new FileStream(basePath + @"/PDF/HTTP Succinctly.pdf", FileMode.Open, FileAccess.Read);
if (!string.IsNullOrEmpty(ViewTemplate))
{
FileStreamResult fileStreamResult = new FileStreamResult(fileStreamInput, "application/pdf");
fileStreamResult.FileDownloadName = "HTTP Succinctly.pdf";
return fileStreamResult;
}
else if (!string.IsNullOrEmpty(Extract))
{
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(fileStreamInput);
string extractedText = string.Empty;
for (var i = 0; i < loadedDocument.Pages.Count; i++)
{
extractedText += loadedDocument.Pages[i].ExtractText(true);
}
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(extractedText);
MemoryStream stream = new MemoryStream(byteArray);
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/txt");
fileStreamResult.FileDownloadName = "Sample.txt";
return fileStreamResult;
}
return View();
}
}
}

Просмотреть файл

@ -1,62 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using Syncfusion.Pdf.Parsing;
using samplebrowser.Models;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
// GET: /FindText/
public IActionResult FindText()
{
FindTextMessage message = new FindTextMessage();
message.Message = string.Empty;
return View("FindText", message);
}
[HttpPost]
public IActionResult FindText(string ViewTemplate, string Find)
{
string basePath = _hostingEnvironment.WebRootPath;
FileStream fileStreamInput = new FileStream(basePath + @"/PDF/Manual.pdf", FileMode.Open, FileAccess.Read);
if (!string.IsNullOrEmpty(ViewTemplate))
{
FileStreamResult fileStreamResult = new FileStreamResult(fileStreamInput, "application/pdf");
fileStreamResult.FileDownloadName = "Manual.pdf";
return fileStreamResult;
}
else if (!string.IsNullOrEmpty(Find))
{
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(fileStreamInput);
Dictionary<int, List<Syncfusion.Drawing.RectangleF>> matchRects = new Dictionary<int, List<Syncfusion.Drawing.RectangleF>>();
loadedDocument.FindText("document", out matchRects);
FindTextMessage message = new FindTextMessage();
for (int i = 0; i < loadedDocument.Pages.Count; i++)
{
List<Syncfusion.Drawing.RectangleF> rectCoords = matchRects[i];
message.Message = "First Occurrence: X:" + rectCoords[0].X + "; Y:" + rectCoords[0].Y + "; Width:" + rectCoords[0].Width+"; Height:" + rectCoords[0].Height + Environment.NewLine +
"Second Occurrence: X:" + rectCoords[1].X + "; Y:" + rectCoords[1].Y + "; Width:" + rectCoords[1].Width + "; Height:" + rectCoords[1].Height + Environment.NewLine +
"Third Occurrence: X:" + rectCoords[2].X + "; Y:" + rectCoords[2].Y + "; Width:" + rectCoords[2].Width + "; Height:" + rectCoords[2].Height + Environment.NewLine +
"Fourth Occurrence: X:" + rectCoords[3].X + "; Y:" + rectCoords[3].Y + "; Width:" + rectCoords[3].Width + "; Height:" + rectCoords[3].Height + Environment.NewLine;
return View("FindText", message);
}
}
return View("FindText");
}
}
}

Просмотреть файл

@ -1,141 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /FormFilling/
public ActionResult FormFilling()
{
return View();
}
[HttpPost]
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();
}
}
}

Просмотреть файл

@ -1,268 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.ColorSpace;
using Syncfusion.Pdf.Functions;
using Syncfusion.Pdf.Graphics;
using System.IO;
using System.Reflection;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /GraphicsBrushes/
public ActionResult GraphicBrushes()
{
return View();
}
[HttpPost]
public ActionResult GraphicBrushes(string InsideBrowser)
{
//Create a new PDF document
PdfDocument document = new PdfDocument();
document.PageSettings = new PdfPageSettings(new SizeF(300, 400));
# region Graphic Brushes
PdfPage page = document.Pages.Add();
PdfGraphics graphics = page.Graphics;
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Read the file
FileStream file = new FileStream(dataPath + "simple.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfImage image = PdfImage.FromStream(file);
PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 8f, PdfFontStyle.Bold);
PdfFont font1 = new PdfStandardFont(PdfFontFamily.TimesRoman, 7f, PdfFontStyle.Bold);
graphics.DrawString("PDF Graphic Brushes", font, PdfBrushes.Black, new PointF(80, 20));
graphics.DrawString("Solid Brush", font1, PdfBrushes.Black, new PointF(10, 40));
//SolidBrush
RectangleF rectangle = new RectangleF(20, 60, 50, 50);
PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
graphics.DrawEllipse(brush, rectangle);
graphics.TranslateTransform(60, 0);
brush = new PdfSolidBrush(Color.Green);
graphics.DrawEllipse(brush, rectangle);
graphics.TranslateTransform(60, 0);
brush.Color = Color.Red;
PdfBrush someBrush = brush.Clone();
graphics.DrawEllipse(someBrush, rectangle);
graphics.TranslateTransform(-120, 70);
graphics.DrawString("Tiling Brush", font1, PdfBrushes.Black, new PointF(10, 60));
//TillingBrush
graphics.TranslateTransform(0, 20);
PdfTilingBrush tillingBrush = new PdfTilingBrush(new SizeF(10, 10));
RectangleF rect = new RectangleF(0, 0, 10, 10);
tillingBrush.Graphics.DrawImage(image, 0, 0, 10, 10);
graphics.DrawEllipse(tillingBrush, rectangle);
graphics.TranslateTransform(60, 0);
tillingBrush = new PdfTilingBrush(rect);
tillingBrush.Graphics.DrawEllipse(PdfPens.Yellow, rect);
tillingBrush.Graphics.DrawLine(PdfPens.Green, 0, 0, 10, 10);
tillingBrush.Graphics.DrawLine(PdfPens.Red, 0, 10, 10, 0);
graphics.DrawEllipse(tillingBrush, rectangle);
graphics.TranslateTransform(60, 0);
rect = new RectangleF(0, 0, 20, 20);
PdfTilingBrush tillingBrushNew = new PdfTilingBrush(rect);
tillingBrushNew.Graphics.DrawEllipse(tillingBrush, rect);
graphics.DrawEllipse(tillingBrushNew, rectangle);
# endregion
# region PdfColorSpace
page = document.Pages.Add();
PdfGraphics g = page.Graphics;
g.DrawString("Color Space", font, PdfBrushes.Black, new PointF(120, 20));
//Set DeviceRGB Colorspace.
document.ColorSpace = PdfColorSpace.RGB;
page.Graphics.DrawString("Device RGB", font, PdfBrushes.Black, new PointF(10, 50));
PdfBrush brush1 = PdfBrushes.Green;
g.DrawRectangle(brush1, new RectangleF(20, 70, 30, 30));
//Set DeviceCMYK Colorspace.
document.ColorSpace = PdfColorSpace.CMYK;
page.Graphics.DrawString("Device CMYK", font, PdfBrushes.Black, new PointF(90, 50));
g.DrawEllipse(brush1, new RectangleF(100, 70, 30, 30));
//Set DeviceGray Colorspace.
document.ColorSpace = PdfColorSpace.GrayScale;
page.Graphics.DrawString("Device Gray", font, PdfBrushes.Black, new PointF(170, 50));
g.DrawPie(brush1, new RectangleF(180, 70, 30, 30), 0, 45);
# endregion
# region CIE Based Color Space
# region CalRGB Color
document.ColorSpace = PdfColorSpace.RGB;
//page = document.Pages.Add();
g = page.Graphics;
g.DrawString("CalRGB Color", font, PdfBrushes.Black, new PointF(10, 130));
rect = new RectangleF(20, 140, 30, 30);
// Instantiate CalRGB Color Space
PdfCalRGBColorSpace calRgbCS = new PdfCalRGBColorSpace();
calRgbCS.Gamma = new double[] { 1.6, 1.1, 2.5 };
calRgbCS.Matrix = new double[] { 1, 0, 0, 0, 1, 0, 0, 0, 1 };
calRgbCS.WhitePoint = new double[] { 0.2, 1, 0.8 };
PdfCalRGBColor red = new PdfCalRGBColor(calRgbCS);
red.Red = 0;
red.Green = 1;
red.Blue = 0;
PdfBrush brush2 = new PdfSolidBrush(red);
g.DrawRectangle(brush2, rect);
# endregion
# region CalGray Color
g.DrawString("CalGray Color", font, PdfBrushes.Black, new PointF(90, 130));
rect = new RectangleF(100, 140, 30, 30);
PdfCalGrayColorSpace calGrayCS = new PdfCalGrayColorSpace();
calGrayCS.Gamma = 0.7;
calGrayCS.WhitePoint = new double[] { 0.2, 1, 0.8 };
PdfCalGrayColor red1 = new PdfCalGrayColor(calGrayCS);
red1.Gray = 0.1;
brush2 = new PdfSolidBrush(red1);
g.DrawRectangle(brush2, rect);
# endregion
# region Lab Color
page.Graphics.DrawString("Lab Color", font, PdfBrushes.Black, new PointF(170, 130));
rect = new RectangleF(180, 140, 30, 30);
PdfLabColorSpace calGrayCS1 = new PdfLabColorSpace();
calGrayCS1.Range = new double[] { 0.2, 1, 0.8, 23.5 };
calGrayCS1.WhitePoint = new double[] { 0.2, 1, 0.8 };
PdfLabColor red2 = new PdfLabColor(calGrayCS1);
red2.L = 90;
red2.A = 0.5;
red2.B = 20;
brush2 = new PdfSolidBrush(red2);
g.DrawRectangle(brush2, rect);
# endregion
# region ICC Color
g.DrawString("ICC Color", font, PdfBrushes.Black, new PointF(10, 200));
rect = new RectangleF(20, 210, 30, 30);
PdfCalRGBColorSpace calRgbCS3 = new PdfCalRGBColorSpace();
calRgbCS3.Gamma = new double[] { 7.6, 5.1, 8.5 };
calRgbCS3.Matrix = new double[] { 1, 0, 0, 0, 1, 0, 0, 0, 1 };
calRgbCS3.WhitePoint = new double[] { 0.7, 1, 0.8 };
// Read the ICC profile.
FileStream fs = new FileStream(dataPath +"rgb.icc", FileMode.Open, FileAccess.Read);
byte[] profileData = new byte[fs.Length];
fs.Read(profileData, 0, profileData.Length);
fs.Dispose();
PdfICCColorSpace IccBasedCS4 = new PdfICCColorSpace();
IccBasedCS4.ProfileData = profileData;
IccBasedCS4.AlternateColorSpace = calRgbCS3;
IccBasedCS4.ColorComponents = 3;
IccBasedCS4.Range = new double[] { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0 };
PdfICCColor red4 = new PdfICCColor(IccBasedCS4);
red4.ColorComponents = new double[] { 1, 0, 1 };
brush2 = new PdfSolidBrush(red4);
g.DrawRectangle(brush2, rect);
# endregion
# region Separation Color
g.DrawString("Separation Color", font, PdfBrushes.Black, new PointF(90, 200));
rect = new RectangleF(100, 210, 30, 30);
PdfExponentialInterpolationFunction function = new PdfExponentialInterpolationFunction(true);
float[] numArray = new float[3];
numArray[0] = 90f;
numArray[1] = 0.5f;
numArray[2] = 20f;
function.C1 = numArray;
PdfLabColorSpace calLabCS8 = new PdfLabColorSpace();
calLabCS8.Range = new double[] { 0.2, 1, 0.8, 23.5 };
calLabCS8.WhitePoint = new double[] { 0.2, 1, 0.8 };
PdfSeparationColorSpace colorspace8 = new PdfSeparationColorSpace();
colorspace8.AlternateColorSpaces = calLabCS8;
colorspace8.TintTransform = function;
colorspace8.Colorant = "PANTONE Orange 021 C";
PdfSeparationColor color8 = new PdfSeparationColor(colorspace8);
color8.Tint = 0.7;
brush2 = new PdfSolidBrush(color8);
g.DrawRectangle(brush2, rect);
# endregion
# region Indexed Color
g.DrawString("Indexed Color", font, PdfBrushes.Black, new PointF(170, 200));
rect = new RectangleF(180, 210, 30, 30);
PdfIndexedColorSpace colorspace7 = new PdfIndexedColorSpace();
colorspace7.BaseColorSpace = new PdfDeviceColorSpace(PdfColorSpace.RGB);
colorspace7.MaxColorIndex = 3;
colorspace7.IndexedColorTable = new byte[] { 150, 0, 222, 255, 0, 0, 0, 255, 0, 0, 0, 255 };
PdfIndexedColor color7 = new PdfIndexedColor(colorspace7);
color7.SelectColorIndex = 3;
brush2 = new PdfSolidBrush(color7);
g.DrawRectangle(brush2, rect);
# endregion
# 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 = "GraphicBrushes.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,325 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using System.IO;
using System.Text;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /HeadersandFooters/
# region Private Members
private bool m_paginateStart = true;
RectangleF bounds;
private RectangleF m_columnBounds;
# endregion
public ActionResult HeadersandFooters()
{
return View();
}
[HttpPost]
public ActionResult HeadersFooters(string InsideBrowser)
{
//Create a PDF document
PdfDocument doc = new PdfDocument();
//Add a page
PdfPage page = doc.Pages.Add();
RectangleF rect = new RectangleF(0, 0, page.GetClientSize().Width, 50);
PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
PdfPen pen = new PdfPen(Color.Black, 1f);
//Create font
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 11.5f);
PdfFont heading = new PdfStandardFont(PdfFontFamily.Courier, 14,PdfFontStyle.Bold);
//Adding Header
this.AddDocumentHeader(doc, "Syncfusion Essential PDF", "Header and Footer Demo");
//Adding Footer
this.AddDocumentFooter(doc, "@Copyright 2018");
//Set formats
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Justify;
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Read the file
FileStream file = new FileStream(dataPath + "Essential studio.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(file, Encoding.ASCII);
string text = reader.ReadToEnd();
reader.Dispose();
RectangleF column = new RectangleF(0, 20, page.Graphics.ClientSize.Width / 2f - 10f, page.Graphics.ClientSize.Height);
bounds = column;
m_columnBounds = column;
//Create text element to control the text flow
PdfTextElement element = new PdfTextElement(text, font);
element.Brush = new PdfSolidBrush(Color.Black);
element.StringFormat = format;
PdfLayoutFormat layoutFormat = new PdfLayoutFormat();
layoutFormat.Break = PdfLayoutBreakType.FitPage;
layoutFormat.Layout = PdfLayoutType.Paginate;
//Get the remaining text that flows beyond the boundary.
PdfTextLayoutResult result = element.Draw(page, bounds, layoutFormat);
file = new FileStream(dataPath + "Essential PDF.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
reader = new StreamReader(file, Encoding.ASCII);
text = reader.ReadToEnd();
reader.Dispose();
element = new PdfTextElement(text, font);
element.Brush = new PdfSolidBrush(Color.Black);
element.StringFormat = format;
// Next paragraph flow from last line of the previous paragraph.
bounds.Y = result.LastLineBounds.Y + 35f;
//Raise the event when the text flows to next page.
element.BeginPageLayout += new BeginPageLayoutEventHandler(BeginPageLayout2);
//Raise the event when the text reaches the end of the page.
element.EndPageLayout += new EndPageLayoutEventHandler(EndPageLayout2);
result.Page.Graphics.DrawString("Essential PDF", heading, PdfBrushes.DarkBlue, new PointF(bounds.X, bounds.Y));
bounds.Y = result.LastLineBounds.Y + 60f;
result = element.Draw(result.Page, new RectangleF(bounds.X, bounds.Y, bounds.Width, -1), layoutFormat);
file = new FileStream(dataPath + "Essen PDF.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfImage image = new PdfBitmap(file);
bounds.Y = result.LastLineBounds.Y + 20f;
bounds.X = bounds.Width + 20f;
result.Page.Graphics.DrawImage(image, new PointF(bounds.X, bounds.Y));
result.Page.Graphics.DrawString("Essential DocIO", heading, PdfBrushes.DarkBlue, new PointF(bounds.X, bounds.Y + image.Height));
file = new FileStream(dataPath + "Essential DocIO.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
reader = new StreamReader(file, Encoding.ASCII);
text = reader.ReadToEnd();
reader.Dispose();
element = new PdfTextElement(text, font);
element.Brush = new PdfSolidBrush(Color.Black);
element.StringFormat = format;
bounds.Y = result.LastLineBounds.Y + image.Height + 40;
bounds.X = bounds.Width + 20f;
result = element.Draw(result.Page, new RectangleF(bounds.X, bounds.Y, bounds.Width, -1), layoutFormat);
file = new FileStream(dataPath + "Essen DocIO.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
image = new PdfBitmap(file);
bounds.Y = result.LastLineBounds.Y + 20f;
bounds.X = bounds.Width + 20f;
result.Page.Graphics.DrawImage(image, new PointF(bounds.X, bounds.Y));
file = new FileStream(dataPath + "Essential XlsIO.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
reader = new StreamReader(file, Encoding.ASCII);
text = reader.ReadToEnd();
reader.Dispose();
element = new PdfTextElement(text, font);
element.Brush = new PdfSolidBrush(Color.Black);
element.StringFormat = format;
result.Page.Graphics.DrawString("Essential XlsIO", heading, PdfBrushes.DarkBlue, new PointF(bounds.X, bounds.Y + image.Height));
bounds.Y = result.LastLineBounds.Y + image.Height + 40;
bounds.X = bounds.Width + 20f;
result = element.Draw(result.Page, new RectangleF(bounds.X, bounds.Y, bounds.Width, -1), layoutFormat);
file = new FileStream(dataPath + "Essen XlsIO.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
image = new PdfBitmap(file);
bounds.Y = result.LastLineBounds.Y + 20f;
bounds.X = bounds.Width + 20f;
result.Page.Graphics.DrawImage(image, new PointF(bounds.X, bounds.Y));
//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 = "HeadersAndFooters.pdf";
return fileStreamResult;
}
private void EndPageLayout2(object sender, EndPageLayoutEventArgs e)
{
EndTextPageLayoutEventArgs args = (EndTextPageLayoutEventArgs)e;
PdfTextLayoutResult tlr = args.Result;
RectangleF bounds = tlr.Bounds;
args.NextPage = tlr.Page;
}
private void BeginPageLayout2(object sender, BeginPageLayoutEventArgs e)
{
RectangleF bounds = e.Bounds;
// First column.
if (!m_paginateStart)
{
bounds.X = bounds.Width + 20f;
bounds.Y = 10f;
}
else
{
// Second column.
bounds.X = 0f;
m_paginateStart = false;
}
e.Bounds = bounds;
m_columnBounds = bounds;
}
# region Helper Methods
/// <summary>
/// Adds header to the document
/// </summary>
/// <param name="doc"></param>
/// <param name="title"></param>
/// <param name="description"></param>
private void AddDocumentHeader(PdfDocument doc, string title, string description)
{
RectangleF rect = new RectangleF(0, 0, doc.Pages[0].GetClientSize().Width, 50);
//Create page template
PdfPageTemplateElement header = new PdfPageTemplateElement(rect);
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 24);
float doubleHeight = font.Height * 2;
Color activeColor = Color.FromArgb(44, 71, 120);
SizeF imageSize = new SizeF(110f, 35f);
//Locating the logo on the right corner of the Drawing Surface
PointF imageLocation = new PointF(doc.Pages[0].GetClientSize().Width - imageSize.Width - 20, 5);
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 img = new PdfBitmap(file);
//Draw the image in the Header.
header.Graphics.DrawImage(img, imageLocation, imageSize);
PdfSolidBrush brush = new PdfSolidBrush(activeColor);
PdfPen pen = new PdfPen(Color.DarkBlue, 3f);
font = new PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold);
//Set formattings for the text
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
format.LineAlignment = PdfVerticalAlignment.Middle;
//Draw title
header.Graphics.DrawString(title, font, brush, new RectangleF(0, 0, header.Width, header.Height), format);
brush = new PdfSolidBrush(Color.Gray);
font = new PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold);
format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Left;
format.LineAlignment = PdfVerticalAlignment.Bottom;
//Draw description
header.Graphics.DrawString(description, font, brush, new RectangleF(0, 0, header.Width, header.Height - 8), format);
//Draw some lines in the header
pen = new PdfPen(Color.DarkBlue, 0.7f);
header.Graphics.DrawLine(pen, 0, 0, header.Width, 0);
pen = new PdfPen(Color.DarkBlue, 2f);
header.Graphics.DrawLine(pen, 0, 03, header.Width + 3, 03);
pen = new PdfPen(Color.DarkBlue, 2f);
header.Graphics.DrawLine(pen, 0, header.Height - 3, header.Width, header.Height - 3);
header.Graphics.DrawLine(pen, 0, header.Height, header.Width, header.Height);
//Add header template at the top.
doc.Template.Top = header;
}
/// <summary>
/// Adds footer to the document
/// </summary>
/// <param name="doc"></param>
/// <param name="footerText"></param>
private void AddDocumentFooter(PdfDocument doc, string footerText)
{
RectangleF rect = new RectangleF(0, 0, doc.Pages[0].GetClientSize().Width, 50);
//Create a page template
PdfPageTemplateElement footer = new PdfPageTemplateElement(rect);
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 8);
PdfSolidBrush brush = new PdfSolidBrush(Color.Gray);
PdfPen pen = new PdfPen(Color.DarkBlue, 3f);
font = new PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold);
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
format.LineAlignment = PdfVerticalAlignment.Middle;
footer.Graphics.DrawString(footerText, font, brush, new RectangleF(0, 18, footer.Width, footer.Height), format);
format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Right;
format.LineAlignment = PdfVerticalAlignment.Bottom;
//Create page number field
PdfPageNumberField pageNumber = new PdfPageNumberField(font, brush);
//Create page count field
PdfPageCountField count = new PdfPageCountField(font, brush);
//Create author field
PdfDocumentAuthorField authorField = new PdfDocumentAuthorField(font, brush);
footer.Graphics.DrawString("Page\tof", font, brush, new RectangleF(0, 0, footer.Width - 8, footer.Height - 8), format);
//Draw current page number
pageNumber.Draw(footer.Graphics, new PointF(496, 35));
//Draw number of pages
count.Draw(footer.Graphics, new PointF(510, 35));
//Draw number of pages
authorField.Draw(footer.Graphics, new PointF(320, 35));
//Add the footer template at the bottom
doc.Template.Bottom = footer;
}
#endregion
}
}

Просмотреть файл

@ -1,77 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
public ActionResult ImageInsertion()
{
return View();
}
[HttpPost]
public ActionResult ImageInsertion(string Browser)
{
string dataPath = _hostingEnvironment.WebRootPath + @"/PDF/";
// Create a new instance of PdfDocument class.
PdfDocument document = new PdfDocument();
// Add a new page to the newly created document.
PdfPage page = document.Pages.Add();
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold);
PdfGraphics g = page.Graphics;
g.DrawString("JPEG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 40));
//Load JPEG image to stream.
FileStream jpgImageStream = new FileStream(dataPath + "Xamarin_JPEG.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Load the JPEG image
PdfImage jpgImage = new PdfBitmap(jpgImageStream);
//Draw the JPEG image
g.DrawImage(jpgImage,new Syncfusion.Drawing.RectangleF(0,70,515,215));
g.DrawString("PNG Image", font, PdfBrushes.Blue, new Syncfusion.Drawing.PointF(0, 355));
//Load PNG image to stream.
FileStream pngImageStream = new FileStream(dataPath + "Xamarin_PNG.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Load the PNG image
PdfImage pngImage = new PdfBitmap(pngImageStream);
g.DrawImage(pngImage,new Syncfusion.Drawing.RectangleF(0,365,199,300));
MemoryStream stream = new MemoryStream();
//Save the PDF document
document.Save(stream);
stream.Position = 0;
//Close the PDF document
document.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = "ImageInsertion.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,73 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /ImportAndStamp/
public ActionResult ImportAndStamp()
{
return View();
}
[HttpPost]
public ActionResult ImportAndStamp(string Browser, string Stamptext, IFormFile file)
{
PdfLoadedDocument ldoc = null;
if (file != null && file.Length > 0)
{
ldoc = new PdfLoadedDocument(file.OpenReadStream());
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 36f);
foreach (PdfPageBase lPage in ldoc.Pages)
{
PdfGraphics graphics = lPage.Graphics;
PdfGraphicsState state = graphics.Save();
graphics.SetTransparency(0.25f);
graphics.RotateTransform(-40);
graphics.DrawString(Stamptext, font, PdfPens.Red, PdfBrushes.Red, new PointF(-150, 450));
graphics.Restore(state);
}
}
else
{
ViewBag.lab = "NOTE: Please select PDF document.";
return View();
}
MemoryStream stream = new MemoryStream();
//Save the PDF document
ldoc.Save(stream);
stream.Position = 0;
//Close the PDF document
ldoc.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = "Stamp.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,327 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using Syncfusion.Pdf.Tables;
using System.IO;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
public ActionResult InteractiveFeatures()
{
return View();
}
PdfPage interactivePage;
PdfDocument document;
[HttpPost]
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;
}
#region Helper Methods
void table_BeginCellLayout(object sender, BeginCellLayoutEventArgs args)
{
if (args.CellIndex == 2 && args.RowIndex > -1)
{
CreateTextBox(interactivePage, "price" + args.RowIndex.ToString(), "Price", args.Bounds, true, args.Value);
args.Skip = true;
}
else if (args.CellIndex == 3 && args.RowIndex == -1)
{
PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation(new RectangleF(args.Bounds.Right - 18, args.Bounds.Top + 2, 1, 1),
"Please enter a validate interger between 1 to 50");
popupAnnotation.Border.Width = 4;
popupAnnotation.Open = false;
popupAnnotation.Border.HorizontalRadius = 10;
popupAnnotation.Border.VerticalRadius = 10;
popupAnnotation.Icon = PdfPopupIcon.Comment;
interactivePage.Annotations.Add(popupAnnotation);
}
else if (args.CellIndex == 3 && args.RowIndex > -1)
{
PdfTextBoxField textBoxField = new PdfTextBoxField(interactivePage, "quantity" + args.RowIndex.ToString());
//Set properties to the textbox.
textBoxField.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); ;
textBoxField.BorderColor = new PdfColor(white);
textBoxField.BackColor = Syncfusion.Drawing.Color.FromArgb(255, 238, 238, 248);
textBoxField.Bounds = args.Bounds;
textBoxField.Text = "0";
PdfJavaScriptAction action = new PdfJavaScriptAction(@"event.rc = event.value > -1 && event.value < 51;
var f = this.getField('price" + args.RowIndex.ToString() + @"')
var f1 = this.getField('quantity" + args.RowIndex.ToString() + @"')
var f2 = this.getField('TotalPrice" + args.RowIndex.ToString() + @"')
var f3 = this.getField('GrandTotal');
if(!event.rc)
{
f1.fillColor=color.red;
app.beep();
}
else
{
f1.fillColor = color.transparent;
f2.value = f1.value * f.value;
f3.value = this.getField('TotalPrice0').value + this.getField('TotalPrice1').value + this.getField('TotalPrice2').value + this.getField('TotalPrice3').value + this.getField('TotalPrice4').value +this.getField('TotalPrice5').value;
}");
textBoxField.Actions.LostFocus = action;
document.Form.Fields.Add(textBoxField);
}
else if (args.CellIndex == 4 && args.RowIndex > -1)
{
CreateTextBox(interactivePage, "TotalPrice" + args.RowIndex.ToString(), "Total Price", args.Bounds, true, "0");
}
}
/// <summary>
/// Creates textbox and adds it in the form.
/// </summary>
/// <param name="page"></param>
/// <param name="text"></param>
/// <param name="tooltip"></param>
/// <param name="f"></param>
/// <param name="bounds"></param>
private void CreateTextBox(PdfPage page, string text, string tooltip, RectangleF bounds, bool readOnly, string value)
{
// Create a Text box field.
PdfTextBoxField textBoxField = new PdfTextBoxField(page, text);
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
//Set properties to the textbox.
textBoxField.Font = font;
textBoxField.BackColor = Syncfusion.Drawing.Color.FromArgb(255, 238, 238, 248);
textBoxField.BorderColor = white;
textBoxField.Bounds = bounds;
textBoxField.ToolTip = tooltip;
textBoxField.ReadOnly = readOnly;
textBoxField.Text = value;
document.Form.Fields.Add(textBoxField);
}
public static IEnumerable<CylceProducts> GetProductReport(string webRootPath)
{
string dataPath = webRootPath + @"/PDF/";
//Read the file
FileStream xmlStream = new FileStream(dataPath + "AdventureWorkCycle.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader reader = new StreamReader(xmlStream, true))
{
return XElement.Parse(reader.ReadToEnd())
.Elements("Report")
.Select(c => new CylceProducts
{
ProductID = c.Element("ProductID").Value,
Product = c.Element("Product").Value,
Price = c.Element("Price").Value,
Quantity = c.Element("Quantity").Value,
TotalPrice = c.Element("TotalPrice").Value
});
}
}
#region Products
public class CylceProducts
{
public string ProductID { get; set; }
public string Product { get; set; }
public string Price { get; set; }
public string Quantity { get; set; }
public string TotalPrice { get; set; }
}
#endregion
#endregion
}
}

Просмотреть файл

@ -1,414 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /JobApplication/
public ActionResult JobApplication()
{
return View();
}
[HttpPost]
public ActionResult JobApplication(string Browser)
{
PdfDocument pdfDoc = new PdfDocument();
pdfDoc.ViewerPreferences.HideMenubar = true;
pdfDoc.ViewerPreferences.HideWindowUI = true;
pdfDoc.ViewerPreferences.HideToolbar = true;
pdfDoc.ViewerPreferences.FitWindow = true;
pdfDoc.ViewerPreferences.PageLayout = PdfPageLayout.SinglePage;
pdfDoc.PageSettings.Orientation = PdfPageOrientation.Portrait;
pdfDoc.PageSettings.Margins.All = 0;
//To set coordinates to draw form fields
RectangleF bounds = new RectangleF(180, 65, 156, 15);
PdfUnitConverter con = new PdfUnitConverter();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Read the file
FileStream file = new FileStream(dataPath + "Careers.png", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfImage img = new PdfBitmap(file);
//Set the page size
SizeF pageSize = new SizeF(500, 310);
pdfDoc.PageSettings.Height = pageSize.Height;
pdfDoc.PageSettings.Width = pageSize.Width;
PdfFont pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold);
#region First Page
pdfDoc.Pages.Add();
PdfPage firstPage = pdfDoc.Pages[0];
pdfDoc.Pages[0].Graphics.DrawImage(img, 0, 0, pageSize.Width, pageSize.Height);
pdfDoc.Pages[0].Graphics.DrawString("General Information", pdfFont, new PdfSolidBrush(new PdfColor(213, 123, 19)), 25, 40);
pdfDoc.Pages[0].Graphics.DrawString("Education Grade", pdfFont, new PdfSolidBrush(new PdfColor(213, 123, 19)), 25, 190);
pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
//Create fields in first page.
pdfDoc.Pages[0].Graphics.DrawString("First Name:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 65);
//Create text box for firstname.
PdfTextBoxField textBoxField1 = new PdfTextBoxField(pdfDoc.Pages[0], "FirstName");
textBoxField1.ToolTip = "First Name";
PdfStandardFont font1 = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
textBoxField1.Font = font1;
textBoxField1.BorderColor = new PdfColor(Color.Gray);
textBoxField1.BorderStyle = PdfBorderStyle.Beveled;
textBoxField1.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField1);
pdfDoc.Pages[0].Graphics.DrawString("Last Name:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 83);
//Set position to draw form fields
bounds.Y = bounds.Y + 18;
//Create text box for lastname.
PdfTextBoxField textBoxField2 = new PdfTextBoxField(pdfDoc.Pages[0], "LastName");
textBoxField2.ToolTip = "Last Name";
textBoxField2.Font = font1;
textBoxField2.BorderColor = new PdfColor(Color.Gray);
textBoxField2.BorderStyle = PdfBorderStyle.Beveled;
textBoxField2.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField2);
pdfDoc.Pages[0].Graphics.DrawString("Email:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 103);
//Set position to draw form fields
bounds.Y = bounds.Y + 18;
//Create text box for Email.
PdfTextBoxField textBoxField3 = new PdfTextBoxField(pdfDoc.Pages[0], "Email");
textBoxField3.ToolTip = "Email id";
textBoxField3.Font = font1;
textBoxField3.BorderColor = new PdfColor(Color.Gray);
textBoxField3.BorderStyle = PdfBorderStyle.Beveled;
textBoxField3.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField3);
pdfDoc.Pages[0].Graphics.DrawString("Business Phone:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 123);
//Set position to draw form fields
bounds.Y = bounds.Y + 18;
//Create text box for Business phone.
PdfTextBoxField textBoxField4 = new PdfTextBoxField(pdfDoc.Pages[0], "Business");
textBoxField4.ToolTip = "Business phone";
textBoxField4.Font = font1;
textBoxField4.BorderColor = new PdfColor(Color.Gray);
textBoxField4.BorderStyle = PdfBorderStyle.Beveled;
textBoxField4.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField4);
pdfDoc.Pages[0].Graphics.DrawString("Which position are\nyou applying for?", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 143);
//Create combo box for Position.
#region Create ComboBox
//Set position to draw Combo Box
bounds.Y = bounds.Y + 24;
PdfComboBoxField comboBox = new PdfComboBoxField(pdfDoc.Pages[0], "JobTitle");
comboBox.Bounds = bounds;
comboBox.BorderWidth = 1;
comboBox.BorderColor = new PdfColor(Color.Gray);
comboBox.Font = pdfFont;
comboBox.ToolTip = "Job Title";
comboBox.Items.Add(new PdfListFieldItem("Development", "accounts"));
comboBox.Items.Add(new PdfListFieldItem("Support", "advertise"));
comboBox.Items.Add(new PdfListFieldItem("Documentation", "agri"));
pdfDoc.Form.Fields.Add(comboBox);
#endregion
pdfDoc.Pages[0].Graphics.DrawString("Highest qualification", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 217);
//Create Checkbox box.
#region Create CheckBox
pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 8);
//Set position to draw Checkbox
bounds.Y = 239;
bounds.X = 25;
bounds.Width = 10;
bounds.Height = 10;
// Create a Check Box
PdfCheckBoxField chb = new PdfCheckBoxField(pdfDoc.Pages[0], "Adegree");
chb.Font = pdfFont;
chb.ToolTip = "degree";
chb.Bounds = bounds;
chb.BorderColor = new PdfColor(Color.Gray);
bounds.X += chb.Bounds.Height + 10;
pdfDoc.Pages[0].Graphics.DrawString("Associate degree", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);
bounds.X += 90;
pdfDoc.Form.Fields.Add(chb);
//Create a Checkbox
chb = new PdfCheckBoxField(pdfDoc.Pages[0], "Bdegree");
chb.Font = pdfFont;
chb.Bounds = bounds;
chb.BorderColor = new PdfColor(Color.Gray);
bounds.X += chb.Bounds.Height + 10;
pdfDoc.Pages[0].Graphics.DrawString("Bachelor degree", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);
bounds.X += 90;
pdfDoc.Form.Fields.Add(chb);
//Create a Checkbox
chb = new PdfCheckBoxField(pdfDoc.Pages[0], "college");
chb.Font = pdfFont;
chb.ToolTip = "college";
chb.Bounds = bounds;
chb.BorderColor = new PdfColor(Color.Gray);
bounds.X += chb.Bounds.Height + 10;
pdfDoc.Pages[0].Graphics.DrawString("College", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);
bounds.Y += 20;
bounds.X = 25;
pdfDoc.Form.Fields.Add(chb);
//Create a Checkbox
chb = new PdfCheckBoxField(pdfDoc.Pages[0], "pg");
chb.Font = pdfFont;
chb.Bounds = bounds;
chb.BorderColor = new PdfColor(Color.Gray);
bounds.X += chb.Bounds.Height + 10;
pdfDoc.Pages[0].Graphics.DrawString("Post Graduate", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);
bounds.X += 90;
pdfDoc.Form.Fields.Add(chb);
//Create a Checkbox
chb = new PdfCheckBoxField(pdfDoc.Pages[0], "mba");
chb.Font = pdfFont;
chb.Bounds = bounds;
chb.BorderColor = new PdfColor(Color.Gray);
bounds.X += chb.Bounds.Height + 10;
pdfDoc.Pages[0].Graphics.DrawString("MBA", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);
pdfDoc.Form.Fields.Add(chb);
#endregion
# region Create Button
PdfButtonField submitButton = new PdfButtonField(pdfDoc.Pages[0], "Next");
submitButton.Bounds = new RectangleF(pdfDoc.Pages[0].GetClientSize().Width - 20, pdfDoc.Pages[0].GetClientSize().Height - 25, 20, 20);
submitButton.Font = pdfFont;
submitButton.ToolTip = "Next";
PdfPage page = pdfDoc.Pages.Add();
PdfDestination dest = new PdfDestination(page, new PointF(0, 100));
PdfGoToAction goToAction = new PdfGoToAction(page);
goToAction.Destination = dest;
submitButton.Actions.GotFocus = goToAction;
# endregion
# endregion
# region Second Page
//Create second page.
pdfDoc.Pages.Add();
//img = new PdfBitmap(file);
pdfDoc.Pages[1].Graphics.DrawImage(img, new PointF(0, 0), new SizeF(pageSize.Width, pageSize.Height));
pdfDoc.Pages[1].Graphics.DrawString("Current position", new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Bold), new PdfSolidBrush(new PdfColor(213, 123, 19)), 25, 40);
bounds.X = 25; bounds.Y = 65;
chb = new PdfCheckBoxField(pdfDoc.Pages[1], "Cemp");
chb.Font = pdfFont;
chb.Bounds = bounds;
chb.BorderWidth = 1;
chb.BorderColor = new PdfColor(Color.Gray);
bounds.X += chb.Bounds.Height + 10;
pdfDoc.Pages[1].Graphics.DrawString("I am not currently employed", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), bounds.X, bounds.Y);
bounds.X += 90;
pdfDoc.Form.Fields.Add(chb);
//Add fileds in second page
pdfDoc.Pages[1].Graphics.DrawString("Job Title", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 85);
bounds.X = 175;
bounds.Y = 85;
bounds.Width = 150;
bounds.Height = 16;
PdfTextBoxField textBoxField5 = new PdfTextBoxField(pdfDoc.Pages[1], "Jtitle");
textBoxField5.ToolTip = "Job title";
textBoxField5.Font = font1;
textBoxField5.BorderColor = new PdfColor(Color.Gray);
textBoxField5.BorderStyle = PdfBorderStyle.Beveled;
textBoxField5.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField5);
pdfDoc.Pages[1].Graphics.DrawString("Employer:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 103);
//Set position to draw form fields
bounds.Y = bounds.Y + 18;
PdfTextBoxField textBoxField6 = new PdfTextBoxField(pdfDoc.Pages[1], "Employer");
textBoxField6.ToolTip = "Employer";
textBoxField6.Font = font1;
textBoxField6.BorderColor = new PdfColor(Color.Gray);
textBoxField6.BorderStyle = PdfBorderStyle.Beveled;
textBoxField6.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField6);
pdfDoc.Pages[1].Graphics.DrawString("Reason for leaving:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 123);
//Set position to draw form fields
bounds.Y = bounds.Y + 18;
PdfTextBoxField textBoxField7 = new PdfTextBoxField(pdfDoc.Pages[1], "Reason");
textBoxField7.ToolTip = "Reason for leaving";
textBoxField7.Font = font1;
textBoxField7.BorderColor = new PdfColor(Color.Gray);
textBoxField7.BorderStyle = PdfBorderStyle.Beveled;
textBoxField7.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField7);
pdfDoc.Pages[1].Graphics.DrawString("Total Annual salary:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 143);
//Set position to draw form fields
bounds.Y = bounds.Y + 18;
PdfTextBoxField textBoxField8 = new PdfTextBoxField(pdfDoc.Pages[1], "Asalary");
textBoxField8.ToolTip = "Annual salary";
textBoxField8.Font = font1;
textBoxField8.BorderColor = new PdfColor(Color.Gray);
textBoxField8.BorderStyle = PdfBorderStyle.Beveled;
textBoxField8.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField8);
pdfDoc.Pages[1].Graphics.DrawString("Duties:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 168);
bounds.Y = bounds.Y + 50;
bounds.X = 25;
bounds.Height = bounds.Height * 4;
PdfTextBoxField textBoxField9 = new PdfTextBoxField(pdfDoc.Pages[1], "Duties");
//Set properties to the textbox
textBoxField9.ToolTip = "Duties";
textBoxField9.Font = font1;
textBoxField9.BorderColor = new PdfColor(Color.Gray);
textBoxField9.BorderStyle = PdfBorderStyle.Beveled;
textBoxField9.Bounds = bounds;
pdfDoc.Form.Fields.Add(textBoxField9);
pdfDoc.Pages[1].Graphics.DrawString("Employment type:", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 268);
#region Create ComboBox
//Set position to draw Combo Box
bounds.Y = bounds.Y + 74;
bounds.Height = 20;
bounds.X = 175;
//Create a combo Box
comboBox = new PdfComboBoxField(pdfDoc.Pages[1], "EmpType");
comboBox.Bounds = bounds;
comboBox.BorderColor = new PdfColor(Color.Gray);
comboBox.Font = pdfFont;
comboBox.ToolTip = "Employment type";
comboBox.Items.Add(new PdfListFieldItem("Full time", "ft"));
comboBox.Items.Add(new PdfListFieldItem("Part time", "pt"));
pdfDoc.Form.Fields.Add(comboBox);
#endregion
# endregion
# region Third Page
//Create submit button for next page navigation.
submitButton = new PdfButtonField(pdfDoc.Pages[1], "Apply");
submitButton.Bounds = new RectangleF(pdfDoc.Pages[1].GetClientSize().Width - 20, pdfDoc.Pages[1].GetClientSize().Height - 25, 20, 20);
submitButton.Font = pdfFont;
submitButton.BorderStyle = PdfBorderStyle.Beveled;
page = pdfDoc.Pages[2];
dest = new PdfDestination(page, new PointF(0, 100));
goToAction = new PdfGoToAction(page);
goToAction.Destination = dest;
submitButton.Actions.GotFocus = goToAction;
//img = new PdfBitmap(file);
pdfDoc.Pages[2].Graphics.DrawImage(img, 0, 0, pageSize.Width, pageSize.Height);
pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold);
pdfDoc.Pages[2].Graphics.DrawString("Thank You", pdfFont, new PdfSolidBrush(new PdfColor(213, 123, 19)), 25, 80);
pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 10, PdfFontStyle.Regular);
pdfDoc.Pages[2].Graphics.DrawString("Thanks for taking the time to complete this form.\nWe will be in contact with you shortly.", pdfFont, new PdfSolidBrush(new PdfColor(124, 143, 166)), 25, 110);
//Send email
PdfButtonField submitButton1 = new PdfButtonField(pdfDoc.Pages[2], "submitButton1");
submitButton1.Bounds = new RectangleF(25, 160, 100, 20);
submitButton1.Font = pdfFont;
submitButton1.Text = "Apply";
submitButton1.BorderStyle = PdfBorderStyle.Beveled;
submitButton1.BackColor = new PdfColor(181, 191, 203);
PdfJavaScriptAction javaAction = new PdfJavaScriptAction("address = app.response(\"Enter an e-mail address.\",\"SEND E-MAIL\",\"\");"
+ "if (address)" +
"{ " +
"cmdLine = \"mailto:\" + address;" +
"this.submitForm(cmdLine,true,false,\"Remarks\");" +
"}");
submitButton1.Actions.GotFocus = javaAction;
pdfDoc.Form.Fields.Add(submitButton1);
pdfDoc.Form.SetDefaultAppearance(false);
#endregion
MemoryStream stream = new MemoryStream();
//Save the PDF document
pdfDoc.Save(stream);
stream.Position = 0;
//Close the PDF document
pdfDoc.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = "JobApplication.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,108 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /Layers/
public ActionResult Layers()
{
return View();
}
[HttpPost]
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;
}
}
}

Просмотреть файл

@ -1,65 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /MergeDocuments/
public ActionResult MergeDocuments()
{
ViewData["Error"] = "";
return View();
}
[HttpPost]
public ActionResult MergeDocuments(string InsideBrowser)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Read the file
FileStream file1 = new FileStream(dataPath + "Essential_Pdf.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
FileStream file2 = new FileStream(dataPath + "Essential_XlsIO.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Load the documents as streams
PdfLoadedDocument doc1 = new PdfLoadedDocument(file1);
PdfLoadedDocument doc2 = new PdfLoadedDocument(file2);
object[] dobj = { doc1, doc2 };
PdfDocument doc = new PdfDocument();
PdfDocument.Merge(doc, dobj);
MemoryStream stream = new MemoryStream();
//Save the PDF document
doc.Save(stream);
stream.Position = 0;
//Close the PDF document
doc.Close(true);
doc1.Close(true);
doc2.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = "MergedPDF.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,112 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Interactive;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /NamedBookmark/
public ActionResult NamedDestination()
{
return View();
}
# region Methods
public PdfBookmark AddBookmark(PdfDocument document,PdfPage page, string title, PointF point, PdfFont font, PdfBrush brush)
{
PdfGraphics graphics = page.Graphics;
//Add bookmark in PDF document
PdfBookmark bookmarks = document.Bookmarks.Add(title);
//Draw the content in the PDF page
graphics.DrawString(title, font, brush, new PointF(point.X, point.Y));
//Adding bookmark with named destination
PdfNamedDestination namedDestination = new PdfNamedDestination(title);
namedDestination.Destination = new PdfDestination(page, new PointF(point.X, point.Y));
namedDestination.Destination.Mode = PdfDestinationMode.FitToPage;
document.NamedDestinationCollection.Add(namedDestination);
bookmarks.NamedDestination = namedDestination;
return bookmarks;
}
public PdfBookmark AddDocumentSection(PdfDocument document,PdfBookmark bookmark, PdfPage page, string title, PointF point, bool isSubSection, PdfFont font, PdfBrush brush)
{
PdfGraphics graphics = page.Graphics;
//Add bookmark in PDF document
PdfBookmark bookmarks = bookmark.Add(title);
//Draw the content in the PDF page
graphics.DrawString(title, font, brush, new PointF(point.X, point.Y));
//Adding bookmark with named destination
PdfNamedDestination namedDestination = new PdfNamedDestination(title);
namedDestination.Destination = new PdfDestination(page, new PointF(point.X, point.Y));
if (isSubSection == true)
{
namedDestination.Destination.Zoom = 2f;
}
else
{
namedDestination.Destination.Zoom = 1f;
}
document.NamedDestinationCollection.Add(namedDestination);
bookmarks.NamedDestination = namedDestination;
return bookmarks;
}
#endregion
[HttpPost]
public ActionResult NamedDestination(string InsideBrowser)
{
PdfDocument document = new PdfDocument();
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
PdfBrush brush = new PdfSolidBrush(Color.Black);
for (int i = 1; i <= 6; i++)
{
PdfPage pages = document.Pages.Add();
//Add bookmark in PDF document
PdfBookmark bookmark = AddBookmark(document,pages, "Chapter " + i, new PointF(10, 10),font, brush);
//Add sections to bookmark
PdfBookmark section1 = AddDocumentSection(document,bookmark, pages, "Section " + i + ".1", new PointF(30, 30), false, font, brush);
PdfBookmark section2 = AddDocumentSection(document,bookmark, pages, "Section " + i + ".2", new PointF(30, 400), false, font, brush);
//Add subsections to section
PdfBookmark subsection1 = AddDocumentSection(document,section1, pages, "Paragraph " + i + ".1.1", new PointF(50, 50), true, font, brush);
PdfBookmark subsection2 = AddDocumentSection(document,section1, pages, "Paragraph " + i + ".1.2", new PointF(50, 150), true, font, brush);
PdfBookmark subsection3 = AddDocumentSection(document,section1, pages, "Paragraph " + i + ".1.3", new PointF(50, 250), true, font, brush);
PdfBookmark subsection4 = AddDocumentSection(document,section2, pages, "Paragraph " + i + ".2.1", new PointF(50, 420), true, font, brush);
PdfBookmark subsection5 = AddDocumentSection(document,section2, pages, "Paragraph " + i + ".2.2", new PointF(50, 560), true, font, brush);
PdfBookmark subsection6 = AddDocumentSection(document,section2, pages, "Paragraph " + i + ".2.3", new PointF(50, 680), true, font, brush);
}
MemoryStream stream = new MemoryStream();
//Save the PDF document
document.Save(stream);
stream.Position = 0;
//Close the PDF document
document.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = "NamedDestination.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,65 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /OpenTypeFont/
public ActionResult OpenTypeFont()
{
return View();
}
[HttpPost]
public ActionResult OpenTypeFont(string InsideBrowser)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Create a new PDF document
PdfDocument document = new PdfDocument();
//Add a page
PdfPage page = document.Pages.Add();
//Create font
FileStream fontFileStream = new FileStream(dataPath + "NotoSerif-Black.otf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfFont font = new PdfTrueTypeFont(fontFileStream, 14);
//Text to draw
string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
//Create a brush
PdfBrush brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
PdfPen pen = new PdfPen(new PdfColor(0, 0, 0));
SizeF clipBounds = page.Graphics.ClientSize;
RectangleF rect = new RectangleF(0, 0, clipBounds.Width, clipBounds.Height);
//Draw text.
page.Graphics.DrawString(text, font, brush, rect);
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 = "OpenTypeFont.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,75 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /OverlayDocuments/
public ActionResult OverlayDocuments()
{
return View();
}
[HttpPost]
public ActionResult OverlayDocuments(string InsideBrowser)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
string dataPath1 = dataPath + "BorderTemplate.pdf";
string dataPath2 = dataPath + "SourceTemplate.pdf";
Stream stream1 = new FileStream(dataPath2, FileMode.Open, FileAccess.Read);
FileStream file = new FileStream(dataPath1, FileMode.Open, FileAccess.Read, FileShare.Read);
PdfLoadedDocument ldDoc1 = new PdfLoadedDocument(file);
PdfLoadedDocument ldDoc2 = new PdfLoadedDocument(stream1);
PdfDocument doc = new PdfDocument();
for (int i = 0, count = ldDoc2.Pages.Count; i < count; ++i)
{
PdfPage page = doc.Pages.Add();
PdfGraphics g = page.Graphics;
PdfPageBase lpage = ldDoc2.Pages[i];
PdfTemplate template = lpage.CreateTemplate();
g.DrawPdfTemplate(template, PointF.Empty, page.GetClientSize());
lpage = ldDoc1.Pages[0];
template = lpage.CreateTemplate();
g.DrawPdfTemplate(template, PointF.Empty, page.GetClientSize());
}
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 = "Overlay.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,143 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /PageSettings/
public ActionResult PageSettings()
{
return View();
}
[HttpPost]
public ActionResult PageSettings(string InsideBrowser)
{
// Create a new document class object.
PdfDocument doc = new PdfDocument();
PdfSection section;
PdfPage pdfPage;
// Create few sections with one page in each.
for (int i = 0; i < 4; ++i)
{
section = doc.Sections.Add();
//Create page label
PdfPageLabel label = new PdfPageLabel();
label.Prefix = "Sec" + i + "-";
section.PageLabel = label;
pdfPage = section.Pages.Add();
section.Pages[0].Graphics.SetTransparency(0.35f);
section.PageSettings.Transition.PageDuration = 1;
section.PageSettings.Transition.Duration = 1;
section.PageSettings.Transition.Style = PdfTransitionStyle.Box;
}
//Set page size
doc.PageSettings.Size = PdfPageSize.A6;
//Set viewer prefernce.
doc.ViewerPreferences.HideToolbar = true;
doc.ViewerPreferences.PageMode = PdfPageMode.FullScreen;
//Set page orientation
doc.PageSettings.Orientation = PdfPageOrientation.Landscape;
//Create a brush
PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
brush.Color = new PdfColor(Syncfusion.Drawing.Color.LightGreen);
//Create a Rectangle
PdfRectangle rect = new PdfRectangle(0, 0, 1000f, 1000f);
rect.Brush = brush;
PdfPen pen = new PdfPen(Syncfusion.Drawing.Color.Black);
pen.Width = 6f;
//Get the first page in first section
pdfPage = doc.Sections[0].Pages[0];
//Draw the rectangle
rect.Draw(pdfPage.Graphics);
//Draw a line
pdfPage.Graphics.DrawLine(pen, 0, 100, 300, 100);
// Add margins.
doc.PageSettings.SetMargins(0f);
//Get the first page in second section
pdfPage = doc.Sections[1].Pages[0];
doc.Sections[1].PageSettings.Rotate = PdfPageRotateAngle.RotateAngle90;
rect.Draw(pdfPage.Graphics);
pdfPage.Graphics.DrawLine(pen, 0, 100, 300, 100);
// Change the angle f the section. This should rotate the previous page.
doc.Sections[2].PageSettings.Rotate = PdfPageRotateAngle.RotateAngle180;
pdfPage = doc.Sections[2].Pages[0];
rect.Draw(pdfPage.Graphics);
pdfPage.Graphics.DrawLine(pen, 0, 100, 300, 100);
section = doc.Sections[3];
section.PageSettings.Orientation = PdfPageOrientation.Portrait;
pdfPage = section.Pages[0];
rect.Draw(pdfPage.Graphics);
pdfPage.Graphics.DrawLine(pen, 0, 100, 300, 100);
//Set the font
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 16f);
PdfSolidBrush fieldBrush = new PdfSolidBrush(Color.Black);
//Create page number field
PdfPageNumberField pageNumber = new PdfPageNumberField(font, fieldBrush);
//Create page count field
PdfPageCountField count = new PdfPageCountField(font, fieldBrush);
//Draw page template
PdfPageTemplateElement templateElement = new PdfPageTemplateElement(400, 400);
templateElement.Graphics.DrawString("Page :\tof", font, PdfBrushes.Black, new PointF(260, 200));
//Draw current page number
pageNumber.Draw(templateElement.Graphics, new PointF(306, 200));
//Draw number of pages
count.Draw(templateElement.Graphics, new PointF(345, 200));
doc.Template.Stamps.Add(templateElement);
templateElement.Background = 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 = "PageSettings.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,90 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Interactive;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /Portfolio/
public ActionResult Portfolio()
{
return View();
}
[HttpPost]
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;
}
}
}

Просмотреть файл

@ -1,74 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /RTLSupport/
public ActionResult RTLSupport()
{
return View();
}
[HttpPost]
public ActionResult RTLSupport(string InsideBrowser)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Create a new PDF document
PdfDocument document = new PdfDocument();
//Add a page
PdfPage page = document.Pages.Add();
//Create font
FileStream fontFileStream = new FileStream(dataPath + "arial.ttf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfFont font = new PdfTrueTypeFont(fontFileStream, 14);
//Read the text from text file
FileStream rtlText = new FileStream(dataPath + "arabic.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(rtlText, System.Text.Encoding.Unicode);
string text = reader.ReadToEnd();
reader.Dispose();
//Create a brush
PdfBrush brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
PdfPen pen = new PdfPen(new PdfColor(0, 0, 0));
SizeF clipBounds = page.Graphics.ClientSize;
RectangleF rect = new RectangleF(0, 0, clipBounds.Width, clipBounds.Height);
//Set the property for RTL text
PdfStringFormat format = new PdfStringFormat();
format.TextDirection = PdfTextDirection.RightToLeft;
format.Alignment = PdfTextAlignment.Right;
format.ParagraphIndent = 35f;
//Draw text.
page.Graphics.DrawString(text, font, brush, rect, format);
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 = "RTLText.pdf";
return fileStreamResult;
}
}
}

Просмотреть файл

@ -1,84 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /RearrangePages/
public ActionResult RearrangePages()
{
return View();
}
[HttpPost]
public ActionResult RearrangePages(string Browser, string submit1)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
if (submit1 == "View Template")
{
Stream file2 = new FileStream(dataPath + "SyncfusionBrochure.pdf", FileMode.Open, FileAccess.Read, FileShare.Read);
//Load the template document
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(file2);
//Save the PDF to the MemoryStream
MemoryStream ms = new MemoryStream();
loadedDocument.Save(ms);
//If the position is not set to '0' then the PDF will be empty.
ms.Position = 0;
//Close the PDF document.
loadedDocument.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
fileStreamResult.FileDownloadName = "InputTemplate.pdf";
return fileStreamResult;
}
else
{
//Read the file
FileStream file = new FileStream(dataPath + "SyncfusionBrochure.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Load the input PDF document
PdfLoadedDocument ldoc = new PdfLoadedDocument(file);
//Rearrange the page by index
ldoc.Pages.ReArrange(new int[] { 2, 0, 1 });
//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;
//Close the PDF document.
ldoc.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
fileStreamResult.FileDownloadName = "RearrangedPages.pdf";
return fileStreamResult;
}
}
}
}

Просмотреть файл

@ -1,69 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Parsing;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /SplitPDF/
public ActionResult SplitPDF()
{
return View();
}
[HttpPost]
public ActionResult SplitPDF(string Browser, string pageIndex, IFormFile file)
{
if (file != null && file.Length > 0)
{
int splitAtPage = int.Parse(pageIndex.ToString());
PdfLoadedDocument ldoc = new PdfLoadedDocument(file.OpenReadStream());
if (splitAtPage <= ldoc.Pages.Count&&splitAtPage!=0)
{
//Create PDF documents.
PdfDocument doc1 = new PdfDocument();
//Import PDF document into splitAtPage index.
doc1.ImportPage(ldoc, splitAtPage-1);
//Save the PDF to the MemoryStream
MemoryStream ms = new MemoryStream();
doc1.Save(ms);
//If the position is not set to '0' then the PDF will be empty.
ms.Position = 0;
//Close the PDF document.
doc1.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
fileStreamResult.FileDownloadName = "Split.pdf";
return fileStreamResult;
}
else
{
ViewBag.lab = "Invalid Page no";
}
}
return View();
}
}
}

Просмотреть файл

@ -1,300 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Tables;
using Syncfusion.Pdf.Grid;
using Syncfusion.Pdf.Interactive;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using System.Linq;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /TableFeatures/
#region fields
PdfPen borderPen;
PdfPen transparentPen;
float cellSpacing = 7f;
float margin = 40f;
PdfFont smallFont;
PdfLightTable pdfLightTable = null;
#endregion
public ActionResult TableFeatures()
{
return View();
}
[HttpPost]
public ActionResult TableFeatures(string InsideBrowser)
{
#region Field Definitions
//Load product data.
IEnumerable<Products> products = DataProvider.GetProducts(_hostingEnvironment.WebRootPath);
//Create a new PDF standard font
PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 8f);
smallFont = new PdfStandardFont(font, 5f);
PdfFont bigFont = new PdfStandardFont(font, 16f);
//Create a new PDF solid brush
PdfBrush orangeBrush = new PdfSolidBrush(new PdfColor(247, 148, 29));
PdfBrush grayBrush = new PdfSolidBrush(new PdfColor(170, 171, 171));
//Create a new PDF pen
borderPen = new PdfPen(PdfBrushes.DarkGray, .3f);
borderPen.LineCap = PdfLineCap.Square;
transparentPen = new PdfPen(PdfBrushes.Transparent, .3f);
transparentPen.LineCap = PdfLineCap.Square;
# endregion
//Create a new PDF document
PdfDocument document = new PdfDocument();
//Set the margins
document.PageSettings.Margins.All = 0;
# region Footer
//Create a new footer template
PdfPageTemplateElement footer = new PdfPageTemplateElement(new RectangleF(new PointF(0, document.PageSettings.Height - 40), new SizeF(document.PageSettings.Width, 40)));
footer.Graphics.DrawRectangle(new PdfSolidBrush(new PdfColor(77, 77, 77)), footer.Bounds);
footer.Graphics.DrawString("http://www.syncfusion.com", font, grayBrush, new PointF(footer.Width - (footer.Width / 4), 15));
footer.Graphics.DrawString("Copyright © 2001 - 2017 Syncfusion Inc.", font, grayBrush, new PointF(0, 15));
//Add the footer template at the bottom of the page
document.Template.Bottom = footer;
# endregion
//Add a new PDF page
PdfPage page = document.Pages.Add();
page.Graphics.DrawRectangle(orangeBrush, new RectangleF(PointF.Empty, new SizeF(page.Graphics.ClientSize.Width, margin)));
//Draw the text to the PDF page
page.Graphics.DrawString("Essential Studio File Formats Edition", bigFont, PdfBrushes.White, new PointF(10, 10));
# region PdfLightTable
//Create a PDF light table
pdfLightTable = new PdfLightTable();
pdfLightTable.DataSource = products;
pdfLightTable.Style.DefaultStyle.BorderPen = transparentPen;
for (int i = 0; i < pdfLightTable.Columns.Count; i++)
{
if (i % 2 == 0)
pdfLightTable.Columns[i].Width = 16.5f;
}
pdfLightTable.Style.CellSpacing = cellSpacing;
pdfLightTable.BeginRowLayout += new BeginRowLayoutEventHandler(pdfLightTable_BeginRowLayout);
pdfLightTable.BeginCellLayout += new BeginCellLayoutEventHandler(pdfLightTable_BeginCellLayout);
pdfLightTable.Style.DefaultStyle.Font = font;
PdfLayoutResult result = pdfLightTable.Draw(page, new RectangleF(new PointF(margin, 70), new SizeF(page.Graphics.ClientSize.Width - (2 * margin), page.Graphics.ClientSize.Height - margin)));
# endregion
page.Graphics.DrawString("What You Get with Syncfusion", bigFont, orangeBrush, new PointF(margin, result.Bounds.Bottom + 50));
# region PdfGrid
//Create a new PDF grid
PdfGrid pdfGrid = new PdfGrid();
IEnumerable<Report> report = DataProvider.GetReport(_hostingEnvironment.WebRootPath);
pdfGrid.DataSource = report;
pdfGrid.Headers.Clear();
pdfGrid.Columns[0].Width = 80;
pdfGrid.Style.Font = font;
pdfGrid.Style.CellSpacing = 15f;
for (int i = 0; i < pdfGrid.Rows.Count; i++)
{
if (i % 2 == 0)
{
PdfGridCell cell = pdfGrid.Rows[i].Cells[0];
cell.RowSpan = 2;
cell.Value = "";
cell = pdfGrid.Rows[i].Cells[1];
cell.Style.Font = bigFont;
}
for (int j = 0; j < pdfGrid.Columns.Count; j++)
{
pdfGrid.Rows[i].Cells[j].Style.Borders.All = transparentPen;
}
}
//Create a PDF grid layout format
PdfGridLayoutFormat gridLayoutFormat = new PdfGridLayoutFormat();
//Set pagination
gridLayoutFormat.Layout = PdfLayoutType.Paginate;
//Draw the grid to the PDF document
pdfGrid.Draw(page, new RectangleF(new PointF(margin, result.Bounds.Bottom + 75), new SizeF(page.Graphics.ClientSize.Width - (2 * margin), page.Graphics.ClientSize.Height - margin)), gridLayoutFormat);
#endregion
MemoryStream stream = new MemoryStream();
//Save the PDF document
document.Save(stream);
//Close the PDF document
document.Close(true);
stream.Position = 0;
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = "TableFeatures.pdf";
return fileStreamResult;
}
#region PdfLightTable Events
void pdfLightTable_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
{
if (args.RowIndex % 2 == 0)
args.MinimalHeight = 20;
else
args.MinimalHeight = 30;
}
void pdfLightTable_BeginCellLayout(object sender, BeginCellLayoutEventArgs args)
{
if (args.RowIndex > -1 && args.CellIndex > -1)
{
float x = args.Bounds.X;
float y = args.Bounds.Y;
float width = args.Bounds.Right;
float height = args.Bounds.Bottom;
if (args.Value == "dummy")
{
args.Skip = true;
return;
}
if (args.CellIndex % 2 == 0 && !string.IsNullOrEmpty(args.Value))
{
args.Skip = true;
}
if (args.Value.Contains("http"))
{
args.Skip = true;
// Create the Text Web Link
PdfTextWebLink textLink = new PdfTextWebLink();
textLink.Url = args.Value;
textLink.Text = "Know more...";
textLink.Brush = PdfBrushes.Black;
textLink.Font = smallFont;
textLink.DrawTextWebLink(args.Graphics, new PointF(args.Bounds.X + 2 * args.Bounds.Width / 3, args.Bounds.Y));
}
# region Draw manual borders
if (args.RowIndex % 3 == 0)//top
{
if (args.CellIndex % 2 == 0)
width += cellSpacing;
args.Graphics.DrawLine(borderPen, new PointF(x, y), new PointF(width, y));
}
else if (args.RowIndex % 3 == 2)//bottom
{
if (args.CellIndex % 2 == 0)
width += cellSpacing;
args.Graphics.DrawLine(borderPen, new PointF(x, height), new PointF(width, height));
}
if (args.CellIndex % 2 == 0)//left
{
if (args.RowIndex % 3 != 2)
height += cellSpacing;
args.Graphics.DrawLine(borderPen, new PointF(x, y), new PointF(x, height));
}
else if (args.CellIndex % 2 != 0)//right
{
if (args.RowIndex % 3 != 2)
height += cellSpacing;
args.Graphics.DrawLine(borderPen, new PointF(width, y), new PointF(width, height));
}
# endregion
}
}
# endregion
internal sealed class DataProvider
{
public static IEnumerable<Products> GetProducts(string webRootPath)
{
string dataPath = webRootPath + @"/PDF/";
//Read the file
FileStream xmlStream = new FileStream(dataPath + "Products.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader reader = new StreamReader(xmlStream, true))
{
return XElement.Parse(reader.ReadToEnd())
.Elements("Products")
.Select(c => new Products
{
Image1 = c.Element("Image1").Value,
Description1 = c.Element("Description1").Value,
Image2 = c.Element("Image2").Value,
Description2 = c.Element("Description2").Value,
Image3 = (c.Element("Image3") != null) ? c.Element("Image3").Value : "dummy",
Description3 = (c.Element("Description3") != null) ? c.Element("Description3").Value : "dummy",
});
}
}
public static IEnumerable<Report> GetReport(string webRootPath)
{
string dataPath = webRootPath + @"/PDF/";
//Read the file
FileStream xmlStream = new FileStream(dataPath + "Report.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader reader = new StreamReader(xmlStream, true))
{
return XElement.Parse(reader.ReadToEnd())
.Elements("Report")
.Select(c => new Report
{
Image = c.Element("Image").Value,
Description = c.Element("Description").Value,
});
}
}
}
#region Products
public class Products
{
public string Image1 { get; set; }
public string Description1 { get; set; }
public string Image2 { get; set; }
public string Description2 { get; set; }
public string Image3 { get; set; }
public string Description3 { get; set; }
}
#endregion
#region Report
public class Report
{
public string Image { get; set; }
public string Description { get; set; }
}
#endregion
}
}

Просмотреть файл

@ -1,122 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /TextFlow/
public ActionResult TextFlow()
{
return View();
}
[HttpPost]
public ActionResult TextFlow(string InsideBrowser)
{
//Create a new PDF document.
PdfDocument doc = new PdfDocument();
//Set compression level
doc.Compression = PdfCompressionLevel.None;
//Add a page to the document.
PdfPage page = doc.Pages.Add();
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Read the file
FileStream file = new FileStream(dataPath + "Manual.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Read the text from the text file
StreamReader reader = new StreamReader(file, System.Text.Encoding.ASCII);
string text = reader.ReadToEnd();
reader.Dispose();
//Set the font
PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman,12);
//Set the formats for the text
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Justify;
format.LineAlignment = PdfVerticalAlignment.Top;
format.ParagraphIndent = 15f;
//Create a text element
PdfTextElement element = new PdfTextElement(text, font);
element.Brush = new PdfSolidBrush(Color.Black);
element.StringFormat = format;
element.Font = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
//Set the properties to paginate the text.
PdfLayoutFormat layoutFormat = new PdfLayoutFormat();
layoutFormat.Break = PdfLayoutBreakType.FitPage;
layoutFormat.Layout = PdfLayoutType.Paginate;
RectangleF bounds = new RectangleF(PointF.Empty, page.Graphics.ClientSize);
//Raise the events to draw the graphic elements for each page.
element.BeginPageLayout += new BeginPageLayoutEventHandler(BeginPageLayout);
element.EndPageLayout += new EndPageLayoutEventHandler(EndPageLayout);
//Draw the text element with the properties and formats set.
PdfTextLayoutResult result = element.Draw(page, bounds, layoutFormat);
//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 = "TextFlow.pdf";
return fileStreamResult;
}
private void BeginPageLayout(object sender, BeginPageLayoutEventArgs e)
{
int index = e.Page.Section.Pages.IndexOf(e.Page);
float offset = 50;
PdfSolidBrush brush = new PdfSolidBrush(Color.LightBlue);
if (index % 2 == 0)
{
RectangleF bounds = e.Bounds;
e.Page.Graphics.DrawEllipse(brush, bounds.Width / 2 - offset, bounds.Height / 2 - offset, 2 * offset, 2 * offset);
}
else
{
RectangleF bounds = e.Bounds;
e.Page.Graphics.DrawRectangle(brush, bounds.Width / 2 - offset, bounds.Height / 2 - offset, 2 * offset, 2 * offset);
}
}
private void EndPageLayout(object sender, EndPageLayoutEventArgs e)
{
EndTextPageLayoutEventArgs args = (EndTextPageLayoutEventArgs)e;
PdfPage page = args.Result.Page;
PdfPen pen = PdfPens.Black;
page.Graphics.DrawRectangle(pen, new RectangleF(PointF.Empty, page.Graphics.ClientSize));
}
}
}

Просмотреть файл

@ -1,69 +0,0 @@
#region Copyright Syncfusion Inc. 2001 - 2020
// Copyright Syncfusion Inc. 2001 - 2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
using Syncfusion.DocIORenderer;
using Syncfusion.Pdf;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
public IActionResult WordToPDF(string button)
{
if (button == null)
return View();
if (Request.Form.Files != null)
{
// Gets the extension from file.
string extension = Path.GetExtension(Request.Form.Files[0].FileName).ToLower();
// Compares extension with supported extensions.
if (extension == ".doc" || extension == ".docx" || extension == ".dot" || extension == ".dotx" || extension == ".dotm" || extension == ".docm"
|| extension == ".xml" || extension == ".rtf")
{
Stream stream = new FileStream(Path.GetTempFileName(), FileMode.Create);
Request.Form.Files[0].CopyToAsync(stream);
try
{
// Loads document from stream.
WordDocument document = new WordDocument(stream, FormatType.Automatic);
// Creates a new instance of DocIORenderer class.
DocIORenderer render = new DocIORenderer();
// Converts Word document into PDF document.
PdfDocument pdf = render.ConvertToPDF(document);
MemoryStream memoryStream = new MemoryStream();
// Save the PDF document.
pdf.Save(memoryStream);
render.Dispose();
pdf.Close();
document.Close();
memoryStream.Position = 0;
return File(memoryStream, "application/pdf", "WordToPDF.pdf");
}
catch (Exception ex)
{
ViewBag.Message = string.Format("The input document could not be processed completely, Could you please email the document to support@syncfusion.com for troubleshooting.");
}
}
else
{
ViewBag.Message = string.Format("Please choose Word format document to convert to PDF");
}
}
else
{
ViewBag.Message = string.Format("Browse a Word document and then click the button to convert as a PDF document");
}
return View();
}
}
}

Просмотреть файл

@ -1,89 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Drawing;
using System.IO;
using Syncfusion.Pdf.Xfa;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /XFAFormCreation/
public ActionResult XFAFormFilling()
{
return View();
}
[HttpPost]
public ActionResult XFAFormFilling(string submit1, string submit, string InsideBrowser)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
if (submit1 == "View Template")
{
Stream file2 = new FileStream(dataPath + "xfaTemplate.pdf", FileMode.Open, FileAccess.Read, FileShare.Read);
FileStreamResult fileStreamResult = new FileStreamResult(file2, "application/pdf");
fileStreamResult.FileDownloadName = "XFAFormTemplate.pdf";
return fileStreamResult;
}
else
{
//Read the file
FileStream file1 = new FileStream(dataPath + "xfaTemplate.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Load the existing XFA document.
PdfLoadedXfaDocument ldoc = new PdfLoadedXfaDocument(file1);
//Loaded the existing XFA form.
PdfLoadedXfaForm lform = ldoc.XfaForm;
//Fill the XFA form fields.
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["title[0]"] as PdfLoadedXfaComboBoxField).SelectedIndex = 0;
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["fn[0]"] as PdfLoadedXfaTextBoxField).Text = "Simons";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["ln[0]"] as PdfLoadedXfaTextBoxField).Text = "Bistro";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["dob[0]"] as PdfLoadedXfaDateTimeField).Value = new System.DateTime(1989, 5, 21);
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["company[0]"] as PdfLoadedXfaTextBoxField).Text = "XYZ Pvt Ltd";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["jt[0]"] as PdfLoadedXfaTextBoxField).Text = "Developer";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["jd[0]"] as PdfLoadedXfaTextBoxField).Text = "Develop and maintain components and applications for the web, desktop and mobile platforms. \nWork with some of the best UI/UX designers in the world to craft Stunning user interfaces. \nRegular appraisals to ensure quick growth if you deliver on the job.";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["st[0]"] as PdfLoadedXfaTextBoxField).Text = "Vinbaeltet 34";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["ad1[0]"] as PdfLoadedXfaTextBoxField).Text = "Kobenhaven";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["city[0]"] as PdfLoadedXfaTextBoxField).Text = "Denmark";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["state[0]"] as PdfLoadedXfaComboBoxField).SelectedIndex = 1;
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["zip[0]"] as PdfLoadedXfaNumericField).NumericValue = 24534;
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["country[0]"] as PdfLoadedXfaTextBoxField).Text = "US";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["em[0]"] as PdfLoadedXfaTextBoxField).Text = "simonsbistro@outlook.com";
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["phone[0]"] as PdfLoadedXfaNumericField).NumericValue = 8765456789;
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["sdn[0]"] as PdfLoadedXfaListBoxField).SelectedItems = new string[] { "Vegan", "Diary Free" };
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["san[0]"] as PdfLoadedXfaListBoxField).SelectedIndex = 0;
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["email[0]"] as PdfLoadedXfaCheckBoxField).IsChecked = true;
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["phone[1]"] as PdfLoadedXfaCheckBoxField).IsChecked = true;
(((lform.Fields["subform1[0]"] as PdfLoadedXfaForm).Fields["subform3[0]"] as PdfLoadedXfaForm).Fields["group1[0]"] as PdfLoadedXfaRadioButtonGroup).Fields[1].IsChecked = true;
//Saving 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;
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
fileStreamResult.FileDownloadName = "Sample.pdf";
return fileStreamResult;
}
}
}
}

Просмотреть файл

@ -1,382 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Drawing;
using System.IO;
using Syncfusion.Pdf.Xfa;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /XFAFormCreation/
public ActionResult XFAFormCreation()
{
return View();
}
[HttpPost]
public ActionResult XFAFormCreation(string InsideBrowser)
{
PdfXfaDocument doc = new PdfXfaDocument();
PdfXfaPage page = doc.Pages.Add();
PdfFont font0 = new PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold);
PdfFont font1 = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Italic);
PdfFont font2 = new PdfStandardFont(PdfFontFamily.TimesRoman, 9, PdfFontStyle.Italic);
PdfFont font3 = new PdfStandardFont(PdfFontFamily.TimesRoman, 11, PdfFontStyle.Regular);
PdfXfaForm mainForm = new PdfXfaForm(PdfXfaFlowDirection.Vertical, page.GetClientSize().Width);
PdfXfaForm subForm1 = new PdfXfaForm(PdfXfaFlowDirection.Horizontal, page.GetClientSize().Width - 40);
PdfXfaForm headerForm = new PdfXfaForm(page.GetClientSize().Width);
headerForm.Width = page.GetClientSize().Width;
headerForm.Border = new PdfXfaBorder() { Width = 0 };
headerForm.Border.FillColor = new PdfXfaSolidBrush(new PdfColor(Color.OrangeRed));
PdfXfaTextElement cr = new PdfXfaTextElement("CONFERENCE REGISTRATION") { HorizontalAlignment = PdfXfaHorizontalAlignment.Center, VerticalAlignment = PdfXfaVerticalAlignment.Middle, Width = page.GetClientSize().Width, Height = 60 };
cr.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 26, PdfFontStyle.Bold);
cr.ForeColor = new PdfColor(Color.White);
headerForm.Fields.Add(cr);
mainForm.Fields.Add(headerForm);
subForm1.Margins.Left = 40;
subForm1.Margins.Bottom = 40;
PdfXfaTextElement name = new PdfXfaTextElement("Name", font0);
name.Width = 500;
name.Height = 70;
name.VerticalAlignment = PdfXfaVerticalAlignment.Bottom;
name.Margins.Top = 20;
subForm1.Fields.Add(name);
PdfXfaLine line1 = new PdfXfaLine(new PointF(0, 0), new PointF(450, 0), 1.2f);
line1.Color = new PdfColor(Color.LightGray);
subForm1.Fields.Add(line1);
PdfXfaRectangleField rectangle = new PdfXfaRectangleField("rect", new SizeF(60, 1.2f)) { Visibility = PdfXfaVisibility.Invisible };
subForm1.Fields.Add(rectangle);
PdfXfaCaption caption1 = new PdfXfaCaption();
caption1.VerticalAlignment = PdfXfaVerticalAlignment.Bottom;
caption1.HorizontalAlignment = PdfXfaHorizontalAlignment.Center;
caption1.Position = PdfXfaPosition.Bottom;
caption1.Font = font2;
caption1.Width = caption1.Font.MeasureString("first Name").Height + 3;
PdfXfaComboBoxField title = new PdfXfaComboBoxField("title", new SizeF(40, 40)) { Width = 34, Height = 40 };
title.Caption = caption1.Clone() as PdfXfaCaption;
title.Caption.Text = "Title";
title.Border.Style = PdfXfaBorderStyle.Lowered;
title.HorizontalAlignment = PdfXfaHorizontalAlignment.JustifyAll;
title.Items.Add("Mr");
title.Items.Add("Mrs");
title.Items.Add("Miss");
subForm1.Fields.Add(title);
title.Margins.Top = 7;
PdfXfaTextBoxField fn = new PdfXfaTextBoxField("fn", new SizeF(207, 40)) { Width = 208, Height = 40 };
fn.Caption = caption1.Clone() as PdfXfaCaption;
fn.Caption.Text = "First Name";
fn.Margins.Left = 5;
fn.Margins.Top = 7;
fn.Border.Style = PdfXfaBorderStyle.Lowered;
subForm1.Fields.Add(fn);
PdfXfaTextBoxField ln = new PdfXfaTextBoxField("ln", new SizeF(214, 50)) { Width = 208, Height = 40 };
ln.Caption = caption1.Clone() as PdfXfaCaption;
ln.Caption.Text = "Last Name";
ln.Border.Style = PdfXfaBorderStyle.Lowered;
ln.Margins.Left = 5;
ln.Margins.Top = 7;
subForm1.Fields.Add(ln);
caption1.HorizontalAlignment = PdfXfaHorizontalAlignment.Left;
caption1.VerticalAlignment = PdfXfaVerticalAlignment.Top;
caption1.Position = PdfXfaPosition.Top;
caption1.Font = font3;
PdfXfaDateTimeField dob = new PdfXfaDateTimeField("dob", new SizeF(450, 40));
dob.Caption = caption1.Clone() as PdfXfaCaption;
dob.Caption.Text = "Date of Birth";
dob.Margins.Top = 7;
dob.HorizontalAlignment = PdfXfaHorizontalAlignment.Left;
dob.Border.Style = PdfXfaBorderStyle.Lowered;
subForm1.Fields.Add(dob);
PdfXfaTextBoxField company = new PdfXfaTextBoxField("company", new SizeF(450, 40)) { Width = 450, Height = 40 };
company.Caption = caption1.Clone() as PdfXfaCaption;
company.Caption.Text = "Company";
company.Margins.Top = 7;
company.Border.Style = PdfXfaBorderStyle.Lowered;
subForm1.Fields.Add(company);
PdfXfaTextBoxField jt = new PdfXfaTextBoxField("jt", new SizeF(500, 50)) { Width = 450, Height = 40 };
jt.Caption = caption1.Clone() as PdfXfaCaption;
jt.Caption.Text = "Job Title";
jt.Border.Style = PdfXfaBorderStyle.Lowered;
jt.Margins.Top = 7;
subForm1.Fields.Add(jt);
PdfXfaTextBoxField jd = new PdfXfaTextBoxField("jd", new SizeF(500, 120)) { Width = 450 };
jd.Caption = caption1.Clone() as PdfXfaCaption;
jd.Caption.Text = "Job Description";
jd.Type = PdfXfaTextBoxType.Multiline;
jd.Border.Style = PdfXfaBorderStyle.Lowered;
jd.Margins.Top = 7;
subForm1.Fields.Add(jd);
PdfXfaTextElement address = new PdfXfaTextElement("Address", font0);
address.Width = 500;
address.Height = 40;
address.VerticalAlignment = PdfXfaVerticalAlignment.Bottom;
address.Margins.Top = 10;
subForm1.Fields.Add(address);
subForm1.Fields.Add(line1);
caption1.VerticalAlignment = PdfXfaVerticalAlignment.Bottom;
caption1.Position = PdfXfaPosition.Bottom;
caption1.Font = font2;
PdfXfaTextBoxField st = new PdfXfaTextBoxField("st", new SizeF(450, 30)) { Width = 450, Height = 40 };
st.Caption = caption1.Clone() as PdfXfaCaption;
st.Caption.Text = "Street Address";
st.Border.Style = PdfXfaBorderStyle.Lowered;
st.Margins.Top = 7;
subForm1.Fields.Add(st);
PdfXfaTextBoxField addLine1 = new PdfXfaTextBoxField("ad1", new SizeF(500, 30)) { Width = 450, Height = 40 };
addLine1.Caption = caption1.Clone() as PdfXfaCaption;
addLine1.Caption.Text = "Address Line1";
addLine1.Border.Style = PdfXfaBorderStyle.Lowered;
addLine1.Margins.Top = 7;
subForm1.Fields.Add(addLine1);
PdfXfaTextBoxField city = new PdfXfaTextBoxField("city", new SizeF(280, 30)) { Width = 220, Height = 40 };
city.Caption = caption1.Clone() as PdfXfaCaption;
city.Caption.Text = "City";
city.Border.Style = PdfXfaBorderStyle.Lowered;
city.Margins.Top = 7;
subForm1.Fields.Add(city);
PdfXfaComboBoxField state = new PdfXfaComboBoxField("state", new SizeF(230, 40));
state.Items.Add("Colorado");
state.Items.Add("Florida");
state.Items.Add("Georgia");
state.Items.Add("Hawaii");
state.Items.Add("Nevada");
state.Items.Add("New Mexico");
state.Items.Add("New York");
state.Items.Add("North Carolina");
state.Items.Add("Oregon");
state.Items.Add("Texas");
state.Caption = caption1.Clone() as PdfXfaCaption;
state.Caption.Text = "State";
state.Border.Style = PdfXfaBorderStyle.Lowered;
state.Margins.Left = 5;
state.Margins.Top = 7;
subForm1.Fields.Add(state);
PdfXfaNumericField zip = new PdfXfaNumericField("zip", new SizeF(220, 40));
zip.Caption = caption1.Clone() as PdfXfaCaption;
zip.CombLength = 5;
zip.Caption.Text = "Postal / Zip Code";
zip.PatternString = "zzzz9";
zip.FieldType = PdfXfaNumericType.Integer;
zip.Border.Style = PdfXfaBorderStyle.Lowered;
zip.Margins.Top = 7;
subForm1.Fields.Add(zip);
PdfXfaTextBoxField country = new PdfXfaTextBoxField("country", new SizeF(500, 30)) { Width = 230, Height = 40 };
country.Caption = caption1.Clone() as PdfXfaCaption;
country.Caption.Text = "Country";
country.Border.Style = PdfXfaBorderStyle.Lowered;
country.Margins.Left = 5;
country.Margins.Top = 7;
subForm1.Fields.Add(country);
PdfXfaTextBoxField email = new PdfXfaTextBoxField("em", new SizeF(500, 30)) { Width = 220, Height = 40 };
email.Caption = caption1.Clone() as PdfXfaCaption;
email.Caption.Text = "Email";
email.Margins.Top = 7;
email.Border.Style = PdfXfaBorderStyle.Lowered;
subForm1.Fields.Add(email);
PdfXfaNumericField phone = new PdfXfaNumericField("phone", new SizeF(230, 40));
phone.Caption = caption1.Clone() as PdfXfaCaption;
phone.Caption.Text = "Phone Number";
phone.FieldType = PdfXfaNumericType.Decimal;
phone.Margins.Left = 5;
phone.PatternString = "zzzzzzzzz9";
phone.Margins.Top = 7;
phone.Border.Style = PdfXfaBorderStyle.Lowered;
subForm1.Fields.Add(phone);
PdfXfaTextElement specialDN = new PdfXfaTextElement("Special Dietary Needs");
specialDN.Font = font0;
specialDN.Margins.Top = 25;
specialDN.Height = 42;
specialDN.Width = 450;
subForm1.Fields.Add(specialDN);
subForm1.Fields.Add(line1);
PdfXfaListBoxField sdn = new PdfXfaListBoxField("sdn", new SizeF(450, 80));
sdn.Items.Add("Vegan");
sdn.Items.Add("Gluten Free");
sdn.Items.Add("Nut Free");
sdn.Items.Add("Diary Free");
sdn.Items.Add("Vegetables");
sdn.SelectionMode = PdfXfaSelectionMode.Multiple;
sdn.HorizontalAlignment = PdfXfaHorizontalAlignment.Left;
sdn.Border.Style = PdfXfaBorderStyle.Lowered;
sdn.Margins.Top = 7;
subForm1.Fields.Add(sdn);
PdfXfaTextElement specialAN = new PdfXfaTextElement("Special Assistance Needs");
specialAN.Font = font0;
specialAN.Margins.Top = 25;
specialAN.Height = 42;
specialAN.Width = 450;
subForm1.Fields.Add(specialAN);
subForm1.Fields.Add(line1);
PdfXfaListBoxField san = new PdfXfaListBoxField("san", new SizeF(450, 40));
san.Items.Add("Wheel chair");
san.Items.Add("Ambulatory lift services");
san.HorizontalAlignment = PdfXfaHorizontalAlignment.Left;
san.Margins.Top = 7;
san.Border.Style = PdfXfaBorderStyle.Lowered;
subForm1.Fields.Add(san);
PdfXfaTextElement pcm = new PdfXfaTextElement("Prefered Contact Method");
pcm.Font = font0;
pcm.Margins.Top = 25;
pcm.Height = 42;
pcm.Width = 500;
subForm1.Fields.Add(pcm);
subForm1.Fields.Add(line1);
PdfXfaCaption caption = new PdfXfaCaption();
caption.Font = font1;
caption.Width = 370;
caption.VerticalAlignment = PdfXfaVerticalAlignment.Middle;
caption.Position = PdfXfaPosition.Right;
PdfXfaCheckBoxField c_email = new PdfXfaCheckBoxField("email", new SizeF(400, 22));
c_email.HorizontalAlignment = PdfXfaHorizontalAlignment.Left;
c_email.Caption = caption.Clone() as PdfXfaCaption;
c_email.Caption.Text = "E-Mail";
c_email.CheckedStyle = PdfXfaCheckedStyle.Check;
c_email.Border.Style = PdfXfaBorderStyle.Lowered;
c_email.Margins.Top = 7;
subForm1.Fields.Add(c_email);
PdfXfaCheckBoxField c_phone = new PdfXfaCheckBoxField("phone", new SizeF(400, 20));
c_phone.HorizontalAlignment = PdfXfaHorizontalAlignment.Left;
c_phone.Caption = caption.Clone() as PdfXfaCaption;
c_phone.Caption.Text = "Phone";
c_phone.Margins.Top = 7;
c_phone.Border.Style = PdfXfaBorderStyle.Lowered;
c_phone.CheckedStyle = PdfXfaCheckedStyle.Check;
subForm1.Fields.Add(c_phone);
PdfXfaCheckBoxField c_mail = new PdfXfaCheckBoxField("mail", new SizeF(400, 20));
c_mail.HorizontalAlignment = PdfXfaHorizontalAlignment.Left;
c_mail.Caption = caption.Clone() as PdfXfaCaption;
c_mail.Caption.Text = "Mail";
c_mail.Border.Style = PdfXfaBorderStyle.Lowered;
c_mail.Margins.Top = 7;
c_mail.CheckedStyle = PdfXfaCheckedStyle.Check;
subForm1.Fields.Add(c_mail);
PdfXfaCheckBoxField c_nocontact = new PdfXfaCheckBoxField("nc", new SizeF(400, 20));
c_nocontact.HorizontalAlignment = PdfXfaHorizontalAlignment.Left;
c_nocontact.Caption = caption.Clone() as PdfXfaCaption;
c_nocontact.Caption.Text = "No Contact";
c_nocontact.Margins.Top = 5;
c_nocontact.Border.Style = PdfXfaBorderStyle.Lowered;
c_nocontact.CheckedStyle = PdfXfaCheckedStyle.Check;
subForm1.Fields.Add(c_nocontact);
PdfXfaTextElement MS = new PdfXfaTextElement("Membership status");
MS.Font = font0;
MS.Margins.Top = 25;
MS.Height = 42;
MS.Width = 400;
subForm1.Fields.Add(MS);
subForm1.Fields.Add(line1);
PdfXfaRadioButtonGroup msg = new PdfXfaRadioButtonGroup("group1");
msg.Margins.Top = 7;
subForm1.Fields.Add(msg);
PdfXfaRadioButtonField r_nonMember = new PdfXfaRadioButtonField("r1", new SizeF(120, 15));
r_nonMember.Caption = caption.Clone() as PdfXfaCaption;
r_nonMember.Caption.Text = "Non-Member";
r_nonMember.VerticalAlignment = PdfXfaVerticalAlignment.Middle;
r_nonMember.Border.Style = PdfXfaBorderStyle.Lowered;
r_nonMember.Caption.Width = 100;
msg.Items.Add(r_nonMember);
PdfXfaRadioButtonField r_member = new PdfXfaRadioButtonField("r2", new SizeF(100, 15));
r_member.Caption = caption.Clone() as PdfXfaCaption;
r_member.Caption.Text = "Member";
r_member.Border.Style = PdfXfaBorderStyle.Lowered;
r_member.VerticalAlignment = PdfXfaVerticalAlignment.Middle;
r_member.Caption.Width = 80;
msg.Items.Add(r_member);
PdfXfaRadioButtonField r_exhibition = new PdfXfaRadioButtonField("r3", new SizeF(100, 15));
r_exhibition.Caption = caption.Clone() as PdfXfaCaption;
r_exhibition.Caption.Text = "Exhibition";
r_exhibition.VerticalAlignment = PdfXfaVerticalAlignment.Middle;
r_exhibition.Caption.Width = 80;
r_exhibition.Border.Style = PdfXfaBorderStyle.Lowered;
msg.Items.Add(r_exhibition);
PdfXfaRadioButtonField r_student = new PdfXfaRadioButtonField("r4", new SizeF(100, 15));
r_student.Caption = caption.Clone() as PdfXfaCaption;
r_student.Caption.Text = "Student";
r_student.VerticalAlignment = PdfXfaVerticalAlignment.Middle;
r_student.Border.Style = PdfXfaBorderStyle.Lowered;
r_student.Caption.Width = 80;
msg.Items.Add(r_student);
mainForm.Fields.Add(subForm1);
doc.XfaForm = mainForm;
//Saving the PDF to the MemoryStream
MemoryStream ms = new MemoryStream();
doc.Save(ms, PdfXfaType.Static);
doc.Close();
//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;
}
}
}

Просмотреть файл

@ -1,27 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Syncfusion.ZugFerd
{
/// <summary>
/// Country codes
/// </summary>
public enum CountryCodes
{
US,
AX,
AL,
DZ,
AS,
AD,
}
}

Просмотреть файл

@ -1,124 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Syncfusion.ZugFerd
{
/// <summary>
/// Currency Codes
/// </summary>
public enum CurrencyCodes
{
AED = 784,
AFN = 971,
ALL = 8,
AMD = 51,
ARS = 32,
AUD = 36,
AZN = 944,
BAM = 977,
BDT = 50,
BGN = 975,
BHD = 48,
BND = 96,
BOB = 68,
BRL = 986,
BYR = 974,
BZD = 84,
CAD = 124,
CHF = 756,
CLP = 152,
CNY = 156,
COP = 170,
CRC = 188,
CZK = 203,
DKK = 208,
DOP = 214,
DZD = 12,
EEK = 233,
EGP = 818,
ETB = 230,
EUR = 978,
GBP = 826,
GEL = 981,
GTQ = 320,
HKD = 344,
HNL = 340,
HRK = 191,
HUF = 348,
IDR = 360,
ILS = 376,
INR = 356,
IQD = 368,
IRR = 364,
ISK = 352,
JMD = 388,
JOD = 400,
JPY = 392,
KES = 404,
KGS = 417,
KHR = 116,
KRW = 410,
KWD = 414,
KZT = 398,
LAK = 418,
LBP = 422,
LKR = 144,
LTL = 440,
LVL = 428,
LYD = 434,
MAD = 504,
MKD = 807,
MNT = 496,
MOP = 446,
MVR = 462,
MXN = 484,
MYR = 458,
NIO = 558,
NOK = 578,
NPR = 524,
NZD = 554,
OMR = 512,
PAB = 590,
PEN = 604,
PHP = 608,
PKR = 586,
PLN = 985,
PYG = 600,
QAR = 634,
RON = 946,
RSD = 941,
RUB = 643,
RWF = 646,
SAR = 682,
SEK = 752,
SGD = 702,
SYP = 760,
THB = 764,
TJS = 972,
TND = 788,
TRY = 949,
TTD = 780,
TWD = 901,
UAH = 980,
USD = 840,
UYU = 858,
UZS = 860,
VEF = 937,
VND = 704,
XOF = 952,
YER = 886,
ZAR = 710,
ZWL = 932,
Unknown = 0
}
}

Просмотреть файл

@ -1,27 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Syncfusion.ZugFerd
{
/// <summary>
/// Invoice Type
/// </summary>
public enum InvoiceType
{
Unknown = 0,
Invoice = 380,
Correction = 1380,
CreditNote = 381,
DebitNote = 383,
SelfBilledInvoice = 389
}
}

Просмотреть файл

@ -1,33 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Syncfusion.ZugFerd
{
/// <summary>
/// Invoice product
/// </summary>
public class Product
{
public string ProductID { get; set; }
public string productName { get; set; }
public float Price { get; set; }
public float Quantity { get; set; }
public float Total { get; set; }
}
}

Просмотреть файл

@ -1,28 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Syncfusion.ZugFerd
{
/// <summary>
/// User Details
/// </summary>
public class UserDetails
{
public string ID { get; set; }
public string Name { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Postcode { get; set; }
public CountryCodes Country { get; set; }
public string Street { get; set; }
}
}

Просмотреть файл

@ -1,336 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace Syncfusion.ZugFerd
{
/// <summary>
/// zugFerd Invoice
/// </summary>
public class ZugFerdInvoice
{
public string InvoiceNumber { get; set; }
public DateTime InvoiceDate { get; set; }
public CurrencyCodes Currency { get; set; }
public InvoiceType Type { get; set; }
public UserDetails Buyer { get; set; }
public UserDetails Seller { get; set; }
public ZugFerdProfile Profile { get; set; }
public float TotalAmount { get; set; }
List<Product> products = new List<Product>();
XNamespace rsm = "urn:ferd:CrossIndustryDocument:invoice:1p0";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XNamespace udt = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15";
XNamespace ram = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12";
public void AddProduct(Product product)
{
products.Add(product);
}
public void AddProduct(string productID, string productName,float price, float quantity, float totalPrice)
{
Product product = new Product()
{
ProductID = productID,
productName = productName,
Price = price,
Quantity = quantity,
Total = totalPrice
};
products.Add(product);
}
public ZugFerdInvoice(string invoiceNumber, DateTime invoiceDate, CurrencyCodes currency)
{
InvoiceNumber= invoiceNumber;
InvoiceDate = invoiceDate;
Currency = currency;
}
public Stream Save(Stream stream)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = Encoding.UTF8;
XDocument doc = new XDocument();
XElement root = new XElement(rsm + "CrossIndustryDocument", new XAttribute(XNamespace.Xmlns + "xsi", xsi));
root.SetAttributeValue(XNamespace.Xmlns + "rsm", rsm);
root.SetAttributeValue(XNamespace.Xmlns + "ram", ram);
root.SetAttributeValue(XNamespace.Xmlns + "udt", udt);
#region SpecifiedExchangedDocumentContext
XElement SpecifiedExchangedDocumentContext = new XElement(rsm + "SpecifiedExchangedDocumentContext");
XElement testIndicator = new XElement(ram + "TestIndicator");
XElement udtIndicator = new XElement(udt + "Indicator");
udtIndicator.Value = "true";
testIndicator.Add(udtIndicator);
SpecifiedExchangedDocumentContext.Add(testIndicator);
XElement guidelineSpecifiedDocumentContextParameter = new XElement(ram + "GuidelineSpecifiedDocumentContextParameter");
XElement id = new XElement(ram + "ID");
id.Value = "urn:ferd:CrossIndustryDocument:invoice:1p0:" + Profile.ToString();
guidelineSpecifiedDocumentContextParameter.Add(id);
SpecifiedExchangedDocumentContext.Add(guidelineSpecifiedDocumentContextParameter);
root.Add(SpecifiedExchangedDocumentContext);
#endregion
#region HeaderExchangedDocument
XElement headerExchangedDocument = new XElement(rsm + "HeaderExchangedDocument");
id = new XElement(ram + "ID");
id.Value = InvoiceNumber;
headerExchangedDocument.Add(id);
XElement name = new XElement(ram + "Name");
name.Value = GetInvoiceTypeName(Type);
headerExchangedDocument.Add(name);
XElement typeCode = new XElement(ram + "TypeCode");
typeCode.Value = GetInvoiceTypeCode(Type).ToString();
headerExchangedDocument.Add(typeCode);
XElement issueDateTime = new XElement(ram + "IssueDateTime");
XElement dateTimeString = new XElement(udt + "DateTimeString", new XAttribute("format", "102"));
dateTimeString.Value = ConvertDateFormat(InvoiceDate, "102");
issueDateTime.Add(dateTimeString);
headerExchangedDocument.Add(issueDateTime);
root.Add(headerExchangedDocument);
#endregion
#region SpecifiedSupplyChainTradeTransaction
XElement specifiedSupplyChainTradeTransaction = new XElement(rsm + "SpecifiedSupplyChainTradeTransaction");
XElement applicableSupplyChainTradeAgreement = new XElement(ram + "ApplicableSupplyChainTradeAgreement");
XElement sellerParty = WriteUserDetails("SellerTradeParty", Seller);
applicableSupplyChainTradeAgreement.Add(sellerParty);
XElement buyerParty =WriteUserDetails("BuyerTradeParty", Buyer);
applicableSupplyChainTradeAgreement.Add(buyerParty);
specifiedSupplyChainTradeTransaction.Add(applicableSupplyChainTradeAgreement);
XElement ApplicableSupplyChainTradeSettlement = new XElement(ram+"ApplicableSupplyChainTradeSettlement");
XElement InvoiceCurrencyCode = new XElement(ram+ "InvoiceCurrencyCode");
InvoiceCurrencyCode.Value = Currency.ToString("g");
ApplicableSupplyChainTradeSettlement.Add(InvoiceCurrencyCode);
XElement SpecifiedTradeSettlementMonetarySummation = new XElement(ram+"SpecifiedTradeSettlementMonetarySummation");
XElement GrandTotalAmount = new XElement(ram+"GrandTotalAmount");
GrandTotalAmount.Value = TotalAmount.ToString();
GrandTotalAmount.SetAttributeValue("currencyID",Currency.ToString("g"));
SpecifiedTradeSettlementMonetarySummation.Add(GrandTotalAmount);
ApplicableSupplyChainTradeSettlement.Add(SpecifiedTradeSettlementMonetarySummation);
specifiedSupplyChainTradeTransaction.Add(ApplicableSupplyChainTradeSettlement);
XElement LineItem = AddTradeLineItems();
specifiedSupplyChainTradeTransaction.Add(LineItem);
root.Add(specifiedSupplyChainTradeTransaction);
#endregion
doc.Add(root);
XmlWriter writer = XmlWriter.Create(stream, settings);
doc.WriteTo(writer);
writer.Flush();
stream.Position = 0;
return stream;
}
private XElement AddTradeLineItems()
{
XElement tradeLineItem = null;
if (products.Count == 0)
throw new Exception("prodcut empty");
foreach (Product product in this.products)
{
tradeLineItem = new XElement(ram + "IncludedSupplyChainTradeLineItem");
if (Profile != ZugFerdProfile.Basic)
{
XElement tradeAgreement = new XElement(ram + "SpecifiedSupplyChainTradeAgreement");
XElement tradePrice = new XElement(ram + "GrossPriceProductTradePrice");
XElement basisQuantity = new XElement(ram + "BasisQuantity");
basisQuantity.Value = product.Quantity.ToString();
tradePrice.Add(basisQuantity);
tradeAgreement.Add(tradePrice);
tradeLineItem.Add(tradeAgreement);
}
XElement SpecifiedSupplyChainTradeDelivery = new XElement(ram + "SpecifiedSupplyChainTradeDelivery");
XElement BilledQuantity = new XElement(ram + "BilledQuantity");
BilledQuantity.Value = product.Quantity.ToString();
BilledQuantity.SetAttributeValue("unitCode", "KGM");
SpecifiedSupplyChainTradeDelivery.Add(BilledQuantity);
tradeLineItem.Add(SpecifiedSupplyChainTradeDelivery);
XElement tradSettlement = new XElement(ram + "SpecifiedSupplyChainTradeSettlement");
XElement monetarySummation = new XElement(ram + "SpecifiedTradeSettlementMonetarySummation");
XElement LineTotalAmount = new XElement(ram + "LineTotalAmount");
LineTotalAmount.Value = FormatValue(TotalAmount);
LineTotalAmount.SetAttributeValue("currencyID", this.Currency.ToString("g"));
monetarySummation.Add(LineTotalAmount);
tradSettlement.Add(monetarySummation);
tradeLineItem.Add(tradSettlement);
XElement SpecifiedTradeProduct = new XElement(ram + "SpecifiedTradeProduct");
XElement productName = new XElement(ram + "Name");
productName.Value = product.productName;
SpecifiedTradeProduct.Add(productName);
tradeLineItem.Add(SpecifiedTradeProduct);
}
return tradeLineItem;
}
private void WriteAttribute(XmlWriter writer, string tagName, string attributeName, string attributeValue, string nodeValue)
{
writer.WriteStartElement(tagName);
writer.WriteAttributeString(attributeName, attributeValue);
writer.WriteValue(nodeValue);
writer.WriteEndElement();
}
private void WriteOptionalElement(XmlWriter writer, string tagName, string value)
{
if (!String.IsNullOrEmpty(value))
{
writer.WriteElementString(tagName, value);
}
}
private void WriteOptionalAmount(XmlWriter writer, string tagName, float value, int numDecimals = 2)
{
if (value !=float.MinValue)
{
writer.WriteStartElement(tagName);
writer.WriteAttributeString("currencyID", Currency.ToString("g"));
writer.WriteValue(FormatValue(value, numDecimals));
writer.WriteEndElement();
}
}
private XElement WriteUserDetails( string customerTag, UserDetails user)
{
XElement sellerTradeParty = null;
if (user != null)
{
sellerTradeParty = new XElement(ram + customerTag);
XElement id = new XElement(ram + "ID");
sellerTradeParty.Add(id);
id.Value = user.ID;
XElement name = new XElement(ram + "Name");
name.Value = user.Name;
sellerTradeParty.Add(name);
XElement postalTradeAddress = new XElement(ram + "PostalTradeAddress");
XElement postcodeCode = new XElement(ram + "PostcodeCode");
postcodeCode.Value = user.Postcode;
postalTradeAddress.Add(postcodeCode);
XElement lineOne = new XElement(ram + "LineOne");
lineOne.Value = string.IsNullOrEmpty(user.ContactName) ? user.Street : user.ContactName;
postalTradeAddress.Add(lineOne);
XElement lineTwo = new XElement(ram + "LineTwo");
lineTwo.Value = user.Street;
postalTradeAddress.Add(lineTwo);
XElement cityName = new XElement(ram + "CityName");
cityName.Value = user.City;
postalTradeAddress.Add(cityName);
XElement countryID = new XElement(ram + "CountryID");
countryID.Value = user.Country.ToString("g");
postalTradeAddress.Add(countryID);
sellerTradeParty.Add(postalTradeAddress);
}
return sellerTradeParty;
}
private string ConvertDateFormat(DateTime date, String format = "102")
{
if (format.Equals("102"))
{
return date.ToString("yyyymmdd");
}
else
{
return date.ToString("yyyy-MM-ddTHH:mm:ss");
}
}
private string GetInvoiceTypeName(InvoiceType type)
{
switch (type)
{
case InvoiceType.Invoice: return "RECHNUNG";
case InvoiceType.Correction: return "KORREKTURRECHNUNG";
case InvoiceType.CreditNote: return "GUTSCHRIFT";
case InvoiceType.DebitNote: return "";
case InvoiceType.SelfBilledInvoice: return "";
default: return "";
}
}
private int GetInvoiceTypeCode(InvoiceType type)
{
if ((int)type > 1000)
{
type -= 1000;
}
return (int)type;
}
private string FormatValue(float value, int numDecimals = 2)
{
string formatString = "0.";
for (int i = 0; i < numDecimals; i++)
{
formatString += "0";
}
return value.ToString(formatString).Replace(",", ".");
}
}
}

Просмотреть файл

@ -1,25 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Syncfusion.ZugFerd
{
/// <summary>
/// ZugFord Profile
/// </summary>
public enum ZugFerdProfile
{
Unknown = 0,
Basic = 1,
Comfort = 2,
Extended = 3
}
}

Просмотреть файл

@ -1,383 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.Drawing;
using System.IO;
using Syncfusion.Pdf.Grid;
using System.Xml.Linq;
using Syncfusion.Pdf.Interactive;
using Syncfusion.ZugFerd;
using System.Collections.Generic;
using System.Linq;
namespace samplebrowser.Controllers
{
public partial class PdfController : Controller
{
//
// GET: /Zugferd/
public ActionResult Zugferd()
{
return View();
}
RectangleF TotalPriceCellBounds = RectangleF.Empty;
RectangleF QuantityCellBounds = RectangleF.Empty;
[HttpPost]
public ActionResult Zugferd(string InsideBrowser)
{
//Create ZugFerd invoice PDF
PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic;
CreateZugFerdInvoicePDF(document);
//Create ZugFerd Xml attachment file
Stream zugferdXmlStream = CreateZugFerdXML();
//Creates an attachment.
PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXmlStream);
attachment.Relationship = PdfAttachmentRelationship.Alternative;
attachment.ModificationDate = DateTime.Now;
attachment.Description = "Adventure Invoice";
attachment.MimeType = "application/xml";
document.Attachments.Add(attachment);
MemoryStream stream = new MemoryStream();
//Save the PDF document.
document.Save(stream);
//Close the PDF document.
document.Close();
stream.Position = 0;
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = "Zugferd.pdf";
return fileStreamResult;
}
public Stream CreateZugFerdXML()
{
//Create ZugFerd Invoice
ZugFerdInvoice invoice = new ZugFerdInvoice("2058557939", new DateTime(2013, 6, 5), CurrencyCodes.USD);
//Set ZugFerdProfile to ZugFerdInvoice
invoice.Profile = ZugFerdProfile.Basic;
//Add buyer details
invoice.Buyer = new UserDetails
{
ID = "Abraham_12",
Name = "Abraham Swearegin",
ContactName = "Swearegin",
City = "United States, California",
Postcode = "9920",
Country = CountryCodes.US,
Street = "9920 BridgePointe Parkway"
};
//Add seller details
invoice.Seller = new UserDetails
{
ID = "Adventure_123",
Name = "AdventureWorks",
ContactName = "Adventure support",
City = "Austin,TX",
Postcode = "",
Country = CountryCodes.US,
Street = "800 Interchange Blvd"
};
IEnumerable<Product> products = GetProductReport();
foreach (var product in products)
invoice.AddProduct(product);
invoice.TotalAmount = 1000;
MemoryStream ms = new MemoryStream();
//Save ZugFerd Xml
return invoice.Save(ms);
}
/// <summary>
/// Create ZugFerd Invoice Pdf
/// </summary>
/// <param name="document"></param>
/// <returns></returns>
public PdfDocument CreateZugFerdInvoicePDF(PdfDocument document)
{
string basePath = _hostingEnvironment.WebRootPath;
string dataPath = string.Empty;
dataPath = basePath + @"/PDF/";
//Add page to the PDF
PdfPage page = document.Pages.Add();
PdfGraphics graphics = page.Graphics;
//Create border color
PdfColor borderColor = Syncfusion.Drawing.Color.FromArgb(255, 142, 170, 219);
//Get the page width and height
float pageWidth = page.GetClientSize().Width;
float pageHeight = page.GetClientSize().Height;
//Set the header height
float headerHeight = 90;
PdfColor lightBlue = Syncfusion.Drawing.Color.FromArgb(255, 91, 126, 215);
PdfBrush lightBlueBrush = new PdfSolidBrush(lightBlue);
PdfColor darkBlue = Syncfusion.Drawing.Color.FromArgb(255, 65, 104, 209);
PdfBrush darkBlueBrush = new PdfSolidBrush(darkBlue);
PdfBrush whiteBrush = new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255));
FileStream fontStream = new FileStream(dataPath + "arial.ttf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
PdfTrueTypeFont headerFont = new PdfTrueTypeFont(fontStream, 30, PdfFontStyle.Regular);
PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 18, PdfFontStyle.Regular);
PdfTrueTypeFont arialBoldFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold);
//Create string format.
PdfStringFormat format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
format.LineAlignment = PdfVerticalAlignment.Middle;
float y = 0;
float x = 0;
//Set the margins of address.
float margin = 30;
//Set the line space
float lineSpace = 7;
PdfPen borderPen = new PdfPen(borderColor, 1f);
//Draw page border
graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));
PdfGrid grid = new PdfGrid();
grid.DataSource = GetProductReport();
#region Header
//Fill the header with light Brush
graphics.DrawRectangle(lightBlueBrush, new RectangleF(0, 0, pageWidth, headerHeight));
string title = "INVOICE";
SizeF textSize = headerFont.MeasureString(title);
RectangleF headerTotalBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);
graphics.DrawString(title, headerFont, whiteBrush, new RectangleF(0, 0, textSize.Width + 50, headerHeight), format);
graphics.DrawRectangle(darkBlueBrush, headerTotalBounds);
graphics.DrawString("$" + GetTotalAmount(grid).ToString(), arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight + 10), format);
arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);
format.LineAlignment = PdfVerticalAlignment.Bottom;
graphics.DrawString("Amount", arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight / 2 - arialRegularFont.Height), format);
#endregion
SizeF size = arialRegularFont.MeasureString("Invoice Number: 2058557939");
y = headerHeight + margin;
x = (pageWidth - margin) - size.Width;
graphics.DrawString("Invoice Number: 2058557939", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
size = arialRegularFont.MeasureString("Date :" + DateTime.Now.ToString("dddd dd, MMMM yyyy"));
x = (pageWidth - margin) - size.Width;
y += arialRegularFont.Height + lineSpace;
graphics.DrawString("Date: " + DateTime.Now.ToString("dddd dd, MMMM yyyy"), arialRegularFont, PdfBrushes.Black, new PointF(x, y));
y = headerHeight + margin;
x = margin;
graphics.DrawString("Bill To:", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
y += arialRegularFont.Height + lineSpace;
graphics.DrawString("Abraham Swearegin,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
y += arialRegularFont.Height + lineSpace;
graphics.DrawString("United States, California, San Mateo,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
y += arialRegularFont.Height + lineSpace;
graphics.DrawString("9920 BridgePointe Parkway,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
y += arialRegularFont.Height + lineSpace;
graphics.DrawString("9365550136", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
#region Grid
grid.Columns[0].Width = 110;
grid.Columns[1].Width = 150;
grid.Columns[2].Width = 110;
grid.Columns[3].Width = 70;
grid.Columns[4].Width = 100;
for (int i = 0; i < grid.Headers.Count; i++)
{
grid.Headers[i].Height = 20;
for (int j = 0; j < grid.Columns.Count; j++)
{
PdfStringFormat pdfStringFormat = new PdfStringFormat();
pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;
pdfStringFormat.Alignment = PdfTextAlignment.Left;
if (j == 0 || j == 2)
grid.Headers[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
grid.Headers[i].Cells[j].StringFormat = pdfStringFormat;
grid.Headers[i].Cells[j].Style.Font = arialBoldFont;
}
grid.Headers[0].Cells[0].Value = "Product Id";
}
for (int i = 0; i < grid.Rows.Count; i++)
{
grid.Rows[i].Height = 23;
for (int j = 0; j < grid.Columns.Count; j++)
{
PdfStringFormat pdfStringFormat = new PdfStringFormat();
pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;
pdfStringFormat.Alignment = PdfTextAlignment.Left;
if (j == 0 || j == 2)
grid.Rows[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
grid.Rows[i].Cells[j].StringFormat = pdfStringFormat;
grid.Rows[i].Cells[j].Style.Font = arialRegularFont;
}
}
grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5);
grid.BeginCellLayout += Grid_BeginCellLayout;
PdfGridLayoutResult result = grid.Draw(page, new PointF(0, y + 40));
y = result.Bounds.Bottom + lineSpace;
format = new PdfStringFormat();
format.Alignment = PdfTextAlignment.Center;
RectangleF bounds = new RectangleF(QuantityCellBounds.X, y, QuantityCellBounds.Width, QuantityCellBounds.Height);
page.Graphics.DrawString("Grand Total:", arialBoldFont, PdfBrushes.Black, bounds, format);
bounds = new RectangleF(TotalPriceCellBounds.X, y, TotalPriceCellBounds.Width, TotalPriceCellBounds.Height);
page.Graphics.DrawString(GetTotalAmount(grid).ToString(), arialBoldFont, PdfBrushes.Black, bounds);
#endregion
borderPen.DashStyle = PdfDashStyle.Custom;
borderPen.DashPattern = new float[] { 3, 3 };
graphics.DrawLine(borderPen, new PointF(0, pageHeight - 100), new PointF(pageWidth, pageHeight - 100));
y = pageHeight - 100 + margin;
size = arialRegularFont.MeasureString("800 Interchange Blvd.");
x = pageWidth - size.Width - margin;
graphics.DrawString("800 Interchange Blvd.", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
y += arialRegularFont.Height + lineSpace;
size = arialRegularFont.MeasureString("Suite 2501, Austin, TX 78721");
x = pageWidth - size.Width - margin;
graphics.DrawString("Suite 2501, Austin, TX 78721", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
y += arialRegularFont.Height + lineSpace;
size = arialRegularFont.MeasureString("Any Questions? support@adventure-works.com");
x = pageWidth - size.Width - margin;
graphics.DrawString("Any Questions? support@adventure-works.com", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
return document;
}
private void Grid_BeginCellLayout(object sender, PdfGridBeginCellLayoutEventArgs args)
{
PdfGrid grid = sender as PdfGrid;
if (args.CellIndex == grid.Columns.Count - 1)
{
TotalPriceCellBounds = args.Bounds;
}
else if (args.CellIndex == grid.Columns.Count - 2)
{
QuantityCellBounds = args.Bounds;
}
}
private IEnumerable<Product> GetProductReport()
{
//Stream xmlStream = typeof(ZugFerd).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.InvoiceProductList.xml");
string dataPath = _hostingEnvironment.WebRootPath + @"/PDF/";
//Read the file
FileStream xmlStream = new FileStream(dataPath + "InvoiceProductList.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader reader = new StreamReader(xmlStream, true))
{
return XElement.Parse(reader.ReadToEnd())
.Elements("ProductDetails")
.Select(c => new Product
{
ProductID = c.Element("Productid").Value,
productName = c.Element("Product").Value,
Price = float.Parse(c.Element("Price").Value, System.Globalization.CultureInfo.InvariantCulture),
Quantity = float.Parse(c.Element("Quantity").Value, System.Globalization.CultureInfo.InvariantCulture),
Total = float.Parse(c.Element("Total").Value, System.Globalization.CultureInfo.InvariantCulture)
});
}
}
/// <summary>
/// Get the Total amount of purcharsed items
/// </summary>
/// <param name="grid"></param>
/// <returns></returns>
private float GetTotalAmount(PdfGrid grid)
{
float Total = 0f;
for (int i = 0; i < grid.Rows.Count; i++)
{
string cellValue = grid.Rows[i].Cells[grid.Columns.Count - 1].Value.ToString();
float result = float.Parse(cellValue, System.Globalization.CultureInfo.InvariantCulture);
Total += result;
}
return Total;
}
}
}

Просмотреть файл

@ -1,103 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public IActionResult CreateAnimation()
{
return View();
}
[HttpPost]
public ActionResult CreateAnimation(string Browser)
{
//Opens the presentation document as stream
string basePath = _hostingEnvironment.WebRootPath;
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/Animation.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
//PowerPoint instance is Created.
//Method call to create animation
Animation(presentation);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "CreateAnimation.pptx";
return fileStreamResult;
}
#region Slide1
private void Animation(IPresentation presentation)
{
//Get the slide from the presentation
ISlide slide = presentation.Slides[0];
//Access the animation sequence to create effects
ISequence sequence = slide.Timeline.MainSequence;
//Add motion path effect to the shape
IEffect line1 = sequence.AddEffect(slide.Shapes[8] as IShape, EffectType.PathUp, EffectSubtype.None, EffectTriggerType.OnClick);
IMotionEffect motionEffect = line1.Behaviors[0] as IMotionEffect;
motionEffect.Timing.Duration = 1f;
IMotionPath motionPath = motionEffect.Path;
motionPath[1].Points[0].X = 0.00365f;
motionPath[1].Points[0].Y = -0.27431f;
//Add motion path effect to the shape
IEffect line2 = sequence.AddEffect(slide.Shapes[3] as IShape, EffectType.PathDown, EffectSubtype.None, EffectTriggerType.WithPrevious);
motionEffect = line2.Behaviors[0] as IMotionEffect;
motionEffect.Timing.Duration = 0.75f;
motionPath = motionEffect.Path;
motionPath[1].Points[0].X = 0.00234f;
motionPath[1].Points[0].Y = 0.43449f;
//Add wipe effect to the shape
IEffect wipe1 = sequence.AddEffect(slide.Shapes[1] as IShape, EffectType.Wipe, EffectSubtype.None, EffectTriggerType.AfterPrevious);
wipe1.Behaviors[1].Timing.Duration = 1f;
//Add fly effect to the shape
IEffect fly1 = sequence.AddEffect(slide.Shapes[5] as IShape, EffectType.Fly, EffectSubtype.Left, EffectTriggerType.AfterPrevious);
fly1.Behaviors[1].Timing.Duration = 0.70f;
fly1.Behaviors[2].Timing.Duration = 0.70f;
////Add wipe effect to the shape
IEffect wipe2 = sequence.AddEffect(slide.Shapes[2] as IShape, EffectType.Wipe, EffectSubtype.None, EffectTriggerType.AfterPrevious);
wipe2.Behaviors[1].Timing.Duration = 1f;
////Add fly effect to the shape
IEffect fly2 = sequence.AddEffect(slide.Shapes[4] as IShape, EffectType.Fly, EffectSubtype.Right, EffectTriggerType.AfterPrevious);
fly2.Behaviors[1].Timing.Duration = 0.70f;
fly2.Behaviors[2].Timing.Duration = 0.70f;
IEffect fly3 = sequence.AddEffect(slide.Shapes[6] as IShape, EffectType.Fly, EffectSubtype.Top, EffectTriggerType.AfterPrevious);
fly3.Behaviors[1].Timing.Duration = 1.50f;
fly3.Behaviors[2].Timing.Duration = 1.50f;
////Add flay effect to the shape
IEffect fly4 = sequence.AddEffect(slide.Shapes[7] as IShape, EffectType.Fly, EffectSubtype.Left, EffectTriggerType.AfterPrevious);
fly4.Behaviors[1].Timing.Duration = 0.50f;
fly4.Behaviors[2].Timing.Duration = 0.50f;
}
#endregion
}
}

Просмотреть файл

@ -1,159 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
using Syncfusion.OfficeChart;
using Syncfusion.Drawing;
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public IActionResult Chart()
{
return View();
}
[HttpPost]
public ActionResult Chart(string Browser)
{
IPresentation presentation = Syncfusion.Presentation.Presentation.Create();
// Method call to create slides
CreateChart(presentation);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "Chart.pptx";
return fileStreamResult;
}
#region Slide
# region Slide1
private void CreateChart(IPresentation presentation)
{
ISlide slide1 = presentation.Slides.Add(SlideLayoutType.Blank);
IPresentationChart chart = slide1.Shapes.AddChart(1.93 * 72, 0.31 * 72, 9.48 * 72, 6.89 * 72);
chart.ChartData.SetValue(1, 1, "Crescent City, CA");
chart.ChartData.SetValue(3, 2, "Precipitation,in.");
chart.ChartData.SetValue(3, 3, "Temperature,deg.F");
chart.ChartData.SetValue(4, 1, "Jan");
chart.ChartData.SetValue(5, 1, "Feb");
chart.ChartData.SetValue(6, 1, "March");
chart.ChartData.SetValue(7, 1, "Apr");
chart.ChartData.SetValue(8, 1, "May");
chart.ChartData.SetValue(9, 1, "June");
chart.ChartData.SetValue(10, 1, "July");
chart.ChartData.SetValue(11, 1, "Aug");
chart.ChartData.SetValue(12, 1, "Sept");
chart.ChartData.SetValue(13, 1, "Oct");
chart.ChartData.SetValue(14, 1, "Nov");
chart.ChartData.SetValue(15, 1, "Dec");
chart.ChartData.SetValue(4, 2, 10.9);
chart.ChartData.SetValue(5, 2, 8.9);
chart.ChartData.SetValue(6, 2, 8.6);
chart.ChartData.SetValue(7, 2, 4.8);
chart.ChartData.SetValue(8, 2, 3.2);
chart.ChartData.SetValue(9, 2, 1.4);
chart.ChartData.SetValue(10, 2, 0.6);
chart.ChartData.SetValue(11, 2, 0.7);
chart.ChartData.SetValue(12, 2, 1.7);
chart.ChartData.SetValue(13, 2, 5.4);
chart.ChartData.SetValue(14, 2, 9.0);
chart.ChartData.SetValue(15, 2, 10.4);
chart.ChartData.SetValue(4, 3, 47.5);
chart.ChartData.SetValue(5, 3, 48.7);
chart.ChartData.SetValue(6, 3, 48.9);
chart.ChartData.SetValue(7, 3, 50.2);
chart.ChartData.SetValue(8, 3, 53.1);
chart.ChartData.SetValue(9, 3, 56.3);
chart.ChartData.SetValue(10, 3, 58.1);
chart.ChartData.SetValue(11, 3, 59.0);
chart.ChartData.SetValue(12, 3, 58.5);
chart.ChartData.SetValue(13, 3, 55.4);
chart.ChartData.SetValue(14, 3, 51.1);
chart.ChartData.SetValue(15, 3, 47.8);
chart.DataRange = chart.ChartData[3, 1, 15, 3];
chart.ChartTitle = "Crescent City, CA";
chart.PrimaryValueAxis.Title = "Precipitation,in.";
chart.PrimaryValueAxis.TitleArea.TextRotationAngle = 90;
chart.PrimaryValueAxis.MaximumValue = 14.0;
chart.PrimaryValueAxis.NumberFormat = "0.0";
#region Format Series
// Format serie
IOfficeChartSerie serieOne = chart.Series[0];
serieOne.Name = "Precipitation,in.";
serieOne.SerieFormat.Fill.FillType = OfficeFillType.Gradient;
serieOne.SerieFormat.Fill.TwoColorGradient(OfficeGradientStyle.Vertical, OfficeGradientVariants.ShadingVariants_2);
serieOne.SerieFormat.Fill.GradientColorType = OfficeGradientColor.TwoColor;
serieOne.SerieFormat.Fill.ForeColor = Color.Plum;
//Show value as data labels
serieOne.DataPoints.DefaultDataPoint.DataLabels.IsValue = true;
serieOne.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside;
//Format the second serie
IOfficeChartSerie serieTwo = chart.Series[1];
serieTwo.SerieType = OfficeChartType.Line_Markers;
serieTwo.Name = "Temperature,deg.F";
//Format marker
serieTwo.SerieFormat.MarkerStyle = OfficeChartMarkerType.Diamond;
serieTwo.SerieFormat.MarkerSize = 8;
serieTwo.SerieFormat.MarkerBackgroundColor = Color.DarkGreen;
serieTwo.SerieFormat.MarkerForegroundColor = Color.DarkGreen;
serieTwo.SerieFormat.LineProperties.LineColor = Color.DarkGreen;
//Use Secondary Axis
serieTwo.UsePrimaryAxis = false;
#endregion
#region Set the Secondary Axis for Second Serie.
//Display secondary axis for the series.
chart.SecondaryCategoryAxis.IsMaxCross = true;
chart.SecondaryValueAxis.IsMaxCross = true;
//Set the title
chart.SecondaryValueAxis.Title = "Temperature,deg.F";
chart.SecondaryValueAxis.TitleArea.TextRotationAngle = 90;
//Hide the secondary category axis
chart.SecondaryCategoryAxis.Border.LineColor = Color.Transparent;
chart.SecondaryCategoryAxis.MajorTickMark = OfficeTickMark.TickMark_None;
chart.SecondaryCategoryAxis.TickLabelPosition = OfficeTickLabelPosition.TickLabelPosition_None;
#endregion
#region Legend setting
chart.Legend.Position = OfficeLegendPosition.Bottom;
chart.Legend.IsVerticalLegend = false;
#endregion
}
#endregion
#endregion
}
}

Просмотреть файл

@ -1,163 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
using Syncfusion.OfficeChart;
using Syncfusion.Drawing;
using System;
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public IActionResult Comment()
{
return View();
}
[HttpPost]
public ActionResult Comment(string Browser)
{
string basePath = _hostingEnvironment.WebRootPath;
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/Images.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
SlideWithComments(presentation);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "Comment.pptx";
return fileStreamResult;
}
private void SlideWithComments(IPresentation presentation)
{
#region Slide 1
ISlide slide1 = presentation.Slides[0];
IShape shape1 = (IShape)slide1.Shapes[0];
shape1.Left = 1.27 * 72;
shape1.Top = 0.85 * 72;
shape1.Width = 10.86 * 72;
shape1.Height = 3.74 * 72;
ITextBody textFrame = shape1.TextBody;
IParagraphs paragraphs = textFrame.Paragraphs;
paragraphs.Add();
IParagraph paragraph = paragraphs[0];
paragraph.HorizontalAlignment = HorizontalAlignmentType.Left;
ITextParts textParts = paragraph.TextParts;
textParts.Add();
ITextPart textPart = textParts[0];
textPart.Text = "Essential Presentation ";
textPart.Font.CapsType = TextCapsType.All;
textPart.Font.FontName = "Calibri Light (Headings)";
textPart.Font.FontSize = 80;
textPart.Font.Color = ColorObject.Black;
IComment comment = slide1.Comments.Add(0.5, 0.04, "Author1", "A1", "Essential Presentation is available from 13.1 versions of Essential Studio", DateTime.Now);
//Author2 add reply to a parent comment
slide1.Comments.Add("Author2", "A2", "Does it support rendering of slides as images or PDF?", DateTime.Now, comment);
//Author1 add reply to a parent comment
slide1.Comments.Add("Author1", "A1", "Yes, you may render slides as images and PDF.", DateTime.Now, comment);
#endregion
#region Slide2
ISlide slide2 = presentation.Slides.Add(SlideLayoutType.Blank);
IPresentationChart chart = slide2.Shapes.AddChart(230, 80, 500, 400);
//Specifies the chart title
chart.ChartTitle = "Sales Analysis";
//Sets chart data - Row1
chart.ChartData.SetValue(1, 2, "Jan");
chart.ChartData.SetValue(1, 3, "Feb");
chart.ChartData.SetValue(1, 4, "March");
//Sets chart data - Row2
chart.ChartData.SetValue(2, 1, 2010);
chart.ChartData.SetValue(2, 2, 60);
chart.ChartData.SetValue(2, 3, 70);
chart.ChartData.SetValue(2, 4, 80);
//Sets chart data - Row3
chart.ChartData.SetValue(3, 1, 2011);
chart.ChartData.SetValue(3, 2, 80);
chart.ChartData.SetValue(3, 3, 70);
chart.ChartData.SetValue(3, 4, 60);
//Sets chart data - Row4
chart.ChartData.SetValue(4, 1, 2012);
chart.ChartData.SetValue(4, 2, 60);
chart.ChartData.SetValue(4, 3, 70);
chart.ChartData.SetValue(4, 4, 80);
//Creates a new chart series with the name
IOfficeChartSerie serieJan = chart.Series.Add("Jan");
//Sets the data range of chart serie – start row, start column, end row, end column
serieJan.Values = chart.ChartData[2, 2, 4, 2];
//Creates a new chart series with the name
IOfficeChartSerie serieFeb = chart.Series.Add("Feb");
//Sets the data range of chart serie – start row, start column, end row, end column
serieFeb.Values = chart.ChartData[2, 3, 4, 3];
//Creates a new chart series with the name
IOfficeChartSerie serieMarch = chart.Series.Add("March");
//Sets the data range of chart series – start row, start column, end row, end column
serieMarch.Values = chart.ChartData[2, 4, 4, 4];
//Sets the data range of the category axis
chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 4, 1];
//Specifies the chart type
chart.ChartType = OfficeChartType.Column_Clustered_3D;
slide2.Comments.Add(0.35, 0.04, "Author2", "A2", "Do all 3D-chart types support in Presentation library?", DateTime.Now);
#endregion
}
}
}

Просмотреть файл

@ -1,172 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
using Syncfusion.OfficeChart;
using Syncfusion.Drawing;
using System;
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public IActionResult Connector()
{
return View();
}
[HttpPost]
public ActionResult Connector(string Browser)
{
//Create an instance for PowerPoint
IPresentation presentation = Syncfusion.Presentation.Presentation.Create();
//Add a blank slide to Presentation
ISlide slide = presentation.Slides.Add(SlideLayoutType.Blank);
//Add header shape
IShape headerTextBox = slide.Shapes.AddTextBox(58.44, 53.85, 221.93, 81.20);
//Add a paragraph into the text box
IParagraph paragraph = headerTextBox.TextBody.AddParagraph("Flow chart with ");
//Add a textPart
ITextPart textPart = paragraph.AddTextPart("Connector");
//Change the color of the font
textPart.Font.Color = ColorObject.FromArgb(44, 115, 230);
//Make the textpart bold
textPart.Font.Bold = true;
//Set the font size of the paragraph
paragraph.Font.FontSize = 28;
//Add start shape to slide
IShape startShape = slide.Shapes.AddShape(AutoShapeType.FlowChartTerminator, 420.45, 36.35, 133.93, 50.39);
//Add a paragraph into the start shape text body
AddParagraph(startShape, "Start", ColorObject.FromArgb(255, 149, 34));
//Add alarm shape to slide
IShape alarmShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 420.45, 126.72, 133.93, 50.39);
//Add a paragraph into the alarm shape text body
AddParagraph(alarmShape, "Alarm Rings", ColorObject.FromArgb(255, 149, 34));
//Add condition shape to slide
IShape conditionShape = slide.Shapes.AddShape(AutoShapeType.FlowChartDecision, 420.45, 222.42, 133.93, 97.77);
//Add a paragraph into the condition shape text body
AddParagraph(conditionShape, "Ready to Get Up ?", ColorObject.FromArgb(44, 115, 213));
//Add wake up shape to slide
IShape wakeUpShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 420.45, 361.52, 133.93, 50.39);
//Add a paragraph into the wake up shape text body
AddParagraph(wakeUpShape, "Wake Up", ColorObject.FromArgb(44, 115, 213));
//Add end shape to slide
IShape endShape = slide.Shapes.AddShape(AutoShapeType.FlowChartTerminator, 420.45, 453.27, 133.93, 50.39);
//Add a paragraph into the end shape text body
AddParagraph(endShape, "End", ColorObject.FromArgb(44, 115, 213));
//Add snooze shape to slide
IShape snoozeShape = slide.Shapes.AddShape(AutoShapeType.FlowChartProcess, 624.85, 245.79, 159.76, 50.02);
//Add a paragraph into the snooze shape text body
AddParagraph(snoozeShape, "Hit Snooze button", ColorObject.FromArgb(255, 149, 34));
//Add relay shape to slide
IShape relayShape = slide.Shapes.AddShape(AutoShapeType.FlowChartDelay, 624.85, 127.12, 159.76, 49.59);
//Add a paragraph into the relay shape text body
AddParagraph(relayShape, "Relay", ColorObject.FromArgb(255, 149, 34));
//Connect the start shape with alarm shape using connector
IConnector connector1 = slide.Shapes.AddConnector(ConnectorType.Straight, startShape, 2, alarmShape, 0);
//Set the arrow style for the connector
connector1.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow;
//Connect the alarm shape with condition shape using connector
IConnector connector2 = slide.Shapes.AddConnector(ConnectorType.Straight, alarmShape, 2, conditionShape, 0);
//Set the arrow style for the connector
connector2.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow;
//Connect the condition shape with snooze shape using connector
IConnector connector3 = slide.Shapes.AddConnector(ConnectorType.Straight, conditionShape, 3, snoozeShape, 1);
//Set the arrow style for the connector
connector3.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow;
//Connect the snooze shape with relay shape using connector
IConnector connector4 = slide.Shapes.AddConnector(ConnectorType.Straight, snoozeShape, 0, relayShape, 2);
//Set the arrow style for the connector
connector4.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow;
//Connect the relay shape with alarm shape using connector
IConnector connector5 = slide.Shapes.AddConnector(ConnectorType.Straight, relayShape, 1, alarmShape, 3);
//Set the arrow style for the connector
connector5.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow;
//Connect the condition shape with wake up shape using connector
IConnector connector6 = slide.Shapes.AddConnector(ConnectorType.Straight, conditionShape, 2, wakeUpShape, 0);
//Set the arrow style for the connector
connector6.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow;
//Connect the wake up shape with end shape using connector
IConnector connector7 = slide.Shapes.AddConnector(ConnectorType.Straight, wakeUpShape, 2, endShape, 0);
//Set the arrow style for the connector
connector7.LineFormat.EndArrowheadStyle = ArrowheadStyle.Arrow;
//Add No textbox to slide
IShape noTextBox = slide.Shapes.AddTextBox(564.02, 245.43, 51.32, 26.22);
//Add a paragraph into the text box
noTextBox.TextBody.AddParagraph("No");
//Add Yes textbox to slide
IShape yesTextBox = slide.Shapes.AddTextBox(487.21, 327.99, 50.09, 26.23);
//Add a paragraph into the text box
yesTextBox.TextBody.AddParagraph("Yes");
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "Connector.pptx";
return fileStreamResult;
}
/// <summary>
/// Add a paragraph into the specified shape with specified text
/// </summary>
/// <param name="shape">Represent the shape</param>
/// <param name="text">Represent the text to be added</param>
/// <param name="fillColor">Represent the color to fill the shape</param>
private void AddParagraph(IShape shape, string text, IColor fillColor)
{
//set the fill type as solid
shape.Fill.FillType = FillType.Solid;
//Set the color of the solid fill
shape.Fill.SolidFill.Color = fillColor;
//set the fill type of line format as solid
shape.LineFormat.Fill.FillType = FillType.Solid;
//set the fill color of line format
if (fillColor.R == 255)
shape.LineFormat.Fill.SolidFill.Color = ColorObject.FromArgb(190, 100, 39);
else
shape.LineFormat.Fill.SolidFill.Color = ColorObject.FromArgb(54, 91, 157);
//Add a paragraph into the specified shape with specified text
IParagraph paragraph = shape.TextBody.AddParagraph(text);
//Set the vertical alignment as center
shape.TextBody.VerticalAlignment = VerticalAlignmentType.Middle;
//Set horizontal alignment as center
paragraph.HorizontalAlignment = HorizontalAlignmentType.Center;
//Set font color as white
paragraph.Font.Color = ColorObject.White;
//Change the font size
paragraph.Font.FontSize = 16;
}
}
}

Просмотреть файл

@ -1,125 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2017.
// Copyright Syncfusion Inc. 2001-2017. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public ActionResult Default()
{
return View();
}
private readonly IHostingEnvironment _hostingEnvironment;
public PresentationController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public ActionResult Default(string Browser)
{
//Retrieve the current application environment.
//Open the existing presentation.
string basePath = _hostingEnvironment.WebRootPath;
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/HelloWorld.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
//Method call to create slides
CreateDefaultSlide(presentation);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "Sample.pptx";
return fileStreamResult;
}
# region Slide
private void CreateDefaultSlide(IPresentation presentation)
{
//Retrieve the first slide of the presentation.
ISlide slide1 = presentation.Slides[0];
//Retrieve the first shape of the slide.
IShape titleShape = slide1.Shapes[0] as IShape;
//Set the size and position of the shape.
titleShape.Left = 0.33 * 72;
titleShape.Top = 0.58 * 72;
titleShape.Width = 12.5 * 72;
titleShape.Height = 1.75 * 72;
//Retrieve the text body of the shape.
ITextBody textFrame1 = (slide1.Shapes[0] as IShape).TextBody;
IParagraphs paragraphs1 = textFrame1.Paragraphs;
//Add a new paragraph.
IParagraph paragraph = paragraphs1.Add();
//Set the horizontal alignment type for the paragraph.
paragraph.HorizontalAlignment = HorizontalAlignmentType.Center;
//Add a text part.
ITextPart textPart1 = paragraph.AddTextPart();
//Add text to the text part.
textPart1.Text = "Essential Presentation";
//Set the font properties for the text part.
textPart1.Font.CapsType = TextCapsType.All;
textPart1.Font.FontName = "Adobe Garamond Pro";
textPart1.Font.Bold = true;
textPart1.Font.FontSize = 40;
//Retrieve the second shape of the slide.
IShape subtitle = slide1.Shapes[1] as IShape;
//Set the size and position of the shape.
subtitle.Left = 1.33 * 72;
subtitle.Top = 2.67 * 72;
subtitle.Width = 10 * 72;
subtitle.Height = 1.7 * 72;
//Retrieve the text body of the shape.
ITextBody textFrame2 = (slide1.Shapes[1] as IShape).TextBody;
textFrame2.VerticalAlignment = VerticalAlignmentType.Top;
IParagraphs paragraphs2 = textFrame2.Paragraphs;
//Add a new paragraph.
IParagraph para = paragraphs2.Add();
//Set the horizontal alignment type for the paragraph.
para.HorizontalAlignment = HorizontalAlignmentType.Left;
//Add a text part.
ITextPart textPart2 = para.AddTextPart();
//Add text to the text part.
textPart2.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus.Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet.";
textPart2.Font.FontName = "Adobe Garamond Pro";
textPart2.Font.FontSize = 21;
//Add a new paragraph.
para = paragraphs2.Add();
//Set the horizontal alignment type for the paragraph.
para.HorizontalAlignment = HorizontalAlignmentType.Left;
//Add a text part.
textPart2 = para.AddTextPart();
//Add text to the text part.
textPart2.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet. Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula.";
//Set the font properties.
textPart2.Font.FontName = "Adobe Garamond Pro";
textPart2.Font.FontSize = 21;
}
#endregion
}
}

Просмотреть файл

@ -1,79 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public IActionResult ModifyAnimation()
{
return View();
}
[HttpPost]
public ActionResult ModifyAnimation(string Browser,string view)
{
string basePath = _hostingEnvironment.WebRootPath;
if (view.Trim() == "Input Template")
{
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/ShapeWithAnimation.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
return File(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation","ShapeWithAnimation.pptx");
}
else
{
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/ShapeWithAnimation.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
//New Instance of PowerPoint is Created.[Equivalent to launching MS PowerPoint with no slides].
//Modify the existing animation
ModifyAnimation(presentation);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "ModifyAnimation.pptx";
return fileStreamResult;
}
}
#region Modify Animation
private void ModifyAnimation(IPresentation presentation)
{
//Retrieves the slide instance
ISlide slide = presentation.Slides[0];
//Retrieves the slide main sequence
ISequence sequence = slide.Timeline.MainSequence;
//Retrieves the existing animation effect from the main sequence
IEffect loopEffect = sequence[0];
//Change the type of the existing animation effect
loopEffect.Type = EffectType.Bounce;
}
#endregion
}
}

Просмотреть файл

@ -1,76 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
using Syncfusion.PresentationRenderer;
namespace samplebrowser.Controllers.Presentation
{
public partial class PresentationController : Controller
{
public IActionResult PPTXToImage()
{
return View();
}
private readonly IHostingEnvironment _hostingEnvironment;
public PresentationController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public ActionResult PPTXToImage(string Browser, string view)
{
string basePath = _hostingEnvironment.WebRootPath;
if (view.Trim() == "Input Template")
{
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/ConversionTemplate.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
return File(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation", "InputTemplate.pptx");
}
else
{
//Load the PowerPoint presentation into stream.
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/ConversionTemplate.pptx", FileMode.Open, FileAccess.Read);
//Open the existing PowerPoint presentation.
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
//Initialize PresentationRenderer to perform image conversion.
presentation.PresentationRenderer = new PresentationRenderer();
//Convert PowerPoint slide to image stream.
Stream stream = presentation.Slides[0].ConvertToImage(ExportImageFormat.Jpeg);
//Reset the stream position
stream.Position = 0;
//Close the PowerPoint Presentation.
presentation.Close();
//Initialize the file stream to download the converted image.
FileStreamResult fileStreamResult = new FileStreamResult(stream, "image/jpeg");
//Set the file name.
fileStreamResult.FileDownloadName = "Slide1.jpg";
return fileStreamResult;
}
}
}
}

Просмотреть файл

@ -1,73 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
using Syncfusion.PresentationToPdfConverter;
using Syncfusion.Pdf;
namespace samplebrowser.Controllers.Presentation
{
public partial class PresentationController : Controller
{
public IActionResult PPTXToPDF()
{
return View();
}
[HttpPost]
public ActionResult PPTXToPDF(string Browser, string view)
{
string basePath = _hostingEnvironment.WebRootPath;
if (view.Trim() == "Input Template")
{
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/ConversionTemplate.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
return File(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation", "InputTemplate.pptx");
}
else
{
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/ConversionTemplate.pptx", FileMode.Open, FileAccess.Read);
//Open the existing PowerPoint presentation.
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
//Convert the PowerPoint document to PDF document.
PdfDocument pdfDocument = PresentationToPdfConverter.Convert(presentation);
MemoryStream pdfStream = new MemoryStream();
//Save the converted PDF document to Memory stream.
pdfDocument.Save(pdfStream);
pdfStream.Position = 0;
//Close the PDF document.
pdfDocument.Close(true);
//Close the PowerPoint Presentation.
presentation.Close();
//Initialize the file stream to download the converted PDF.
FileStreamResult fileStreamResult = new FileStreamResult(pdfStream, "application/pdf");
//Set the file name.
fileStreamResult.FileDownloadName = "Sample.pdf";
return fileStreamResult;
}
}
}
}

Просмотреть файл

@ -1,551 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public IActionResult Slide()
{
return View();
}
[HttpPost]
public ActionResult Slide(string Browser)
{
string basePath = _hostingEnvironment.WebRootPath;
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/Slides.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
//New Instance of PowerPoint is Created.[Equivalent to launching MS PowerPoint with no slides].
//Method call to create slides
CreateFirstSlide(presentation);
CreateSecondtwo(presentation);
CreateThirdSlide(presentation);
CreateFourthSlide(presentation);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "Slide.pptx";
return fileStreamResult;
}
#region Slide
#region Slide1
private void CreateFirstSlide(IPresentation presentation)
{
ISlide slide1 = presentation.Slides[0];
IShape shape1 = slide1.Shapes[0] as IShape;
shape1.Left = 1.5 * 72;
shape1.Top = 1.94 * 72;
shape1.Width = 10.32 * 72;
shape1.Height = 2 * 72;
ITextBody textFrame1 = shape1.TextBody;
IParagraphs paragraphs1 = textFrame1.Paragraphs;
IParagraph paragraph1 = paragraphs1.Add();
ITextPart textPart1 = paragraph1.AddTextPart();
paragraphs1[0].IndentLevelNumber = 0;
textPart1.Text = "Essential Presentation";
textPart1.Font.FontName = "HelveticaNeue LT 65 Medium";
textPart1.Font.CapsType = TextCapsType.All;
textPart1.Font.FontSize = 48;
textPart1.Font.Bold = true;
slide1.Shapes.RemoveAt(1);
}
#endregion
# region Slide2
private void CreateSecondtwo(IPresentation presentation)
{
ISlide slide2 = presentation.Slides.Add(SlideLayoutType.SectionHeader);
IShape shape1 = slide2.Shapes[0] as IShape;
shape1.Left = 0.77 * 72;
shape1.Top = 0.32 * 72;
shape1.Width = 7.96 * 72;
shape1.Height = 0.99 * 72;
ITextBody textFrame1 = shape1.TextBody;
//Instance to hold paragraphs in textframe
IParagraphs paragraphs1 = textFrame1.Paragraphs;
IParagraph paragraph1 = paragraphs1.Add();
ITextPart textpart1 = paragraph1.AddTextPart();
paragraphs1[0].HorizontalAlignment = HorizontalAlignmentType.Left;
textpart1.Text = "Slide with simple text";
textpart1.Font.FontName = "Helvetica CE 35 Thin";
textpart1.Font.FontSize = 40;
IShape shape2 = slide2.Shapes[1] as IShape;
shape2.Left = 1.21 * 72;
shape2.Top = 1.66 * 72;
shape2.Width = 10.08 * 72;
shape2.Height = 4.93 * 72;
ITextBody textFrame2 = shape2.TextBody;
//Instance to hold paragraphs in textframe
IParagraphs paragraphs2 = textFrame2.Paragraphs;
IParagraph paragraph2 = paragraphs2.Add();
paragraph2.HorizontalAlignment = HorizontalAlignmentType.Left;
ITextPart textpart2 = paragraph2.AddTextPart();
textpart2.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus.";
textpart2.Font.FontName = "Calibri (Body)";
textpart2.Font.FontSize = 15;
textpart2.Font.Color = ColorObject.Black;
//Instance to hold paragraphs in textframe
IParagraph paragraph3 = paragraphs2.Add();
paragraph3.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart1 = paragraph3.AddTextPart();
textpart1.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet.";
textpart1.Font.FontName = "Calibri (Body)";
textpart1.Font.FontSize = 15;
textpart1.Font.Color = ColorObject.Black;
//Instance to hold paragraphs in textframe
IParagraph paragraph4 = paragraphs2.Add();
paragraph4.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart1 = paragraph4.AddTextPart();
textpart1.Text = "Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula.";
textpart1.Font.FontName = "Calibri (Body)";
textpart1.Font.FontSize = 15;
textpart1.Font.Color = ColorObject.Black;
//Instance to hold paragraphs in textframe
IParagraph paragraph5 = paragraphs2.Add();
paragraph5.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart1 = paragraph5.AddTextPart();
textpart1.Text = "Vestibulum duis integer diam mi libero felis, sollicitudin id dictum etiam blandit lacus, ac condimentum magna dictumst interdum et,";
textpart1.Font.FontName = "Calibri (Body)";
textpart1.Font.FontSize = 15;
textpart1.Font.Color = ColorObject.Black;
//Instance to hold paragraphs in textframe
IParagraph paragraph6 = paragraphs2.Add();
paragraph6.HorizontalAlignment = HorizontalAlignmentType.Left;
ITextPart textpart3 = paragraph6.AddTextPart();
textpart1.Text = "nam commodo mi habitasse enim fringilla nunc, amet aliquam sapien per tortor luctus. Conubia voluptates at nunc, congue lectus, malesuada nulla.";
textpart1.Font.Color = ColorObject.White;
textpart1.Font.FontName = "Calibri (Body)";
textpart1.Font.FontSize = 15;
textpart1.Font.Color = ColorObject.Black;
//Instance to hold paragraphs in textframe
IParagraph paragraph7 = paragraphs2.Add();
paragraph7.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart1 = paragraph7.AddTextPart();
textpart1.Text = "Rutrum quo morbi, feugiat sed mi turpis, ac cursus integer ornare dolor. Purus dui in et tincidunt, sed eros pede adipiscing tellus, est suscipit nulla,";
textpart1.Font.FontName = "Calibri (Body)";
textpart1.Font.FontSize = 15;
textpart1.Font.Color = ColorObject.Black;
//Instance to hold paragraphs in textframe
IParagraph paragraph8 = paragraphs2.Add();
paragraph8.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart1 = paragraph8.AddTextPart();
textpart1.Text = "Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula.";
textpart1.Font.FontName = "Calibri (Body)";
textpart1.Font.FontSize = 15;
textpart1.Font.Color = ColorObject.Black;
//Instance to hold paragraphs in textframe
IParagraph paragraph9 = paragraphs2.Add();
paragraph9.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart1 = paragraph9.AddTextPart();
textpart1.Text = "arcu nec fringilla vel aliquam, mollis lorem rerum hac vestibulum ante nullam. Volutpat a lectus, lorem pulvinar quis. Lobortis vehicula in imperdiet orci urna.";
textpart1.Font.FontName = "Calibri (Body)";
textpart1.Font.Color = ColorObject.Black;
textpart1.Font.FontSize = 15;
}
# endregion
# region Slide3
private void CreateThirdSlide(IPresentation presentation)
{
ISlide slide2 = presentation.Slides.Add(SlideLayoutType.TwoContent);
IShape shape1 = slide2.Shapes[0] as IShape;
shape1.Left = 0.36 * 72;
shape1.Top = 0.51 * 72;
shape1.Width = 11.32 * 72;
shape1.Height = 1.06 * 72;
//Adds textframe in shape
ITextBody textFrame1 = shape1.TextBody;
//Instance to hold paragraphs in textframe
IParagraphs paragraphs1 = textFrame1.Paragraphs;
paragraphs1.Add();
IParagraph paragraph1 = paragraphs1[0];
ITextPart textpart1 = paragraph1.AddTextPart();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Left;
//Assigns value to textpart
textpart1.Text = "Slide with Image";
textpart1.Font.FontName = "Helvetica CE 35 Thin";
//Adds shape in slide
IShape shape2 = slide2.Shapes[1] as IShape;
shape2.Left = 8.03 * 72;
shape2.Top = 1.96 * 72;
shape2.Width = 4.39 * 72;
shape2.Height = 4.53 * 72;
ITextBody textFrame2 = shape2.TextBody;
//Instance to hold paragraphs in textframe
IParagraphs paragraphs2 = textFrame2.Paragraphs;
IParagraph paragraph2 = paragraphs2.Add();
ITextPart textpart2 = paragraph2.AddTextPart();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart2.Text = "Lorem ipsum dolor sit amet, lacus amet amet ultricies. Quisque mi venenatis morbi libero, orci dis, mi ut et class porta, massa ligula magna enim, aliquam orci vestibulum tempus.";
textpart2.Font.FontName = "Helvetica CE 35 Thin";
textpart2.Font.FontSize = 16;
IParagraph paragraph3 = paragraphs2.Add();
textpart2 = paragraph3.AddTextPart();
paragraph3.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart2.Text = "Turpis facilisis vitae consequat, cum a a, turpis dui consequat massa in dolor per, felis non amet.";
textpart2.Font.FontName = "Helvetica CE 35 Thin";
textpart2.Font.FontSize = 16;
IParagraph paragraph4 = paragraphs2.Add();
textpart2 = paragraph4.AddTextPart();
paragraph4.HorizontalAlignment = HorizontalAlignmentType.Left;
textpart2.Text = "Auctor eleifend in omnis elit vestibulum, donec non elementum tellus est mauris, id aliquam, at lacus, arcu pretium proin lacus dolor et. Eu tortor, vel ultrices amet dignissim mauris vehicula.";
textpart2.Font.FontName = "Helvetica CE 35 Thin";
textpart2.Font.FontSize = 16;
IShape shape3 = (IShape)slide2.Shapes[2];
slide2.Shapes.RemoveAt(2);
//Adds picture in the shape
string basePath = _hostingEnvironment.WebRootPath;
FileStream imageStream = new FileStream(basePath + @"/Images/Presentation/tablet.jpg", FileMode.Open, FileAccess.Read);
IPicture picture1 = slide2.Shapes.AddPicture(imageStream, 0.81 * 72, 1.96 * 72, 6.63 * 72, 4.43 * 72);
imageStream.Dispose();
}
# endregion
# region Slide4
private void CreateFourthSlide(IPresentation presentation)
{
ISlide slide4 = presentation.Slides.Add(SlideLayoutType.TwoContent);
IShape shape1 = slide4.Shapes[0] as IShape;
shape1.Left = 0.51 * 72;
shape1.Top = 0.34 * 72;
shape1.Width = 11.32 * 72;
shape1.Height = 1.06 * 72;
ITextBody textFrame1 = shape1.TextBody;
//Instance to hold paragraphs in textframe
IParagraphs paragraphs1 = textFrame1.Paragraphs;
paragraphs1.Add();
IParagraph paragraph1 = paragraphs1[0];
ITextPart textpart1 = paragraph1.AddTextPart();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Left;
//Assigns value to textpart
textpart1.Text = "Slide with Table";
textpart1.Font.FontName = "Helvetica CE 35 Thin";
IShape shape2 = slide4.Shapes[1] as IShape;
slide4.Shapes.Remove(shape2);
ITable table = (ITable)slide4.Shapes.AddTable(6, 6, 0.81 * 72, 2.14 * 72, 11.43 * 72, 3.8 * 72);
table.Rows[0].Height = 0.85 * 72;
table.Rows[1].Height = 0.42 * 72;
table.Rows[2].Height = 0.85 * 72;
table.Rows[3].Height = 0.85 * 72;
table.Rows[4].Height = 0.85 * 72;
table.Rows[5].Height = 0.85 * 72;
table.HasBandedRows = true;
table.HasHeaderRow = true;
table.HasBandedColumns = false;
table.BuiltInStyle = BuiltInTableStyle.MediumStyle2Accent1;
ICell cell1 = table.Rows[0].Cells[0];
ITextBody textFrame2 = cell1.TextBody;
IParagraph paragraph2 = textFrame2.Paragraphs.Add();
paragraph2.HorizontalAlignment = HorizontalAlignmentType.Center;
ITextPart textPart2 = paragraph2.AddTextPart();
textPart2.Text = "ID";
ICell cell2 = table.Rows[0].Cells[1];
ITextBody textFrame3 = cell2.TextBody;
IParagraph paragraph3 = textFrame3.Paragraphs.Add();
paragraph3.HorizontalAlignment = HorizontalAlignmentType.Center;
ITextPart textPart3 = paragraph3.AddTextPart();
textPart3.Text = "Company Name";
ICell cell3 = table.Rows[0].Cells[2];
ITextBody textFrame4 = cell3.TextBody;
IParagraph paragraph4 = textFrame4.Paragraphs.Add();
paragraph4.HorizontalAlignment = HorizontalAlignmentType.Center;
ITextPart textPart4 = paragraph4.AddTextPart();
textPart4.Text = "Contact Name";
ICell cell4 = table.Rows[0].Cells[3];
ITextBody textFrame5 = cell4.TextBody;
IParagraph paragraph5 = textFrame5.Paragraphs.Add();
paragraph5.HorizontalAlignment = HorizontalAlignmentType.Center;
ITextPart textPart5 = paragraph5.AddTextPart();
textPart5.Text = "Address";
ICell cell5 = table.Rows[0].Cells[4];
ITextBody textFrame6 = cell5.TextBody;
IParagraph paragraph6 = textFrame6.Paragraphs.Add();
paragraph6.HorizontalAlignment = HorizontalAlignmentType.Center;
ITextPart textPart6 = paragraph6.AddTextPart();
textPart6.Text = "City";
ICell cell6 = table.Rows[0].Cells[5];
ITextBody textFrame7 = cell6.TextBody;
IParagraph paragraph7 = textFrame7.Paragraphs.Add();
paragraph7.HorizontalAlignment = HorizontalAlignmentType.Center;
ITextPart textPart7 = paragraph7.AddTextPart();
textPart7.Text = "Country";
cell1 = table.Rows[1].Cells[0];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "1";
cell1 = table.Rows[1].Cells[1];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "New Orleans Cajun Delights";
cell1 = table.Rows[1].Cells[2];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Shelley Burke";
cell1 = table.Rows[1].Cells[3];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "P.O. Box 78934";
cell1 = table.Rows[1].Cells[4];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "New Orleans";
cell1 = table.Rows[1].Cells[5];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "USA";
cell1 = table.Rows[2].Cells[0];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "2";
cell1 = table.Rows[2].Cells[1];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Cooperativa de Quesos 'Las Cabras";
cell1 = table.Rows[2].Cells[2];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Antonio del Valle Saavedra";
cell1 = table.Rows[2].Cells[3];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Calle del Rosal 4";
cell1 = table.Rows[2].Cells[4];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Oviedo";
cell1 = table.Rows[2].Cells[5];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Spain";
cell1 = table.Rows[3].Cells[0];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "3";
cell1 = table.Rows[3].Cells[1];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Mayumi";
cell1 = table.Rows[3].Cells[2];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Mayumi Ohno";
cell1 = table.Rows[3].Cells[3];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "92 Setsuko Chuo-ku";
cell1 = table.Rows[3].Cells[4];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Osaka";
cell1 = table.Rows[3].Cells[5];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Japan";
cell1 = table.Rows[4].Cells[0];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "4";
cell1 = table.Rows[4].Cells[1];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Pavlova, Ltd.";
cell1 = table.Rows[4].Cells[2];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Ian Devling";
cell1 = table.Rows[4].Cells[3];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "74 Rose St. Moonie Ponds";
cell1 = table.Rows[4].Cells[4];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Melbourne";
cell1 = table.Rows[4].Cells[5];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Australia";
cell1 = table.Rows[5].Cells[0];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "5";
cell1 = table.Rows[5].Cells[1];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Specialty Biscuits, Ltd.";
cell1 = table.Rows[5].Cells[2];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Peter Wilson";
cell1 = table.Rows[5].Cells[3];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "29 King's Way";
cell1 = table.Rows[5].Cells[4];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "Manchester";
cell1 = table.Rows[5].Cells[5];
textFrame1 = cell1.TextBody;
paragraph1 = textFrame1.Paragraphs.Add();
paragraph1.HorizontalAlignment = HorizontalAlignmentType.Center;
textpart1 = paragraph1.AddTextPart();
textpart1.Text = "UK";
slide4.Shapes.RemoveAt(1);
}
#endregion
#endregion
}
}

Просмотреть файл

@ -1,102 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public IActionResult SlideTransition()
{
return View();
}
[HttpPost]
public ActionResult SlideTransition(string Browser)
{
//Opens the presentation document as stream
string basePath = _hostingEnvironment.WebRootPath;
FileStream fileStreamInput = new FileStream(basePath + @"/Presentation/Transition.pptx", FileMode.Open, FileAccess.Read);
IPresentation presentation = Syncfusion.Presentation.Presentation.Open(fileStreamInput);
//PowerPoint instance is Created.
//Method call to create slides
CreateTransition(presentation);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "Transition.pptx";
return fileStreamResult;
}
#region Slide1
private void CreateTransition(IPresentation presentation)
{
//Get the first slide from the presentation
ISlide slide1 = presentation.Slides[0];
// Add the 'Wheel' transition effect to the first slide
slide1.SlideTransition.TransitionEffect = Syncfusion.Presentation.SlideTransition.TransitionEffect.Wheel;
// Get the second slide from the presentation
ISlide slide2 = presentation.Slides[1];
// Add the 'Checkerboard' transition effect to the second slide
slide2.SlideTransition.TransitionEffect = Syncfusion.Presentation.SlideTransition.TransitionEffect.Checkerboard;
// Add the subtype to the transition effect
slide2.SlideTransition.TransitionEffectOption = Syncfusion.Presentation.SlideTransition.TransitionEffectOption.Across;
// Apply the value to transition mouse on click parameter
slide2.SlideTransition.TriggerOnClick = true;
// Get the third slide from the presentation
ISlide slide3 = presentation.Slides[2];
// Add the 'Orbit' transition effect for slide
slide3.SlideTransition.TransitionEffect = Syncfusion.Presentation.SlideTransition.TransitionEffect.Orbit;
// Add the speed for transition
slide3.SlideTransition.Speed = Syncfusion.Presentation.SlideTransition.TransitionSpeed.Fast;
// Get the fourth slide from the presentation
ISlide slide4 = presentation.Slides[3];
// Add the 'Uncover' transition effect to the slide
slide4.SlideTransition.TransitionEffect = Syncfusion.Presentation.SlideTransition.TransitionEffect.Uncover;
// Apply the value to advance on time for slide
slide4.SlideTransition.TriggerOnTimeDelay = true;
// Assign the advance on time value
slide4.SlideTransition.TimeDelay = 5;
// Get the fifth slide from the presentation
ISlide slide5 = presentation.Slides[4];
// Add the 'PageCurlDouble' transition effect to the slide
slide5.SlideTransition.TransitionEffect = Syncfusion.Presentation.SlideTransition.TransitionEffect.PageCurlDouble;
// Add the duration value for the transition effect
slide5.SlideTransition.Duration = 5;
}
#endregion
}
}

Просмотреть файл

@ -1,125 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using Microsoft.AspNetCore.Mvc;
using System.IO;
using Syncfusion.Presentation;
using Microsoft.AspNetCore.Hosting;
using Syncfusion.OfficeChart;
using Syncfusion.Drawing;
namespace samplebrowser.Controllers
{
public partial class PresentationController : Controller
{
public IActionResult SmartArt()
{
return View();
}
[HttpPost]
public ActionResult SmartArt(string Browser)
{
IPresentation presentation = Syncfusion.Presentation.Presentation.Create();
//New Instance of PowerPoint is Created.[Equivalent to launching MS PowerPoint with no slides].
//Method call to edit slides
CreateSlide1(presentation);
CreateSlide2(presentation);
CreateSlide3(presentation);
CreateSlide4(presentation);
MemoryStream ms = new MemoryStream();
//Saves the presentation to the memory stream.
presentation.Save(ms);
//Set the position of the stream to beginning.
ms.Position = 0;
//Initialize the file stream to download the presentation.
FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
//Set the file name.
fileStreamResult.FileDownloadName = "SmartArt.pptx";
return fileStreamResult;
}
#region Slide
#region Slide1
#region Slide1
private void CreateSlide1(IPresentation presentation)
{
ISlide slide1 = presentation.Slides.Add(SlideLayoutType.Blank);
ISmartArt smartArt = slide1.Shapes.AddSmartArt(SmartArtType.BasicBlockList, 100, 100, 640, 427);
ISmartArtNode node1 = smartArt.Nodes[0];
node1.TextBody.AddParagraph("One");
ISmartArtNode node2 = smartArt.Nodes[1];
node2.TextBody.AddParagraph("Two");
ISmartArtNode node3 = smartArt.Nodes[2];
node3.TextBody.AddParagraph("Three");
ISmartArtNode node4 = smartArt.Nodes[3];
node4.TextBody.AddParagraph("Four");
ISmartArtNode node5 = smartArt.Nodes[4];
node5.TextBody.AddParagraph("Five");
}
#endregion
# region Slide2
private void CreateSlide2(IPresentation presentation)
{
ISlide slide = presentation.Slides.Add(SlideLayoutType.Blank);
ISmartArt smartArt = slide.Shapes.AddSmartArt(SmartArtType.StepUpProcess, 100, 100, 640, 427);
ISmartArtNode node1 = smartArt.Nodes[0];
node1.TextBody.AddParagraph("First");
ISmartArtNode node2 = smartArt.Nodes[1];
node2.TextBody.AddParagraph("Second");
ISmartArtNode node3 = smartArt.Nodes[2];
node3.TextBody.AddParagraph("Three");
}
#endregion
# region Slide3
private void CreateSlide3(IPresentation presentation)
{
ISlide slide = presentation.Slides.Add(SlideLayoutType.Blank);
ISmartArt smartArt = slide.Shapes.AddSmartArt(SmartArtType.BasicCycle, 100, 100, 640, 427);
ISmartArtNode node1 = smartArt.Nodes[0];
node1.TextBody.AddParagraph("Requirement");
ISmartArtNode node2 = smartArt.Nodes[1];
node2.TextBody.AddParagraph("Analyzing");
ISmartArtNode node3 = smartArt.Nodes[2];
node3.TextBody.AddParagraph("Estimation");
ISmartArtNode node4 = smartArt.Nodes[3];
node4.TextBody.AddParagraph("Implementing");
ISmartArtNode node5 = smartArt.Nodes[4];
node5.TextBody.AddParagraph("Testing");
}
#endregion
# region Slide4
private void CreateSlide4(IPresentation presentation)
{
ISlide slide = presentation.Slides.Add(SlideLayoutType.Blank);
ISmartArt smartArt = slide.Shapes.AddSmartArt(SmartArtType.Hierarchy, 100, 100, 640, 427);
ISmartArtNode node1 = smartArt.Nodes[0];
node1.TextBody.AddParagraph("Grand Father");
ISmartArtNode childNode1 = node1.ChildNodes[0];
childNode1.TextBody.AddParagraph("Son1");
ISmartArtNode childNode2 = node1.ChildNodes[1];
childNode2.TextBody.AddParagraph("Son2");
ISmartArtNode childnode1 = childNode1.ChildNodes[0];
childnode1.TextBody.AddParagraph("Son1");
ISmartArtNode childnode2 = childNode1.ChildNodes[1];
childnode2.TextBody.AddParagraph("Son2");
ISmartArtNode childnode2s1 = childNode2.ChildNodes[0];
childnode2s1.TextBody.AddParagraph("Son1");
}
#endregion
#endregion
#endregion
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -1,30 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2020.
// Copyright Syncfusion Inc. 2001-2020. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using samplebrowser.Helpers;
using Microsoft.AspNetCore.Hosting;
namespace samplebrowser.Controllers
{
public class SourceCodeTabController : Controller
{
private IHostingEnvironment _appEnv;
public SourceCodeTabController(IHostingEnvironment appEnv)
{
_appEnv = appEnv;
}
public ActionResult Index(string file)
{
return Content(new SourceTabActionResult(file, "false", _appEnv).getContent(_appEnv));
}
}
}

Просмотреть файл

@ -1,279 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2018.
// Copyright Syncfusion Inc. 2001-2018. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.XlsIO;
using Syncfusion.Drawing;
using System.Globalization;
using System.IO;
namespace samplebrowser.Controllers.XlsIO
{
public partial class XlsIOController : Controller
{
#region Constants
string[] _columnNames;
private List<EmployeeDetails> _employeeAttendanceList;
#endregion
//
// GET: /AttendanceTracker/
public ActionResult AttendanceTracker(string button)
{
_columnNames = new string[] { "Employee Name", "Supervisor", "Present Count", "Leave Count", "Absent Count", "Unplanned %", "Planned %" };
if (button == null)
return View();
AttendanceDetailsGenerator attendanceDetailsGenerator = new AttendanceDetailsGenerator();
_employeeAttendanceList = attendanceDetailsGenerator.GetEmployeeAttendanceDetails(2019, 01);
//New instance of XlsIO is created.[Equivalent to launching Microsoft Excel with no workbooks open].
//The instantiation process consists of two steps.
//Step 1 : Instantiate the spreadsheet creation engine.
#region Workbook Initialize
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.EnableIncrementalFormula = true;
application.DefaultVersion = ExcelVersion.Excel2016;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet worksheet = workbook.Worksheets[0];
DateTime dateTime = DateTime.Now;
string monthName = dateTime.ToString("MMM", CultureInfo.InvariantCulture);
worksheet.Name = monthName + "-" + dateTime.Year;
CreateHeaderRow(worksheet);//Format header row
FillAttendanceDetails(worksheet);
ApplyConditionFormatting(worksheet);
#region Apply Styles
worksheet.Range["A1:AL1"].RowHeight = 24;
worksheet.Range["A2:AL31"].RowHeight = 20;
worksheet.Range["A1:B1"].ColumnWidth = 20;
worksheet.Range["C1:G1"].ColumnWidth = 16;
worksheet.Range["H1:AL31"].ColumnWidth = 4;
worksheet.Range["A1:AL31"].CellStyle.Font.Bold = true;
worksheet.Range["A1:AL31"].CellStyle.Font.Size = 12;
worksheet.Range["A2:AL31"].CellStyle.Font.RGBColor = Color.FromArgb(64, 64, 64);
worksheet.Range["A1:AL31"].CellStyle.VerticalAlignment = ExcelVAlign.VAlignCenter;
worksheet.Range["A1:AL1"].CellStyle.Font.Color = ExcelKnownColors.White;
worksheet.Range["A1:AL1"].CellStyle.FillBackgroundRGB = Color.FromArgb(58, 56, 56);
worksheet.Range["A1:B31"].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignLeft;
worksheet.Range["C2:G31"].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignCenter;
worksheet.Range["H1:AL31"].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignCenter;
worksheet.Range["A2:B31"].CellStyle.IndentLevel = 1;
worksheet.Range["A1:G1"].CellStyle.IndentLevel = 1;
worksheet.Range["A1:AL1"].BorderAround(ExcelLineStyle.Medium, Color.LightGray);
worksheet.Range["A1:AL1"].BorderInside(ExcelLineStyle.Medium, Color.LightGray);
worksheet.Range["A2:G31"].BorderAround(ExcelLineStyle.Medium, Color.LightGray);
worksheet.Range["A2:G31"].BorderInside(ExcelLineStyle.Medium, Color.LightGray);
worksheet.Range["H2:AL31"].BorderInside(ExcelLineStyle.Medium, ExcelKnownColors.White);
#endregion
#endregion
try
{
MemoryStream ms = new MemoryStream();
workbook.SaveAs(ms);
ms.Position = 0;
return File(ms, "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "AttendanceTracker.xlsx");
}
catch (Exception)
{
}
// Close the workbook
workbook.Close();
excelEngine.Dispose();
return View();
}
#region HelperMethods
/// <summary>
/// Apply the conditonal format using workbook
/// </summary>
/// <param name="worksheet">worksheet used to get the range and set the conditional formats</param>
private void ApplyConditionFormatting(IWorksheet worksheet)
{
IConditionalFormats statusCondition = worksheet["H2:AL31"].ConditionalFormats;
IConditionalFormat leaveCondition = statusCondition.AddCondition();
leaveCondition.FormatType = ExcelCFType.CellValue;
leaveCondition.Operator = ExcelComparisonOperator.Equal;
leaveCondition.FirstFormula = "\"L\"";
leaveCondition.BackColorRGB = Color.FromArgb(253, 167, 92);
IConditionalFormat absentCondition = statusCondition.AddCondition();
absentCondition.FormatType = ExcelCFType.CellValue;
absentCondition.Operator = ExcelComparisonOperator.Equal;
absentCondition.FirstFormula = "\"A\"";
absentCondition.BackColorRGB = Color.FromArgb(255, 105, 124);
IConditionalFormat presentCondition = statusCondition.AddCondition();
presentCondition.FormatType = ExcelCFType.CellValue;
presentCondition.Operator = ExcelComparisonOperator.Equal;
presentCondition.FirstFormula = "\"P\"";
presentCondition.BackColorRGB = Color.FromArgb(67, 233, 123);
IConditionalFormat weekendCondition = statusCondition.AddCondition();
weekendCondition.FormatType = ExcelCFType.CellValue;
weekendCondition.Operator = ExcelComparisonOperator.Equal;
weekendCondition.FirstFormula = "\"WE\"";
weekendCondition.BackColorRGB = Color.FromArgb(240, 240, 240);
IConditionalFormats presentSummaryCF = worksheet["C2:C31"].ConditionalFormats;
IConditionalFormat presentCountCF = presentSummaryCF.AddCondition();
presentCountCF.FormatType = ExcelCFType.DataBar;
IDataBar dataBar = presentCountCF.DataBar;
dataBar.BarColor = Color.FromArgb(61, 242, 142);
IConditionalFormats leaveSummaryCF = worksheet["D2:D31"].ConditionalFormats;
IConditionalFormat leaveCountCF = leaveSummaryCF.AddCondition();
leaveCountCF.FormatType = ExcelCFType.DataBar;
dataBar = leaveCountCF.DataBar;
dataBar.BarColor = Color.FromArgb(242, 71, 23);
IConditionalFormats absentSummaryCF = worksheet["E2:E31"].ConditionalFormats;
IConditionalFormat absentCountCF = absentSummaryCF.AddCondition();
absentCountCF.FormatType = ExcelCFType.DataBar;
dataBar = absentCountCF.DataBar;
dataBar.BarColor = Color.FromArgb(255, 10, 69);
IConditionalFormats unplannedSummaryCF = worksheet["F2:F31"].ConditionalFormats;
IConditionalFormat unplannedCountCF = unplannedSummaryCF.AddCondition();
unplannedCountCF.FormatType = ExcelCFType.DataBar;
dataBar = unplannedCountCF.DataBar;
dataBar.MaxPoint.Type = ConditionValueType.HighestValue;
dataBar.BarColor = Color.FromArgb(142, 142, 142);
IConditionalFormats plannedSummaryCF = worksheet["G2:G31"].ConditionalFormats;
IConditionalFormat plannedCountCF = plannedSummaryCF.AddCondition();
plannedCountCF.FormatType = ExcelCFType.DataBar;
dataBar = plannedCountCF.DataBar;
dataBar.MaxPoint.Type = ConditionValueType.HighestValue;
dataBar.BarColor = Color.FromArgb(56, 136, 254);
}
/// <summary>
/// Used to fill the attendance details
/// </summary>
/// <param name="worksheet">worksheet used to get the range and fill attendance details</param>
private void FillAttendanceDetails(IWorksheet worksheet)
{
int rowIndex = 2;
foreach (EmployeeDetails empDetails in _employeeAttendanceList)
{
worksheet["A" + rowIndex].Text = empDetails.Name;
worksheet["B" + rowIndex].Text = empDetails.Supervisor;
for (int colIndex = 0; colIndex < empDetails.Attendances.Count; colIndex++)
{
worksheet[rowIndex, colIndex + 8].Text = empDetails.Attendances[colIndex];
}
rowIndex++;
}
//Data validation for list
IDataValidation validation = worksheet.Range["H2:AL31"].DataValidation;
validation.ListOfValues = new string[] { "P", "A", "L", "WE" };
worksheet["C2:C31"].Formula = "=CountIf('H2:AL2',\"P\")";
worksheet["D2:D31"].Formula = "=CountIf('H2:AL2',\"L\")";
worksheet["E2:E31"].Formula = "=CountIf('H2:AL2',\"A\")";
worksheet["F2:F31"].Formula = "=E2/(C2+D2+E2)";
worksheet["G2:G31"].Formula = "=D2/(C2+D2+E2)";
worksheet["F2:G31"].NumberFormat = ".00 %";
}
private void CreateHeaderRow(IWorksheet worksheet)
{
for (int i = 0; i < _columnNames.Length; i++)
{
worksheet[1, i + 1].Text = _columnNames[i];
}
worksheet["H1"].DateTime = new DateTime(2019, 1, 1);
worksheet["I1:AL1"].Formula = "=H1+1";
worksheet["H1:AL1"].NumberFormat = "d";
}
#endregion
}
#region HelperClasses
/// <summary>
/// Returrn the list of employee details
/// </summary>
public class EmployeeDetails
{
public string Name { get; set; }
public string Supervisor { get; set; }
public List<string> Attendances { get; set; }
public EmployeeDetails()
{
Attendances = new List<string>();
}
}
/// <summary>
/// Get the attendance details and return the list
/// </summary>
public class AttendanceDetailsGenerator
{
private List<EmployeeDetails> _employeeAttendanceList;
string[] _dayStatus;
string[] _supervisor;
string[] _employeeNames;
public AttendanceDetailsGenerator()
{
_employeeAttendanceList = new List<EmployeeDetails>();
_dayStatus = new string[] { "P", "L", "P", "A", "P" };
_supervisor = new string[] { "Mary Saveley", "Liz Nixon", "Liu Wong", "Michael Holz" };
_employeeNames = new string[] { "Maria Anders", "Ana Trujillo", "Antonio Moreno", "Thomas Hardy", "Christina Berglund", "Hanna Moos",
"Frederique Citeaux", "Martin Sommer", "Laurence Lebihan", "Elizabeth Lincoln", "Victoria Ashworth", "Patricio Simpson",
"Francisco Chang", "Yang Wang", "Pedro Afonso", "Elizabeth Brown", "Steve Rogers", "Ann Devon",
"Philip Cramer", "Daniel Tonini", "Annette Roulet", "John Smith", "Maria Larsson", "Howard Stark",
"Peter Franken", "Aria Cruz", "Philip Gary", "Fran Willamson", "Howard Snyde", "Mario Pontes"};
}
public List<EmployeeDetails> GetEmployeeAttendanceDetails(int year, int month)
{
Random rnd = new Random();
for (int i = 0; i < 30; i++)
{
EmployeeDetails details = new EmployeeDetails();
details.Name = _employeeNames[i];
details.Supervisor = _supervisor[rnd.Next(_supervisor.Length)];
int numberOfDays = DateTime.DaysInMonth(year, month);
for (int j = 0; j < numberOfDays; j++)
{
DateTime date = new DateTime(year, month, j + 1);
if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
details.Attendances.Add("WE");
else
details.Attendances.Add(_dayStatus[rnd.Next(_dayStatus.Length)]);
}
_employeeAttendanceList.Add(details);
}
return _employeeAttendanceList;
}
}
#endregion
}

Просмотреть файл

@ -1,281 +0,0 @@
#region Copyright Syncfusion Inc. 2001-2017.
// Copyright Syncfusion Inc. 2001-2017. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.XlsIO;
using Syncfusion.Drawing;
using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using MVCSampleBrowser.Models;
namespace MVCSampleBrowser.Controllers
{
public partial class XlsIOController : Controller
{
#region Getting Started
private readonly IHostingEnvironment _hostingEnvironment;
public XlsIOController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
#endregion
public ActionResult AutoFilter(string id, string FilterType, string button, string colorsList, string rdb1, string rdb3, string iconText, string iconSetTypeList, string field, string checkbox)
{
string basePath = _hostingEnvironment.WebRootPath;
if (FilterType == null)
{
ViewBag.datasource = icons.GetSymbols();
ViewBag.datasource2 = icons.GetRating();
ViewBag.datasource3 = icons.GetArrows();
return View();
}
else if (button == "Input Template")
{
//Step 1 : Instantiate the spreadsheet creation engine.
ExcelEngine excelEngine = new ExcelEngine();
//Step 2 : Instantiate the excel application object.
IApplication application = excelEngine.Excel;
IWorkbook workbook;
if (FilterType == "Advanced Filter")
{
FileStream inputStream = new FileStream(basePath + @"/XlsIO/AdvancedFilterData.xlsx", FileMode.Open, FileAccess.Read);
workbook = application.Workbooks.Open(inputStream);
}
else if(FilterType == "Color Filter")
{
FileStream inputStream = new FileStream(basePath + @"/XlsIO/FilterData_Color.xlsx", FileMode.Open, FileAccess.Read);
workbook = application.Workbooks.Open(inputStream);
}
else if (FilterType == "Icon Filter")
{
FileStream inputStream = new FileStream(basePath + @"/XlsIO/IconFilterData.xlsx", FileMode.Open, FileAccess.Read);
workbook = application.Workbooks.Open(inputStream);
}
else
{
FileStream inputStream = new FileStream(basePath + @"/XlsIO/FilterData.xlsx", FileMode.Open, FileAccess.Read);
workbook = application.Workbooks.Open(inputStream);
}
MemoryStream ms = new MemoryStream();
workbook.SaveAs(ms);
ms.Position = 0;
return File(ms, "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "InputTemplate.xlsx");
}
else
{
string fileName = null;
//Step 1 : Instantiate the spreadsheet creation engine.
ExcelEngine excelEngine = new ExcelEngine();
//Step 2 : Instantiate the excel application object.
IApplication application = excelEngine.Excel;
IWorkbook workbook;
if (FilterType == "Advanced Filter")
{
FileStream inputStream = new FileStream(basePath + @"/XlsIO/AdvancedFilterData.xlsx", FileMode.Open, FileAccess.Read);
workbook = application.Workbooks.Open(inputStream);
}
else if (FilterType == "Color Filter")
{
FileStream inputStream = new FileStream(basePath + @"/XlsIO/FilterData_Color.xlsx", FileMode.Open, FileAccess.Read);
workbook = application.Workbooks.Open(inputStream);
}
else if (FilterType == "Icon Filter")
{
FileStream inputStream = new FileStream(basePath + @"/XlsIO/IconFilterData.xlsx", FileMode.Open, FileAccess.Read);
workbook = application.Workbooks.Open(inputStream);
}
else
{
FileStream inputStream = new FileStream(basePath + @"/XlsIO/FilterData.xlsx", FileMode.Open, FileAccess.Read);
workbook = application.Workbooks.Open(inputStream);
}
IWorksheet sheet = workbook.Worksheets[0];
if (FilterType != "Advanced Filter")
sheet.AutoFilters.FilterRange = sheet.Range[1, 1, 49, 3];
switch(FilterType)
{
case "Custom Filter":
fileName = "CustomFilter.xlsx";
IAutoFilter filter1 = sheet.AutoFilters[0];
filter1.IsAnd = false;
filter1.FirstCondition.ConditionOperator = ExcelFilterCondition.Equal;
filter1.FirstCondition.DataType = ExcelFilterDataType.String;
filter1.FirstCondition.String = "Owner";
filter1.SecondCondition.ConditionOperator = ExcelFilterCondition.Equal;
filter1.SecondCondition.DataType = ExcelFilterDataType.String;
filter1.SecondCondition.String = "Sales Representative";
break;
case "Text Filter":
fileName = "TextFilter.xlsx";
IAutoFilter filter2 = sheet.AutoFilters[0];
filter2.AddTextFilter(new string[] { "Owner", "Sales Representative", "Sales Associate" });
break;
case "DateTime Filter":
fileName = "DateTimeFilter.xlsx";
IAutoFilter filter3 = sheet.AutoFilters[1];
filter3.AddDateFilter(new DateTime(2004, 9, 1, 1, 0, 0, 0), DateTimeGroupingType.month);
filter3.AddDateFilter(new DateTime(2011, 1, 1, 1, 0, 0, 0), DateTimeGroupingType.year);
break;
case "Dynamic Filter":
fileName = "DynamicFilter.xlsx";
IAutoFilter filter4 = sheet.AutoFilters[1];
filter4.AddDynamicFilter(DynamicFilterType.Quarter1);
break;
case "Color Filter":
fileName = "ColorFilter.xlsx";
#region ColorFilter
sheet.AutoFilters.FilterRange = sheet["A1:C49"];
Syncfusion.Drawing.Color color = Syncfusion.Drawing.Color.Empty;
switch (colorsList.ToLower())
{
case "red":
color = Color.Red;
break;
case "blue":
color = Color.Blue;
break;
case "green":
color = Color.Green;
break;
case "yellow":
color = Color.Yellow;
break;
case "empty":
color = Color.Empty;
break;
}
if (rdb3 == "FontColor")
{
IAutoFilter filter = sheet.AutoFilters[2];
filter.AddColorFilter(color, ExcelColorFilterType.FontColor);
}
else
{
IAutoFilter filter = sheet.AutoFilters[0];
filter.AddColorFilter(color, ExcelColorFilterType.CellColor);
}
#endregion
break;
case "Icon Filter":
fileName = "IconFilter.xlsx";
#region IconFilter
sheet.AutoFilters.FilterRange = sheet["A4:D44"];
int filterIndex = 0;
ExcelIconSetType iconset = ExcelIconSetType.FiveArrows;
int iconId = 0;
switch (iconSetTypeList)
{
case "ThreeSymbols":
iconset = ExcelIconSetType.ThreeSymbols;
filterIndex = 3;
break;
case "FourRating":
iconset = ExcelIconSetType.FourRating;
filterIndex = 1;
break;
case "FiveArrows":
iconset = ExcelIconSetType.FiveArrows;
filterIndex = 2;
break;
}
switch (iconText)
{
case "0":
//Do nothing
break;
case "1":
iconId = 1;
break;
case "2":
iconId = 2;
break;
case "3":
if (iconSetTypeList.Equals("ThreeSymbols"))
iconset = (ExcelIconSetType)(-1);
else
iconId = 3;
break;
case "4":
if (iconSetTypeList.Equals("FourRating"))
iconset = (ExcelIconSetType)(-1);
else
iconId = 4;
break;
case "5":
iconset = (ExcelIconSetType)(-1);
break;
}
IAutoFilter filter5 = sheet.AutoFilters[filterIndex];
filter5.AddIconFilter(iconset, iconId);
#endregion
break;
case "Advanced Filter":
fileName = "AdvancedFilter.xlsx";
#region AdvancedFilter
IRange filterRange = sheet.Range["A8:G51"];
IRange criteriaRange = sheet.Range["A2:B5"];
if (rdb1 == "FilterIN")
{
sheet.AdvancedFilter(ExcelFilterAction.FilterInPlace, filterRange, criteriaRange, null, checkbox == "Unique");
}
else if (rdb1 == "FilterCopy")
{
IRange range = sheet.Range["I7:O7"];
range.Merge();
range.Text = "FilterCopy";
range.CellStyle.Font.RGBColor = Syncfusion.Drawing.Color.FromArgb(0, 112, 192);
range.HorizontalAlignment = ExcelHAlign.HAlignCenter;
range.CellStyle.Font.Bold = true;
IRange copyRange = sheet.Range["I8"];
sheet.AdvancedFilter(ExcelFilterAction.FilterCopy, filterRange, criteriaRange, copyRange, checkbox == "Unique");
}
break;
#endregion
}
workbook.Version = ExcelVersion.Excel2016;
MemoryStream result = new MemoryStream();
workbook.SaveAs(result);
result.Position = 0;
return File(result, "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
//Close the workbook.
workbook.Close();
excelEngine.Dispose();
return View();
}
}
}
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше