Getting a specific page from Word - c#

how to get specific page from word in c#.net console application?
I have tried it ,
But unfortunately I have got error from my application.
Following is my code:
{
object what = WdGoToItem.wdGoToPage;
object which = WdGoToDirection.wdGoToFirst;
object count = 0;
const string fileName = #"C:\..\..\test.doc";
object fileNameAsObject = fileName;
Application wordApplication = new Application();
object readOnly = false;
object missing = System.Reflection.Missing.Value;
wordApplication.Documents.Open(ref fileNameAsObject, ref missing, ref readOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
// here on this following line I have got error "This method or property is not available because this command is not available for reading."
Range startRange = wordApplication.Selection.GoTo(ref what, ref which, ref count, ref missing);
object count2 = (int)count + 1;
Range endRange = wordApplication.Selection.GoTo(ref what, ref which, ref count2, ref missing);
endRange.SetRange(startRange.Start, endRange.End);
endRange.Select();
;
}
So please provide me any solution on it..
Thanks In advance..

Are you using Office 2013? We ran into an issue with the same error message when running our interop code against a freshly installed Office 2013. It seems to be due to Office 2013's default "Reading Mode" as mentioned here.
Try turning off the reading mode by setting Application.ActiveWindow.View.ReadingLayout to false (as mentioned in the comments of the article). This call must be performed after you have opened a document. Otherwise, the call would fail with the message: System.Runtime.InteropServices.COMException : This command is not available because no document is open.

If you can I would use Open XML SDK 2.5 for Microsoft Office
This gives you full access to the document and in my opinion is the most likely to work and not have any memory problems.

After first call Word application still blocks document. Therefore document is read only.
Kill WINWORD.EXE process and then change code to:
Document document = wordApplication.Documents.Open(ref fileNameAsObject, ref missing, ref readOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
After work close document:
document.Close();
wordApplication.Quit();
After modifications working code:
object what = WdGoToItem.wdGoToPage;
object which = WdGoToDirection.wdGoToFirst;
object count = 0;
const string fileName = #"C:\..\..\test.doc";
object fileNameAsObject = fileName;
Application wordApplication = new Application();
object readOnly = false;
object missing = System.Reflection.Missing.Value;
wordApplication.Documents.Open(ref fileNameAsObject, ref missing, ref readOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
// here on this following line I have got error "This method or property is not available because this command is not available for reading."
Range startRange = wordApplication.Selection.GoTo(ref what, ref which, ref count, ref missing);
object count2 = (int)count + 1;
Range endRange = wordApplication.Selection.GoTo(ref what, ref which, ref count2, ref missing);
endRange.SetRange(startRange.Start, endRange.End);
endRange.Select();
wordApplication.Documents.Close();
wordApplication.Quit();

I know its old but I didnt get a proper answer so my solution is here it works fine.
object missing = System.Reflection.Missing.Value;
var document = application.ActiveDocument;
Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
int num = aDoc.ComputeStatistics(stat, ref missing); // Get number of pages
for(int i=0; i<num; i++)
{
document.ActiveWindow.Selection // Go to page "i"
.GoTo(WdGoToItem.wdGoToPage, missing, missing, i.ToString());
document.ActiveWindow.Selection // Select whole page
.GoTo(WdGoToItem.wdGoToBookmark, missing, missing, "\\page");
document.ActiveWindow.Selection.Copy(); // Copy to clipboard
// Do whatever you want with the selection
}

Related

.net word interop: word.Documents.Open returns null

I'm using .net .4.6.1 and trying to do a mail merge. When i run the following code, which has a valid path to a word (.doc) document, it returns null.
C#
object fileName = pathToDocument;
doc = word.Documents.Open(ref fileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
Any advice appreciated.
Thanks,
Chris
The signature of the Open method is really confusing but it can be treated with more of a common sense approach, try something like this adjusting the file path of your document ...
static void Main(string[] args)
{
var fileName = "c:\\temp\\Test.docx";
var wdApplication = new Microsoft.Office.Interop.Word.Application();
var wdDocument = wdApplication.Documents.Open(fileName);
Console.WriteLine(wdDocument.Words.Count);
wdDocument.Close();
wdApplication.Quit();
}
Word deals with local files only. You need to copy the file locally and then use the Word object model to open it.
The Documents.Open method doesn't require the ref keyword for passing parameters:
doc = word.Documents.Open(pathToDocument,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);

Can you replace ^13 paragraph markers with ^p paragraph markers in MS Word using Interop?

I am wanting to replace all the substitue code for paragraph markers (^13) with the normal paragraph marker code ^p in a Microsft Word document, using C# and Interop.
I am have been using the Microsoft.Office.Interop.Word.Selection.Find.Execute() method.
For example..
.Application.ActiveWindow.Selection.Find.Execute(
ref findText,
ref matchCase,
ref matchWholeWord,
ref matchWildcards,
ref matchSoundsLike,
ref matchAllWordForms,
ref findForward,
ref findWrap,
ref findFormat,
ref replaceText,
ref replaceAll,
ref missing,
ref missing,
ref missing,
ref missing);
findText = "^13"
matchCase = true
matchWholeWord = true
matchWildcards = true
matchSoundsLike = false
matchAllWordForms = false
findForward = true
findWrap = WdFindWrap.wdFindContinue
findFormat = false
replaceText = "^p"
replaceAll = WdReplace.wdReplaceAll
Using the code above, the ^13 markers are not being replaced by ^p markers.
Does anyone know how I can rectify this?
check my codes below:
// Create the Word application and declare a document
Word.Application word = new Word.Application();
Word.Document doc = new Word.Document();
// Define an object to pass to the API for missing parameters
object missing = System.Type.Missing;
try
{
// Everything that goes to the interop must be an object
object fileName = #"D:\test.docx";
// Open the Word document.
// Pass the "missing" object defined above to all optional
// parameters. All parameters must be of type object,
// and passed by reference.
doc = word.Documents.Open(ref fileName,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
// Activate the document
doc.Activate();
// Loop through the StoryRanges (sections of the Word doc)
foreach (Word.Range tmpRange in doc.StoryRanges)
{
// Set the text to find and replace
tmpRange.Find.Text = "xml";
tmpRange.Find.Replacement.Text = "XML";
// Set the Find.Wrap property to continue (so it doesn't
// prompt the user or stop when it hits the end of
// the section)
tmpRange.Find.Wrap = Word.WdFindWrap.wdFindContinue;
// Declare an object to pass as a parameter that sets
// the Replace parameter to the "wdReplaceAll" enum
object replaceAll = Word.WdReplace.wdReplaceAll;
// Execute the Find and Replace -- notice that the
// 11th parameter is the "replaceAll" enum object
tmpRange.Find.Execute(ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref replaceAll,
ref missing, ref missing, ref missing, ref missing);
}
// Save the changes
doc.Save();
// Close the doc and exit the app
doc.Close(ref missing, ref missing, ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);
}
catch (Exception ex)
{
doc.Close(ref missing, ref missing, ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);
System.Diagnostics.Process.Start("D:\\test.docx");
}
One more thing: Note here: using Word = Microsoft.Office.Interop.Word;
If i'm not mistake you can't call find and replace for paragraph but you can change style of them paragraph

Change or add template in Word-document

I'd like to change the template from a lot of Word-documents using a simple C#-program.
This documents are all based on a standard template for title styles, font, etc... We would like to change this template (more specifically: the title colors and other small things) and modify the current documents to use this new template.
In Word, this is easily achieved by clicking "Document Template" in the Designer tab in the ribbon. I used this guide to do this. This works beautifully and does exactly what it should do: change the title colors etc according to the new template.
So the question is simple: how do I do the exact same thing (attach other template and change styles) from within a .NET-application?
I guess I should use the Microsoft.Office.Interop.Word namespace, but I'm stuck there...
I managed to solve it by myself, wasn't that difficult apparantly. This is the code I used:
object missing = System.Reflection.Missing.Value;
Word.Application wordApp = new Word.ApplicationClass();
Word.Document aDoc = null;
object readOnly = false;
object isVisible = false;
wordApp.Visible = false;
object filename = "d:\\Testdocs\\testfile.doc";
object saveAs = "d:\\Testdocs\\output.doc";
object oTemplate = "d:\\Testdocs\\Template.dotx";
aDoc = wordApp.Documents.Add(ref oTemplate, ref missing,
ref missing, ref missing);
aDoc = wordApp.Documents.Open(ref filename, ref missing,
ref readOnly, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref isVisible, ref missing, ref missing,
ref missing, ref missing);
aDoc.Activate();
aDoc.set_AttachedTemplate(oTemplate);
aDoc.UpdateStyles();
aDoc.SaveAs(ref saveAs, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
aDoc.Close(ref missing, ref missing, ref missing);

How to open a RTF file with C# without showing the Microsoft Word "Convert File" dialog?

Question
I want to programmatically open a RTF file in Microsoft Word using C#. But I don't want to get the "Convert File" dialog while doing that. How do I do that?
Code
I've tried this piece of code, but it still shows Word's "Convert File" dialog.
object missing = Missing.Value;
string fileName = #"C:\RtfFile.rtf";
//object encoding = WdSaveFormat.wdFormatRTF;
object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
object noEncodingDialog = true; // http://msdn.microsoft.com/en-us/library/bb216319(office.12).aspx
word.Documents.Open(ref fullFilePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref encoding, ref missing, ref missing, ref missing, ref noEncodingDialog, ref missing);
What I have tried so far
Actually, there are two sub-questions.
On one hand, I am not sure which encoding to use. I've tried both options shown in the code snippet and checked Wikipedia for RTF character encoding.
On the other hand, object noEncodingDialog = true doesn't seem to work since the "Convert File" dialog keeps popping up (probably because the encoding is set wrongly).
Any ideas?
Versions
Word 2003
.NET 3.5
Visual Studio 2010 Ultimate
Full source code
Just in case you want to try it out.
Add reference to "Microsoft Word 11.0 Object Library" from the "COM" tab.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;
namespace WordAutomationDemo
{
public class Program
{
static void Main(string[] args)
{
new Program();
Console.ReadKey();
}
public Program()
{
object wordObject = null;
try
{
wordObject = Marshal.GetActiveObject("Word.Application");
}
catch (Exception)
{
// Do nothing.
}
Application word = null;
bool wordInstanceCreated = false;
if (wordObject != null)
{
word = (Application)wordObject;
}
else
{
wordInstanceCreated = true;
word = new Application();
}
word.Visible = true;
object missing = Missing.Value;
object fullFilePath = #"C:\RtfFile.rtf";
//object encoding = WdSaveFormat.wdFormatRTF; // http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas(v=vs.80).aspx
object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
object noEncodingDialog = true; // http://msdn.microsoft.com/en-us/library/bb216319(office.12).aspx
word.Documents.Open(ref fullFilePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref encoding, ref missing, ref missing, ref missing, ref noEncodingDialog, ref missing);
//if (wordInstanceCreated)
//{
// word.Quit();
//}
}
}
}
According the documentation of the Open method, the second argument (ConfirmConversions) can specify to disable the document conversion. Combining it with the (ReadOnly argument) and it should solve your problem.
bool f = false;
bool t = true;
word.Documents.Open(ref fullFilePath, ref t, ref f, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref encoding, ref missing, ref missing, ref missing, ref noEncodingDialog, ref missing);

When using a virtual printer how can I check that print is finished?

I am using a virtual printer to print a word document into an image file in a C# program. So far everything is going fine except that I don't know when the printing process is finished so I can read the content of the generated image.
Here's my code :
using System;
using Microsoft.Office.Interop.Word;
using Word=Microsoft.Office.Interop.Word;
var app = new ApplicationClass();
object filename = "C:\\ad.doc";
var missing = Type.Missing;
var doc = app.Documents.Open(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
var oldPrinter = app.ActivePrinter;
app.ActivePrinter = "Name of printer";
object outputFileName = "c:\\ad.tif";
object trueValue = true;
object falseValue = false;
doc.PrintOut(ref trueValue, ref falseValue, ref missing, ref outputFileName, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref trueValue, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing);
app.ActivePrinter=oldPrinter ;
doc.Close(ref missing, ref missing, ref missing);
app.Quit(ref missing, ref missing, ref missing);
Then how can I be sure that the print processing is finished so I can continue and get the image content?
Unfortunately, about the only way I've found to check for printing status in word is one of two things.
Print synchronously. Not great though because it'll can hang you
till the printing is complete.
Print the doc asynchronously, and then check the
APPLICATION.BACKGROUNDPRINTINGSTATUS property in a loop or on a
background worker thread continuously until it becomes 0 (no longer
printing) or you hit a watchdog timeout
Something like this....
Do Until _Doc.Application.BackgroundPrintingStatus = 0
System.Windows.Forms.Application.DoEvents()
System.Threading.Thread.Sleep(750)
Loop
Not perfect, but it works.
Note that this will only tell you when its finished spooling from word. If you're talking about knowing when the document is actually completed PRINTING on the printer, that's a whole other issue. You'll need the print jobID and have to query the printer spooler stuff, which I couldn't help you on.

Categories

Resources