Close OpenXML Document Without Saving - openxml

From what I understand, when you open, edit, then close an OpenXML document such as an .DOCX file, the revised document is automatically saved. If you change your mind and decide not to save the edits, is there a way to close the document without saving? I can't seem to find anything.

The document has an AutoSave property, which is set to True by default. The Open method can take an OpenSettings object, which can be used to override the default behavior:
Imports DocumentFormat.OpenXml.Wordprocessing
Dim os As OpenSettings = New OpenSettings()
os.AutoSave = False
Dim doc as Doc = WordprocessingDocument.Open(Path, True, os)
In this case, the document will not be saved unless doc.Save is called. doc.Dispose will simply release the resources without the save.

Related

Word addin, set filename

If one starts a blank file on Word you can usually see in the top bar a name such as "Document1", "Document2" and so on.
Yet, if you attempt to open a file using the Word JS API like this:
Word.run((context) => {
context.application.createDocument(documentB64).open()
return context.sync()
})
The top bar comes out like this:
No filename is set.
To set a filename/handle(?), I tried using the code given here Office JS - Add customProperty to new document but that didn't help.
My addin is usually used in conjunction with another (VSTO) add-on and that add-on can't work properly with the documents opened by my addin and I believe the lack of a filename (/handle?) explains it to some extent.
Is there something I can do about this?
Thank you
Currently you can't do this because the newly created document is just a temporary file and not saved. can you try to call the following code to make sure the newly created file is saved?
const documentCreated = context.application.createDocument(externalDoc);
documentCreated.save();
documentCreated.open();

Add Eventhandler to Object of type Word.Application

With the following code I open a a new word document. To save the word document programmatically I want to add an event listener to the object, which occurs when word will be closed. Is this possible?
Set objWord = createobject("Word.Application")
objWord.visible = True
Set objDoc = objWord.documents.add()
Call objDoc.content.select()
Set selection = objWord.selection()
Call selection.collapse()
objDoc.Close
Set objDoc = Nothing
objWord.Quit
Set objWord = Nothing
EDIT:
I try to explain better what I want to do. My Lotusscript Agent should open a word document for the user. The user types in some text and then closes the word document. Instead of showing the save dialog of word I want to save the document programmatically to embedd the file as attachment to an notes document. Until now I have not found a solution to get an handle of the event when word is closing.
I think this link on one of the ldd wikis probably has what you need. If you are a little clearer on what you need, you may get better answers though.
I think you are wanting to be notified when word closes so you can force a save or something correct? You can already force the save using similar lotusscript to how you are closing it, you don't need to wait until they close it themselves.

VSTO Word add-in - new document event not firing if Word is launched from the executable

In my add-in, I need to create a task pane for each open document. In the add-in's startup method, I subscribe to the ApplicationEvents4_Event.NewDocument and Application.DocumentOpen events, and then create a task pane for each opened document:
((ApplicationEvents4_Event)Application).NewDocument += CreateTaskPaneWrapper;
Application.DocumentOpen += CreateTaskPaneWrapper;
foreach (Document document in Application.Documents)
{
CreateTaskPaneWrapper(document);
}
This covers cases for opening or creating a document through Word's menu, or opening an existing document file in the OS. However, if Word is already opened, launching WINWORD.EXE (or accessing it through a shortcut, which is a pretty common scenario) doesn't trigger either event, despite a new window with a new document being opened. How can I react to this scenario and create a task pane for a document created this way? I'm using VSTO 3 and Visual Studio 2008, targeting Word 2007.
If Word is started, a new document is created BEFORE the Add-In loads, therefore this event can not be trapped.
If you need to work with the initially created document, just take a look at the Documents collection - if Count is greater zero, this document is the one created by Word before your Add-In was loaded.
So I solved this problem in my solution, although I'm not sure it will be cross applicable. Sadly, mine is in VB.Net, so there may need to be some translation.
First, I ended up not using ApplicationEvents4_Event Instead there are other built in event triggers you can use via "ThisAddIn"
Private Sub Application_NewDocument(ByVal Doc As Word.Document) Handles Application.NewDocument
'MsgBox("I opened something")
myCustomTaskPane = Me.CustomTaskPanes.Add(New MyCustomTaskPaneClass, "TaskPane", Doc.ActiveWindow)
myCustomTaskPane.Visible = True
End Sub
Using this method I did have a similar challenge. Running winword.exe, and thereby opening a new word document, did not trigger the NewDocument event. Luckily, there was another event to use - Document change.
Private Sub Application_DocumentChange() Handles Application.DocumentChange
'function to test if the ActiveDocument has a taskpane from my add-in, and then a function to add one
If Not HasMyCustomTaskPane() then AddCustomTaskPane()
End Sub
So - bottom line, regardless of if you keep using ApplicationEvents4_Event you should see if you can use the DocumentChange event. It triggers when a new word window is selected.
Handling task panes for more than one window in Word is fairly complicated, because of how Word loads and re-uses open windows. To do it correctly, you have to consider different actions:
The user takes an action to display or hide a task pane.
The user creates a new document.
The user opens an existing document.
The user closes an open document.
There's a tutorial that explores all the details, both in VB and C#: https://msdn.microsoft.com/en-us/library/bb264456%28v=office.12%29.aspx
I also found a similar answer on SO.

ITextSharp - Adding a Watermark; Leaving the PDF editable - FormFlattening = false

We have a large amount of PDF files that we are creating a web site to allow users to download them and when they do we want to:
Put a watermark on it with their name.
We want the form fields to be left open so they can enter their information.
We want to be able to print and save the document
When I put the Watermark on the document and then open it I get a message from Adobe:
"The document has been changed since it was created and use of extended features is no longer available. Please contact the author..."
According the book "iText-in-Action", this is a security issue (Chapter 8). There seems to be 2 ways to open them:
Remove usage rights : This breaks # 3 above.
Open it in append mode : It does not matter if modify it and save it with "FormFlattening = false" or true, if I put a water mark on the form the fields are no longer editable.
The error message from Adobe does describe the problem, I have modified the content of the document with the watermark, and the form fields become blocked because of this.
I have tried opening the document putting the watermark on it and saving it to a new file, and then closing it. Then reopening it and the trying to unblock the form fields, but it does not work.
Does anyone know if this is possible?
I have read something about templates; I don't know if this is a solution because of the work to convert the documents to templates? Does anyone know if this would help?
Below is a sample of my code for using an Image as a watermark, although I have tried adding text as well:
PdfReader reader = new PdfReader(sourceFile.FullName);
//reader.RemoveUsageRights();
var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.ReadWrite);
PdfStamper pdfStamper = new PdfStamper(reader, fileStream, '\0', true);
Image image = Image.GetInstance(imagePath);
image.SetAbsolutePosition(250, 300);
for (int i = 1; i <= reader.NumberOfPages; i++) // Must start at 1 because 0 is not an actual page.
{
PdfContentByte pdfPageContents = pdfStamper.GetUnderContent(i);
pdfPageContents.AddImage(image);
}
pdfStamper.FormFlattening = false; // enable this if you want the PDF flattened.
//bool have = pdfStamper.PartialFormFlattening("test");
pdfStamper.Close(); // Always close the stamper or you'll have a 0 byte stream.
A document that is Reader-enabled is digitally signed using a private key owned by Adobe. If Adobe Reader can validate that signature using Adobe's public key, the extra functionality (e.g. allowing you to save a form that has been filled out) is enabled.
Adding a watermark isn't part of the actions you're allowed to do with a digitally signed document. There is absolutely no way you can achieve what you want without invalidating the digital signature that triggers the reader enabling.
In short: you're trying to do something that is impossible. You can only achieve this by using Adobe software because you need Adobe's private key to 'restore' the reader enabling after breaking it.
Good advice.
Every time I reboot my computer Adobe complains about needing to be updated. Last thing I want is to be stuck with a hack, that may not work in the future.
One of my attempts was to create a watermark on a different layer of the PDF in the hopes that it would not see it as changing the text layer of the PDF, but this did not work. My boss had a thought of grabing the text from the original PDF and coping it to a new document and then putting the watermark on it. even though I created a new PDF it still sees it as modifying it, and the fields are still not editable.
Still stuck

how to stop macros running when opening a Word document using OLE Interop?

As the title suggests, I have a .Net application which uses interop to open documents in Word. I have set
app.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable
before opening the document. According to the documentation, thhis "Disables all macros in all files opened programmatically, without showing any security alerts"
However, when I attempt to open one specific document I get a dialog box on the screen that says "could not load an object because it is not available on this machine". It's a customer document but I believe it contains a macro with references to a COM object which I don't have installed.
Am I doing something stupid? is there any way to actually disable macros when opening a Word document?
Try:
WordBasic.DisableAutoMacros 1
Bizarrely, this relies on a throwback to pre-VBA days, but still seems to be the most-reliable way to ensure that no auto macros are triggered (in any document - you may want to turn it back using the parameter "0").
I recently had a project where I had to process 6,000 Word templates (yes, templates, not documents) many of which had oddball stuff like macros, etc. I was able to process all but 6 using this technique. (I never did figure out what the problem was with those 6).
EDIT: for a discussion of how to call this from C#, see: http://www.dotnet247.com/247reference/msgs/56/281785.aspx
For c# you can use
(_wordApp.WordBasic as dynamic).DisableAutoMacros();
The whole code I'm using is:
using Word = Microsoft.Office.Interop.Word;
private Word.Application _wordApp;
...
_wordApp = new Word.Application
{
Visible = false,
ScreenUpdating = false,
DisplayAlerts = Word.WdAlertLevel.wdAlertsNone,
FileValidation = MsoFileValidationMode.msoFileValidationSkip
};
_wordApp.Application.AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable;
(_wordApp.WordBasic as dynamic).DisableAutoMacros();