Word Interop 2007 silent printing issue - c#

I am using:
Office 2007
VC# Express 2010
1x Citrix virtual XP network environment accessed through Windows 7 laptop host
1x printer set to output to .prn in a given network-mapped drive
I am using C# and Word Interop to silently print a given set of files automatically. The application scans an input folder every 10 minutes for .doc / .docx files only, and inputs their path&filename into a list. Foreach found file, attempt to print via the following code:
public static Boolean PrintFoundFiles(List<string> foundFiles)
{
successful = false;
foreach (string file in foundFiles)
{
object fileAndPath = file; //declare my objects here, since methods want an object passed
object boolTrue = true; //
object boolFalse = false; //
object output = FormatOutputName(file); //
object missing = System.Type.Missing; //
object copies = "1"; //
object pages = ""; //
object items = Word.WdPrintOutItem.wdPrintDocumentContent; //
object range = Word.WdPrintOutRange.wdPrintAllDocument; //
object pageType = Word.WdPrintOutPages.wdPrintAllPages; //
Word.Application wordApp = new Word.Application(); //open word application
wordApp.Visible = false; //invisible
Word.Document doc = wordApp.Documents.Open(ref fileAndPath, 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); //opens the word document into application behind the scenes
doc.Activate(); //activates document, else when I print the system will throw an exception
wordApp.ActivePrinter = "my printer name"; //Specify printer I will print from
doc.PrintOut(ref boolTrue, ref boolFalse, ref range, ref output, ref missing, ref missing,
ref items, ref copies, ref pages, ref pageType, ref boolTrue, ref boolTrue,
ref missing, ref boolFalse, ref missing, ref missing, ref missing, ref missing);
doc.Close(SaveChanges: false);
doc = null;
((Word._Application)wordApp).Quit(SaveChanges: false); //kill word process the right way
wordApp = null; //reset to null
successful = true;
}
return successful;
}
After I receive the true boolean of "successful", I will back up the file automatically in a backup folder, delete it in the input folder, and look for the .prn in the output folder (it just sits here for processing later).
If I don't provide an output (see ref output on doc.PrintOut()), the output directory doesn't get updated or printed to at all. If I DO provide an output, the .prn is created, though it is a 0kb empty file.
The printer is set up as the default printer, and it has been configured to automatically output to said output folder. If I open Word manually with the same file I'm trying to automatically print from, hit print, it will create a 6kb .prn file in the output directory without having to hit anything other than CTRL + P, OK.
I'm fairly confident the file is being opened OK via "Word.Document doc = wordApp.Documents.Open()" because I did a doc.FullName and got the full path of the input word document in question. I just cannot for the life of me get the .prn to output correctly to the output folder.

If I start my word (2010) and record a macro of me pressing Ctrl+P and hitting print - I'm getting
Application.PrintOut fileName:="", Range:=wdPrintAllDocument, Item:= _
wdPrintDocumentWithMarkup, Copies:=1, Pages:="", PageType:= _
wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
PrintZoomColumn:=0, PrintZoomRow:=0, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
Change your PrintOut to reflect what Word did and see if it solves your issue.
There's no reason to be "fairly confident", just remove
wordApp.Visible = false
Debug your program and make certain it's OK.

Related

How to merge two Word Document Objects in C# (not on file system level)?

i want to append one Word Document Object to another in my C# Code.
Is there any way to do this instantly with Word Interop Functions when i have both Documents as an Object?
I tried several approaches with Merge Function but this function expects filenames as strings and no objects. I don't want to save both documents and load them again.
//schematic version of my code:
doc_template = wordapp.Documents.Open(ref filedocA,
ref readOnly, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing);
doc_final = wordapp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
wordapp.Document tempdoc = null;
foreach (customer cust in dt_customers)
{
tempdoc = doc_template;
//Do some search and replace functions in tempdoc
...
//here somehow the complete tempdoc should be appended to doc_final
}
doc_final should contain all the modified tempdoc from each customer
//Update: Heres what i am doing now: Copying the contents within ranges
object start = tempdoc.Content.Start;
object end = tempdoc.Content.End;
tempdoc.Range(ref start, ref end).Copy();
doc_final.Activate();
start = Destination.Content.End;
end = Destination.Content.End;
start = wordapp.ActiveDocument.Content.End - 1;
rng = Destination.Range(ref start, ref missing);
rng.Select();
rng.Paste();
But is there a better option than simple copy the contents of the documents?

How can use the Word API to programmatically open a document with the Bookmark at the top of the page?

Using the following code to open a Word document at a bookmark
Object readOnly = true;
Object isVisible = true;
Object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();
wordApp.Visible = true;
wordDoc = 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);
object bookmarkName = BookMarkName;
if (wordDoc.Bookmarks.Exists(bookmarkName.ToString()))
{
Microsoft.Office.Interop.Word.Bookmark bookmark = wordDoc.Bookmarks.get_Item(ref bookmarkName);
bookmark.Select();
}
The Word document shows the bookmark, but not at the top of the page. Is there a way of showing the Bookmark at the top of the page as it is shown using Goto-> Bookmark?
The code suggested in StackOverflow Question
How do I use the Microsoft Word API and Bookmarks feature to programmatically open a Word document to a specific location?
which is
Object item = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
Object whichitem = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;
Object count = 1;
Object name = BookMarkName;
wordDoc.GoTo(ref item, ref missing, ref missing, ref name);
does not work and gives all the errors described in the post.
GotoBookmark in MS Word
In pascal work this code:
procedure GotoBookMark(name:string);
var d1,d2,d7,d8:olevariant;
begin
d1:=name;
d2:= wdGoToBookmark;
d7:=unAssigned;
d8:=unAssigned;
try
WA.selection.GoTo_(d2, d7,d8,d1);
except
end;
end;
Where name name of bookmark;
wa is Microsoft.Office.Interop.Word.Application wa= new Microsoft.Office.Interop.Word.Application();
open document MS Word
procedure OpenWordDoc(Name:string);
var FileName,Visible,newtemplate,documenttype:olevariant;
begin
FileName:=Name;
newtemplate:=false;
documenttype:=0;
visible:=true;
WA.Documents.Add( FileName,newtemplate,documenttype,visible);
end;
This is tricky, since Word VBA isn't really screen-oriented. The following code does work on my screen, but you'd need to test to be sure it works in other configurations. You might need to adjust the "fudge factor" (the literal 40). In any case, though, it should get the bookmark near the top of the screen, within a line or so.
The Window.GetPoint method returns the position in pixels of the Range - it's a Windows API method that's been brought into VBA, which is why you have to pass in the variables, which are then populated with the values.
The Window height less the usable height, plus the "fudge factor" gives you the position in points of the visible top of the document. The Window is scrolled line-by-line until the position returned by GetPoint is no longer greater than this position.
Sub ScrollBookmarkTopOfPage()
Dim rng As word.Range
Dim pxLeft As Long, pxTop As Long, pxWidth As Long, pxHeight As Long
Dim winUseHeight As Long, winHeight As Long, pos As Long
Set rng = ActiveDocument.Bookmarks("test").Range
ActiveWindow.GetPoint pxLeft, pxTop, pxWidth, pxHeight, rng
'Debug.Print pxLeft, pxTop, pxWidth, pxHeight
winUseHeight = ActiveWindow.UsableHeight
winHeight = ActiveWindow.height
pos = winHeight - winUseHeight + 40
Do While PixelsToPoints(pxTop) > pos
ActiveWindow.SmallScroll
ActiveWindow.GetPoint pxLeft, pxTop, pxWidth, pxHeight, rng
Loop
rng.Select
End Sub

Merging multiple docx files to one

I am developing a desktop application in C#. I have coded a function to merge multiple docx files but it does not work as expected. I don't get the content exactly as how it was in the source files.
A few blank lines are added in between. The content extends to the next pages, header and footer information is lost, page margins gets changed, etc..
How can I concatenate docs as it is without and change in it.Any suggestions will be helpful.
This is my code.
public bool CombineDocx(string[] filesToMerge, string destFilepath)
{
Application wordApp = null;
Document wordDoc = null;
object outputFile = destFilepath;
object missing = Type.Missing;
object pageBreak = WdBreakType.wdPageBreak;
try
{
wordApp = new Application { DisplayAlerts = WdAlertLevel.wdAlertsNone, Visible = false };
wordDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Selection selection = wordApp.Selection;
foreach (string file in filesToMerge)
{
selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing);
selection.InsertBreak(ref pageBreak);
}
wordDoc.SaveAs( ref outputFile, 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);
return true;
}
catch (Exception ex)
{
Msg.Log(ex);
return false;
}
finally
{
if (wordDoc != null)
{
wordDoc.Close();
}
if (wordApp != null)
{
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsAll;
wordApp.Quit();
Marshal.FinalReleaseComObject(wordApp);
}
}
}
In my opinion it's not so easy. Therefore I'll give you some tips here.
I think you need to implement the following changes to your code.
1.instead of pageBreak you need to add any of section breaks which could be the most appropriate:
object sectionBrak = WdBreakType.wdSectionBreakNextPage;
'other section break types also available
and use this new variable within your loop.
As a result you get all- text, footers and headers of the source document to new one.
2.However, you will still need to read margin parameters and apply them to your new document 'manually' using additional code. Therefore you will need to open source document and check it's margins in this way:
intLM = SourceDocument.Sections(1).PageSetup.LeftMargin;
'...and similar for other margins
and next you need to apply it to new document, to appropriate section:
selection.Sections(1).PageSetup.LeftMargin = intLM;
3.Some other document section could require some other techniques.
You could use the Open XML SDK and the DocumentBuilder tool.
See Merge multiple word documents into one Open Xml

C# Word Document - How to clean formatting?

The dilemma is rather simple. I need to create a small app that will clear all font background colors (leave table cell background colours unchanged), and remove all text with strikethrough in a word document, and then save the document into another folder. Otherwise the document's formatting should remain untouched.
Below is a large-ish example scraped together from random examples available in google showing how to apply specific kinds of formatting to random strings found using Find.Execute(). I have no clue however, on how to only do as described above.
public static string searchDoc(string fileNameRef)
{
Microsoft.Office.Interop.Word._Application word = new Microsoft.Office.Interop.Word.Application(); ;
Microsoft.Office.Interop.Word._Document doc = new Microsoft.Office.Interop.Word.Document();
object missing = System.Type.Missing;
try
{
System.IO.FileInfo ExecutableFileInfo =
new System.IO.FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location);
object fileName =
System.IO.Path.Combine(ExecutableFileInfo.DirectoryName, fileNameRef);
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);
doc.Activate();
//object findStr = "hello"; //sonething to find
// THIS is the part where I fail, I can't find of a way to Find.Execute on formatting
// as opposed to mere strings.
//while (word.Selection.Find.Execute(ref findStr)) //found...
//{
// //change font and format of matched words
// word.Selection.Font.Name = "Tahoma"; //change font to Tahoma
// word.Selection.Font.ColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdRed; //change color to red
//}
object saveFileName = ExecutableFileInfo.DirectoryName + "\\New\\" + fileNameRef;
doc.SaveAs(ref saveFileName, 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);
}
catch (Exception)
{
}
finally
{
doc.Close(ref missing, ref missing, ref missing);
word.Application.Quit(ref missing, ref missing, ref missing);
}
return fileNameRef;
}
Thanks for any help! And I do mean any, simply getting started on how to spot formatting would help a great deal, I imagine. :)
This is not a C#-specific question; it's a Word Object Model question (I refer you to here and here).
As to your specific question, I suggest you turn on the Macro Recorder in Word, perform the actions, and see the generated VBA code. Then you can apply it in C#.
Try this:
using System;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
namespace WordFormattingFindReplace {
class Program {
static void Main(string[] args) {
}
public static string searchDoc(string fileName) {
_Application word = new Application(); ;
_Document doc;
string folderName = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string filePath = Path.Combine(folderName,fileName);
doc = word.Documents.Open(filePath);
var find=doc.Range().Find;
find.Text="Hello";
find.Format=true;
find.Replacement.Font.Name="Tahoma";
find.Replacement.Font.ColorIndex=WdColorIndex.wdRed;
find.Execute(Replace:WdReplace.wdReplaceAll);
doc.SaveAs2(Path.Combine(folderName,"New",fileName));
doc.Close();
//We need to cast this to _Application to resolve which Quit method is being called
((_Application)word.Application).Quit();
return fileName;
}
}
}
Some notes:
Use using statements for clarity. Instead of Microsoft.Office.Interop.Word._Application word, add using Microsoft.Office.Interop.Word at the top of your file, and you can then just write _Application word
If all you need is the folder name, use the static Path.GetDirectoryName method and save as a string variable, instead of creating a FileInfo object
As of .NET 4, you can skip optional arguments when calling Documents.Open, Document.SaveAs and Document.Close. This also means you don't need an object missing.
There's nothing here the user really needs to see, so calling Document.Activate is unnecessary
It's probably better to reuse the Word.Application instance, instead of recreating it for each call.

Word Document Permission through C#

I am working on a document management program. I want to open up a Word document with the click of a button and according to the permissions to the user whoever logged in will be given certain permissions (like read-only, edittable).
I tried with this code:
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.ApplicationClass doc = new Microsoft.Office.Interop.Word.ApplicationClass();
object name = #"some.doc";
object read = true;
object t = true;
doc.Documents.Open(ref name, ref missing, ref read, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref t, ref missing, ref missing, ref missing, ref missing);
doc.Visible = true;
This code is opening up the document but as I have set the read-only true, it should open the document in readonly mode. When document is opened in Word 2003 it is editable whereas when opened in Word 2010 it is read-only.
Also, I'd like to know if is it worth it to disable all the toolbars of Word and create my own with the buttons which I want. I want to give only the functionality which I want - like I want to disable the SaveAs functionality.
How about something like the following code.
By specifying proc.StartInfo.UseShellExecute = true, Windows will automatically launch the application associated with the Word document, for the current user.
namespace ConsoleApplication1
{
using System.Diagnostics;
using System.Windows.Forms;
class Program
{
static void Main( string[] args )
{
var docName = #"some.doc";
try
{
using ( var proc = new Process() )
{
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = docName;
proc.Start();
}
}
catch ( System.Exception ex )
{
MessageBox.Show( string.Format( "Unable to display document '{0}': {1}", docName, ex.Message ) );
}
}
}
}

Categories

Resources