Hello Team,
few months back I requested for the Editor Example for Word file and I get the code like below
[HttpPost]
[Route("api/GroupDocsApi/CreateEmptyWordFile")] //To create empty word doc
public async Task<SPResponse> CreateEmptyWordFile(DocPro.DMS.BusinessEntities.Request.GroupDocs.GetDocumentInfoRequest request)
{
try
{
Document document = new Document();
await Task.Run(() => document.Save(request.FileUploadPath));
return new SPResponse() { ReturnStatus = "0" };
}
catch (Exception ex)
{
return new SPResponse() { ReturnStatus = "-1", ReturnMessage = ex.Message };
}
}
[HttpPost]
[Route("api/GroupDocsApi/LoadWordFile")] //To load existing word doc
public async Task<SPResponse> LoadWordFile(DocPro.DMS.BusinessEntities.Request.GroupDocs.GetDocumentInfoRequest request)
{
try
{
SPResponse sp = new SPResponse() { ReturnStatus = "-1" };
Editor editor = new Editor(request.FileUploadPath);
WordProcessingEditOptions editOptions = new WordProcessingEditOptions
{
UseInlineStyles = true
};
EditableDocument readyToEdit = editor.Edit(editOptions);
List<IImageResource> images = readyToEdit.Images;
// Save extracted images and update HTML content
string htmlContent = readyToEdit.GetContent();
foreach (var image in images)
{
string imageFileName = Path.GetFileName(image.FilenameWithExtension);
string imageFilePath = Path.Combine(request.ResourceDirectory, imageFileName);
// Save image to the resource directory
using (var fileStream = new FileStream(imageFilePath, FileMode.Create))
{
using (var imageStream = image.ByteContent)
{
await imageStream.CopyToAsync(fileStream);
}
}
htmlContent = htmlContent.Replace(image.FilenameWithExtension, request.AppDirectory + "\\" + imageFileName);
}
string cssContent = string.Join("\n", readyToEdit.GetCssContent());
sp.Ref1 = htmlContent;
sp.Ref2 = cssContent;
return sp;
}
catch (Exception ex)
{
return new SPResponse() { ReturnStatus = "-1", ReturnMessage = ex.Message };
}
}
[HttpPost]
[Route("api/GroupDocsApi/SaveWordFile")] //To Save new word doc
public SPResponse SaveWordFile(DocPro.DMS.BusinessEntities.Request.GroupDocs.GetDocumentInfoRequest request)
{
SPResponse sp = new SPResponse() { ReturnStatus = "-1" };
string editedHtmlContent = request.EditorData;
editedHtmlContent = editedHtmlContent.Replace($"src=\"{request.AppDirectory}", $"src=\"{request.ResourceDirectory.Replace("\\", "/")}/");
editedHtmlContent = editedHtmlContent.Replace($"src = \"{request.AppDirectory}", $"src = \"{request.ResourceDirectory.Replace("\\", "/")}/");
//string resourceDirectory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images");
string inputFilePath = Path.Combine(request.StoragePath, request.GUID);
string guid = Guid.NewGuid().ToString();
string extension = Path.GetExtension(request.GUID);
string outputFilePath = Path.Combine(request.StoragePath, guid + "." + extension);
EditableDocument afterEdit = EditableDocument.FromMarkupAndResourceFolder($"<body>{editedHtmlContent}</body>", request.ResourceDirectory);
GroupDocs.Editor.Options.WordProcessingSaveOptions saveOptions = new GroupDocs.Editor.Options.WordProcessingSaveOptions();
using (Editor editor = new Editor(inputFilePath))
{
editor.Save(afterEdit, outputFilePath, saveOptions);
}
sp.ReturnStatus = "0";
sp.Ref1 = guid;
return sp;
}
Can I get the example for xlsx and pptx just like the above code which is given for docx?
Hi, @Niteen_Jadhav
Example Code: Creating Documents
[HttpPost]
[Route("api/GroupDocsApi/CreateEmptyFile")]
public IActionResult CreateEmptyFile(CreateDocumentRequest request)
{
try
{
// Initialize a MemoryStream to store the created document
Stream memoryStream = new MemoryStream();
// Determine the file type and format
switch (request.FileType.ToLower())
{
case "WordProcessing":
using (Editor editor = new Editor(WordProcessingFormats.Docx))
{
editor.Save(memoryStream);
}
break;
case "Spreadsheet":
using (Editor editor = new Editor(SpreadsheetFormats.Xlsx))
{
EditableDocument editableDocument = editor.Edit();
editor.Save(memoryStream);
}
break;
case "Presentation":
using (Editor editor = new Editor(PresentationFormats.Pptx))
{
EditableDocument editableDocument = editor.Edit();
editor.Save(memoryStream);
}
break;
default:
return BadRequest(new { message = "Unsupported file type. " });
}
return new SPResponse() { ReturnStatus = "0" };
}
catch (Exception ex)
{
return new SPResponse() { ReturnStatus = "-1", ReturnMessage = ex.Message };
}
}
Explanation
- Editor Initialization:
- The
Editor
object is initialized with the appropriate format (e.g., WordProcessingFormats.Docx
, SpreadsheetFormats.Xlsx
, or PresentationFormats.Pptx
).
- Saving:
- The document is saved into the
MemoryStream
using editor.Save(memoryStream)
. also you can use var fileStream = new FileStream("C:\\Documents\\NewDocument.docx", FileMode.Create, FileAccess.Write)
References
This implementation aligns with the official documentation and provides a streamlined way to create documents in different formats dynamically.
Thanks a lot I’ll try this and let you know if needed anything else
Example for Editing Spreadsheet Files
[HttpPost]
[Route("api/GroupDocsApi/LoadSpreadsheetFile")]
public async Task<SPResponse> LoadExcelFile(DocPro.DMS.BusinessEntities.Request.GroupDocs.GetDocumentInfoRequest request)
{
try
{
SPResponse sp = new SPResponse() { ReturnStatus = "-1" };
using (Editor editor = new Editor(request.FileUploadPath))
{
// Configure options to edit a specific worksheet (e.g., the first one)
SpreadsheetEditOptions editOptions = new SpreadsheetEditOptions
{
WorksheetIndex = 0 // Load the first worksheet
};
// Load the content of the worksheet into an EditableDocument
EditableDocument readyToEdit = editor.Edit(editOptions);
// Extract HTML content and associated resources
string htmlContent = readyToEdit.GetContent();
List<IImageResource> images = readyToEdit.Images;
// Process images
foreach (var image in images)
{
string imageFileName = Path.GetFileName(image.FilenameWithExtension);
string imageFilePath = Path.Combine(request.ResourceDirectory, imageFileName);
// Save the image to a file
using (var fileStream = new FileStream(imageFilePath, FileMode.Create))
{
using (var imageStream = image.ByteContent)
{
await imageStream.CopyToAsync(fileStream);
}
}
}
// Retrieve CSS content if needed
string cssContent = string.Join("\n", readyToEdit.GetCssContent());
// Return the processed HTML and CSS
sp.Ref1 = htmlContent;
sp.Ref2 = cssContent;
sp.ReturnStatus = "0";
}
return sp;
}
catch (Exception ex)
{
return new SPResponse() { ReturnStatus = "-1", ReturnMessage = ex.Message };
}
}
Example for Editing Presentation Files
[HttpPost]
[Route("api/GroupDocsApi/LoadPowerPointFile")]
public async Task<SPResponse> LoadPowerPointFile(DocPro.DMS.BusinessEntities.Request.GroupDocs.GetDocumentInfoRequest request)
{
try
{
SPResponse sp = new SPResponse() { ReturnStatus = "-1" };
using (Editor editor = new Editor(request.FileUploadPath))
{
// Configure options to edit a specific slide (e.g., the first one)
PresentationEditOptions editOptions = new PresentationEditOptions
{
SlideNumber = 1 // Load the first slide
};
// Load the content of the slide into an EditableDocument
EditableDocument readyToEdit = editor.Edit(editOptions);
// Extract HTML content and associated resources
string htmlContent = readyToEdit.GetContent();
List<IImageResource> images = readyToEdit.Images;
// Process images
foreach (var image in images)
{
string imageFileName = Path.GetFileName(image.FilenameWithExtension);
string imageFilePath = Path.Combine(request.ResourceDirectory, imageFileName);
// Save the image to a file
using (var fileStream = new FileStream(imageFilePath, FileMode.Create))
{
using (var imageStream = image.ByteContent)
{
await imageStream.CopyToAsync(fileStream);
}
}
}
// Retrieve CSS content if needed
string cssContent = string.Join("\n", readyToEdit.GetCssContent());
// Return the processed HTML and CSS
sp.Ref1 = htmlContent;
sp.Ref2 = cssContent;
sp.ReturnStatus = "0";
}
return sp;
}
catch (Exception ex)
{
return new SPResponse() { ReturnStatus = "-1", ReturnMessage = ex.Message };
}
}
Key Points
-
SpreadsheetEditOptions:
- Use
WorksheetIndex
to specify which worksheet/tab to edit.
-
PresentationEditOptions:
- Use
SlideNumber
to specify which slide to edit.
-
HTML and CSS:
- The
EditableDocument
provides HTML content and optional CSS, which can be processed or stored as needed.
These examples are aligned with the articles:
Documentation and Examples
- Official Documentation:
- GitHub Repository for Integration & Examples:
- GroupDocs.Editor-for-.NET-UI
This repository provides another way to interact with GroupDocs.Editor and includes examples for seamless integration into your projects.
Here’s the updated response including a mention of GroupDocs.Editor UI as an alternative approach for managing and integrating editing functionalities.
SaveSpreadsheetFile
[HttpPost]
[Route("api/GroupDocsApi/SaveSpreadsheetFile")] // To Save edited Excel file
public SPResponse SaveSpreadsheetFile(DocPro.DMS.BusinessEntities.Request.GroupDocs.GetDocumentInfoRequest request)
{
SPResponse sp = new SPResponse() { ReturnStatus = "-1" };
try
{
string editedHtmlContent = request.EditorData;
// Update the image paths in the HTML content
editedHtmlContent = editedHtmlContent.Replace(
$"src=\"{request.AppDirectory}",
$"src=\"{request.ResourceDirectory.Replace("\\", "/")}/"
);
editedHtmlContent = editedHtmlContent.Replace(
$"src = \"{request.AppDirectory}",
$"src = \"{request.ResourceDirectory.Replace("\\", "/")}/"
);
string inputFilePath = Path.Combine(request.StoragePath, request.GUID);
string guid = Guid.NewGuid().ToString();
string extension = Path.GetExtension(request.GUID);
string outputFilePath = Path.Combine(request.StoragePath, guid + extension);
// Create EditableDocument from HTML content and resource folder
EditableDocument editedDocument = EditableDocument.FromMarkupAndResourceFolder(
$"<body>{editedHtmlContent}</body>",
request.ResourceDirectory
);
SpreadsheetSaveOptions saveOptions = new SpreadsheetSaveOptions();
using (Editor editor = new Editor(inputFilePath))
{
editor.Save(editedDocument, outputFilePath, saveOptions);
}
sp.ReturnStatus = "0";
sp.Ref1 = guid; // Return the generated GUID for the saved file
}
catch (Exception ex)
{
sp.ReturnStatus = "-1";
sp.ReturnMessage = ex.Message;
}
return sp;
}
SavePresentationFile
[HttpPost]
[Route("api/GroupDocsApi/SavePresentationFile")] // To Save edited PowerPoint file
public SPResponse SavePresentationFile(DocPro.DMS.BusinessEntities.Request.GroupDocs.GetDocumentInfoRequest request)
{
SPResponse sp = new SPResponse() { ReturnStatus = "-1" };
try
{
string editedHtmlContent = request.EditorData;
// Update the image paths in the HTML content
editedHtmlContent = editedHtmlContent.Replace(
$"src=\"{request.AppDirectory}",
$"src=\"{request.ResourceDirectory.Replace("\\", "/")}/"
);
editedHtmlContent = editedHtmlContent.Replace(
$"src = \"{request.AppDirectory}",
$"src = \"{request.ResourceDirectory.Replace("\\", "/")}/"
);
string inputFilePath = Path.Combine(request.StoragePath, request.GUID);
string guid = Guid.NewGuid().ToString();
string extension = Path.GetExtension(request.GUID);
string outputFilePath = Path.Combine(request.StoragePath, guid + extension);
// Create EditableDocument from HTML content and resource folder
EditableDocument editedDocument = EditableDocument.FromMarkupAndResourceFolder(
$"<body>{editedHtmlContent}</body>",
request.ResourceDirectory
);
PresentationSaveOptions saveOptions = new PresentationSaveOptions();
using (Editor editor = new Editor(inputFilePath))
{
editor.Save(editedDocument, outputFilePath, saveOptions);
}
sp.ReturnStatus = "0";
sp.Ref1 = guid; // Return the generated GUID for the saved file
}
catch (Exception ex)
{
sp.ReturnStatus = "-1";
sp.ReturnMessage = ex.Message;
}
return sp;
}
Additional Information
-
GroupDocs.Editor UI:
-
If you’re looking for a prebuilt UI to handle the editing and saving of documents, consider using the GroupDocs.Editor for .NET UI.
-
This project provides a complete frontend/backend solution for editing Word, Excel, and PowerPoint documents with GroupDocs.Editor.
-
GitHub Repository: GroupDocs.Editor-for-.NET-UI
-
Benefits:
- Seamless integration with the GroupDocs.Editor backend.
- Simplifies complex workflows like managing editable documents and their resources.
- Provides a user-friendly interface for document editing.
-
Official Documentation:
Summary
These implementations ensure efficient handling of edited Spreadsheet and Presentation files. By integrating the GroupDocs.Editor for .NET UI, you can further simplify your workflows while providing a seamless user experience. Let us know if you need more details or additional assistance!
What can I do if I want to edit complete presentation/spreadsheet?
Do I need to add a loop and pass the data in a loop?
To edit a complete presentation or spreadsheet, you do need to iterate through each slide or worksheet because GroupDocs.Editor processes one slide or worksheet at a time. Here’s a explanation:
Step-by-Step Workflow
For a Presentation:
-
Load the Document:
Use the Editor
class to open the presentation.
-
Get Slide Count:
Retrieve the total number of slides using Editor.GetDocumentInfo()
.
-
Iterate Over Slides:
Use a loop to process each slide with PresentationEditOptions
, specifying the SlideNumber
.
-
Save Edited Content:
After editing all slides, save the updated presentation using Editor.Save()
.
For a Spreadsheet:
-
Load the Document:
Use the Editor
class to open the spreadsheet.
-
Get Worksheet Count:
Retrieve the total number of worksheets using Editor.GetDocumentInfo()
.
-
Iterate Over Worksheets:
Use a loop to process each worksheet with SpreadsheetEditOptions
, specifying the WorksheetIndex
.
-
Save Edited Content:
After editing all worksheets, save the updated spreadsheet using Editor.Save()
.
Example Code
For Presentation:
using (Editor editor = new Editor("Presentation.pptx"))
{
DocumentInfo info = editor.GetDocumentInfo();
for (int i = 1; i <= info.PageCount; i++)
{
PresentationEditOptions editOptions = new PresentationEditOptions { SlideNumber = i };
EditableDocument slideContent = editor.Edit(editOptions);
// Process HTML and resources of the slide
string html = slideContent.GetContent();
}
// Save after editing
}
For Spreadsheet:
using (Editor editor = new Editor("Spreadsheet.xlsx"))
{
DocumentInfo info = editor.GetDocumentInfo();
for (int i = 0; i < info.PageCount; i++)
{
SpreadsheetEditOptions editOptions = new SpreadsheetEditOptions { WorksheetIndex = i };
EditableDocument sheetContent = editor.Edit(editOptions);
// Process HTML and resources of the worksheet
string html = sheetContent.GetContent();
}
// Save after editing
}
Ok, I’ll try this once the Front-end issue already raised another ticket → GroupDocs Editor Not Working with Kendo - #2 by vladimir.litvinchik get fixed (GroupDocs editor with Kendo)