Spax EA best way to export diagrams into Word document - c#

Got an old module which is generates reports with data from sparx ea project.
There is a part where you need to insert diagrams as pictures in the document.
Now it looks like that
public static void copyDiagram(
EA.Diagram diagram,
EA.Repository eaRepository)
{
eaRepository.App.Project.PutDiagramImageOnClipboard(diagram.DiagramGUID, 0);
eaRepository.CloseDiagram(diagram.DiagramID);
}
copying it to clipboard, and after that there goes something like
currentDocumentRange.Paste()
Looks strange for me.
I think it's not really good to use clipboard like that, so I want to rewrite it in future.
So, only other function I found there looks like that PutDiagramImageToFile(diagrammGUID, path, type)
If there are no better option is it okay to create new file, after that get it by it's path insert into word document, and then delete it?
Or, maybe there are some other SparxEA function, which get image from diagram in byte[] format or like Image format?
What way is better?

I'm using this code (on a diagram wrapper class) to get the image of a diagram without having to use the clipboard.
This code is used primarily in a custom written document generator and is surprisingly fast.
/// <summary>
/// returns diagram image
/// </summary>
public Image image
{
get
{
EA.Project projectInterface = this.model.getWrappedModel().GetProjectInterface();
string diagramGUID = projectInterface.GUIDtoXML(this.wrappedDiagram.DiagramGUID);
string filename = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".png";
//save diagram image to file (format ".png")
projectInterface.PutDiagramImageToFile(diagramGUID, filename, 1);
//load the contents of the file into a memorystream
MemoryStream imageStream = new MemoryStream(File.ReadAllBytes(filename));
//then create the image from the memorystream.
//this allows us to delete the temporary file right after loading it.
//When using Image.FromFile the file would have been locked for the lifetime of the Image
Image diagramImage = Image.FromStream(imageStream);
//delete the temorary file
System.IO.File.Delete(filename);
return diagramImage;
}
}

Related

Accessing Images in PowerPoint file via VSTO Add-In (C#)

I am trying to build a PowerPoint add-in that will allow me to do a one-click optimization of the current presentation by removing unused master slides and converting huge 24-bit PNG files to slightly-compressed JPGs.
I have the first part handled already, and now I'm working on the images. Although I can easily find the Shape object containing the image, I cannot find a way to access the source image through the managed API. At best, I can copy the shape to the clipboard, which does give me the image but in a different format (MemoryBmp).
using PPTX = Microsoft.Office.Interop.PowerPoint;
...
foreach (PPTX.Slide slide in Globals.ThisAddIn.Application.ActivePresentation.Slides)
{
foreach (PPTX.Shape shape in slide.Shapes)
{
if (shape.Type == MsoShapeType.msoPicture)
{
// Now, how can I access the source image contained within this shape?
// I -can- copy it via the clipboard, like this:
shape.Copy();
System.Drawing.Image image = Clipboard.GetImage();
// ...but image's format reflects a MemoryBmp ImageFormat, as noted here:
// https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Advanced/ImageFormat.cs
// ...which doesn't help me determine if the source image is something that should be optimized.
}
}
}
Obviously, I can get to the images directly via other methods (e.g. accessing the contents of the file as a ZIP, or using OpenXML SDK), but I'm trying to perform all the steps from within the already-opened presentation (which means I can't update the open file). Any thoughts on how I can do this?
You could use a Microsoft.Office.Interop.PowerPoint.Shape Export function.
void Export(string PathName, PpShapeFormat Filter, int ScaleWidth = 0, int ScaleHeight = 0, PpExportMode ExportMode = PpExportMode.ppRelativeToSlide)
There is a very little documentation of this function.
I've found it in the Shape interface definition.
So your code would look something like:
shape.Export(<some_file>, PpShapeFormat.ppShapeFormatPNG);
More info on MSDN

How to Handle Multiple Image Uploads in ASP.NET MVC Website?

I am using dropzone.js to upload multiple images to a .NET MVC website. When the images come into the server, I resize them, save information to the database, and then save the actual image on the server in a folder. When I upload them one at a time this works, but if I do multiple uploads at once, I get this error every few uploads:
A generic error occurred in GDI+
Googling this seems that this is a generic error when you are unable to save a file as some other process is using the location. I assume that the multiple uploads are trying to save in the same folder at the same time and one dies. They are not the same filename.
How can I avoid this? Is there a way to have the threads wait for one to finish before it tries saving in the same folder? I'm wondering if there is a method that is like the await call where it waits until it can save.
Edit More Code
I can't copy my whole function as it's very long etc but the part that saves is the following:
//Now we will try saving the actual file. Generate the file name.
String savedFileName = PhotoTools.GenerateImageFileName(photo.image_base_file_name);
String thumbnailSavedFileName = PhotoTools.GenerateImageFileName(photo.image_base_file_name, true);
//Store the file path (directory) that we are going to save the image to.
String directoryToSave = Server.MapPath(Constants.ImageDirectory + $"/{house_id}");
//Create the directory. This function will not do anything if it already exists.
Directory.CreateDirectory(directoryToSave);
//Save the images to the filesystem.
mainImage.Save(Path.Combine(directoryToSave, savedFileName), ImageFormat.Jpeg);
thumbnailImage.Save(Path.Combine(directoryToSave, thumbnailSavedFileName), ImageFormat.Jpeg);
They should not be the same filename as the file name is created as such:
/// <summary>
/// Generates the base property image filename based on the passed in information.
/// </summary>
/// <param name="propName">The house name that we will use for the file name.</param>
/// <returns>The generated file name.</returns>
public static String GenerateBaseImageFileName(String propName)
{
//Save the current datetime to create the filename with.
DateTime now = DateTime.Now;
//Generate the name.
return $"{CommonTools.RemoveSpecialCharacters(propName).Replace(" ","-")}-{now.Hour}{now.Second}{now.Millisecond}";
}
Usually this error A generic error occurred in GDI+ mean that the file or the path doesn't exist:
so try for example to check if the directory exist or create it if not .. and then double check if you have already a file with same name or if the full path exist:
try:
var guid = Guid.New().ToString(); //<-- generate new random guid
//Store the file path (directory) that we are going to save the image to.
String directoryToSave = Server.MapPath(Constants.ImageDirectory + $"/{house_id}");
//Create the directory. This function will not do anything if it already exists.
if(!Directory.Exist(directoryToSave)
Directory.CreateDirectory(directoryToSave);
//Save the images to the filesystem.
mainImage.Save(Path.Combine(directoryToSave, savedFileName + "_" + guid), ImageFormat.Jpeg);
Hope it helps you

Programmatically save open document in MS Word Add-In

I'm trying to create an add-in in C# for MS Word 2010 that will add a new ribbon and a click event-handler. This click event-handler should save the active file in c:\temp, for example. And then I need to load the file content into a byte array.
Probably something like this:
public void ClickEventHandler(Office.IRibbonControl control)
{
string fileLocation = "c:\temp\test.docx";
Word.Document document = this.Document;
document.SaveAs(fileLocation);
byte[] byteArray = File.ReadAllBytes(fileLocation);
}
The point is, this is pseudo-code and I don't know how to load an active document into a byte array. If there is a way without saving the document it would be even better.
And a query if the active file is a docx (and not a doc file) would be nice as well.
Word.Document document = Globals.ThisAddIn.Application.ActiveDocument;
document.SaveAs2(goldenpath + "\\" + name + "." + id + ".docx");
document.Close();
I use this generic function in my program to serialize arbitrary objects to a byte array:
private byte[] MakeByteSize<U>(U obj)
{
if (obj == null) return null;
var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
var ms = new System.IO.MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
Edit:
After reading your additional content, I'm confident that serializing the Word.Document object won't get you what you need, since the byte array representing that object in the program (which is probably a wrapper around some COM interop) won't be the same as the byte array representing the information stored in the file about the document.
Looking at the MSDN article you referenced, it looks like what we really need is a WordprocessingDoc instance representing the document that we can pass to the HtmlConverter class. So I think the question you really want to ask is "How can I create a DocumentFormat.OpenXml.Packaging.WordprocessingDocument from an open document without saving the file first?"
Unforunately, I'm not sure that's possible since I'm not really spotting any methods on that class that would do that.
On the .doc vs .docx issue, the Open XML SDK for Microsoft Office says that it works with documentat that adhere to the "Office Open XML File Formats Specification" which I believe means it will only work with the .docx file format. You might have to try a different route on this, like exporting to PDF perhaps. Good luck!

Creating xlsx file

I am basically creating a xlsx file but I am getting an error while using that file like below.
System.IO.FileFormatException: Archive file cannot be size 0.
The way I tried.
string file = "c:\\DoneDone61.xlsx";
using(File.Create(file))
{
}
Also I cannot open excel file manually because it says the file is corrupted.
Thanks for answers in advance.
An Excel file which you consider to be "blank" is not just a file with no data in it (which is what you are creating). You can see this yourself by creating a document manually in Excel and then opening it in notepad. You'll notice that it actually has data inside of it. That data is used to store information regarding the three empty sheets named "Sheet1", "Sheet2" and "Sheet3". Also, there is some header information so that any program looking at the file knows that it is actually a compressed file (as per the Excel file format). So, as you can see, even a pretty empty excel file still contains SOME data.
If you want to create a blank excel document using C#, you have two good options:
Use a library that allows you to actually work with creating Excel documents that takes care of creating the file correctly. Check out something like the Microsoft OpenXML SDK or ExcelPackage.
Create an empty Excel document, store it somewhere, and when you want to "create" a new empty Excel document, just make a copy of this file.
This one ...
using(File.Create(filePath))
{
}
... creates an empty file. Read: really empty (=> 0 bytes) not an empty XLSX with an XLSX skeleton: ZIP container, file header, style definitions, ....
What exactly did you expect?
EDIT:
If you want to create an empty XLSX file (like "Right Click on Mouse > New > New Microsoft Excel"), you have to use such an template, ... and write it onto the disk.
To achieve that, you have to deploy this template file with your application, and then do a File.Copy(source, dest), or integrate it as a resource and write the resource content to the disk.
What you need to use is Interop.Excel namespace. Here's a guide from msdn
please use this...Its a bit hacky but couldn't get a better way to do this using InterOp
public static void CreateEmptyXLSXFile(string FilePath)
{
FileStream MyStream = new FileStream(FilePath, FileMode.CreateNew, FileAccess.ReadWrite);
MyStream.Write(ExcelDocumentsInterOps.GetEmptyXSLXFileBytes(), 0, ExcelDocumentsInterOps.GetEmptyXSLXFileBytes().Length);
MyStream.Flush();
MyStream.Close();
MyStream.Dispose();
MyStream = null;
}
/// <summary>
/// Returns the bytes for an empty xslx file
/// </summary>
/// <returns></returns>
public static byte[] GetEmptyXSLXFileBytes()
{
string TheSting = "UEsDBBQABgAIAAAAIQBYVsaPYAEAABgFAAATANoBW0NvbnRlbnRfVHlwZXNdLnhtbCCi1gEooAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AxwEAABgAAAAAAAAAAAAAAAAAJBUAAHhsL3dvcmtzaGVldHMvc2hlZXQxLnhtbFBLAQItABQABgAIAAAAIQAQFQ8XQQEAAF8CAAARAAAAAAAAAAAAAAAAAHgWAABkb2NQcm9wcy9jb3JlLnhtbFBLAQItABQABgAIAAAAIQCcPLtYiwEAADQDAAAQAAAAAAAAAAAAAAAAAPAYAABkb2NQcm9wcy9hcHAueG1sUEsFBgAAAAALAAsAygIAALEbAAAAAA==";
return Convert.FromBase64String(TheSting);
}
When dealing with spreadsheet related tasks in .NET, you can use this open source library called SpreadsheetLight to write an excel file (especially, if you want to write content at some point).
If you prefer adding it as package via Nuget, you can say:
Install-Package SpreadsheetLight
After that, going by GenerateReport() exmaple:
// this one creates an empty workbook
using (SLDocument sl = new SLDocument())
{
// sl.SetCellValue("B3", "I love ASP.NET MVC");
sl.SaveAs("c:\\DoneDone61.xlsx");
}
Also see their tutorial for more interesting stuff.

I am merging two Word documents with OpenXML SDK but get a corrupt document when copying an image into a header

I have code which works in all sorts of different situations, including when copying images into the body of the document.
The code works when copying (adding) headers and footers from one document to the other, as long as the headers/footers being copied do not contain images.
When I copy a header which has an image in it, then the resulting file is corrupt, and when I try to open it with the OpenXML SDK it throws an exception saying "Compressed part has inconsistent data length".
I do know that the image has to be created in the HeaderPart (as against the MainDocumentPart when copying into the body).
The code which does the merging of the image looks something like:
private void AddSourceImagesToDestination(XElement sourceXml, OpenXmlPart sourcePart, OpenXmlPart destPart) {
foreach(XElement drawingElement in sourceXml.Descendants(_mswDrawingElementName)) {
XAttribute aBlipEmbedAttribute = drawingElement.Descendants(_ablipElementName).First().Attribute(_embedAttributeName);
string relationshipId = aBlipEmbedAttribute.Value;
ImagePart sourceImagePart = (ImagePart)sourcePart.GetPartById(relationshipId);
ImagePart destinationImagePart = ((HeaderPart)destPart).AddImagePart(sourceImagePart.ContentType);
string newRelationshipId = destPart.GetIdOfPart(destinationImagePart);
aBlipEmbedAttribute.SetValue(newRelationshipId);
destinationImagePart.FeedData(sourceImagePart.GetStream(FileMode.Open, FileAccess.Read));
}
}
The above is called passing the source and destination HeaderParts, and the XML of the source header which will after this be copied into the destination document. After calling the above procedure, destinationHeaderPart.Header.Save() is called.
As I said above, if there are no images in the source header, then the resulting document is fine (i.e. when the foreach doesn't find any drawing elements in the source XML).
I wonder, though, whether this symptom of the images in the header is perhaps a red herring and the real problem is somewhere else.
As I said in the comment on the question, the code to include the images into the header and footer was fine - it did the trick.
How I solved the problem of the corrupt file that my code (elsewhere) was creating was by a bit of trial and error. As other contributors have said, the documentation around OpenXML is, to put it mildly, not very good. So there might be another resolution to this problem, and maybe my "solution" just works because of some other side effects.
Anyway, I have some code which looks like this:
private MemoryStream _memoryStream;
private WordprocessingDocument _wordDocument;
...
_wordDocument = WordprocessingDocument.Open(_memoryStream, true);
...
private void ReopenDocument() {
_wordDocument.Package.Flush();
_wordDocument.Close();
MemoryStream newStream = new MemoryStream();
_memoryStream.WriteTo(newStream);
_memoryStream.Close();
_memoryStream = newStream;
_memoryStream.Position = 0L;
_wordDocument = WordprocessingDocument.Open(_memoryStream, true);
}
If I call the ReopenDocument method immediately prior to writing the _memoryStream to a FileStream, then the corruption is avoided.

Categories