none
word print function criss-crossed the name of the files with the content RRS feed

  • Question

  • The issue we got is that weprinted two batches of .rtf files to PDF files almost at the same time by using c # software, batch B started a minute earlier than batch A, one file in batch A had the right file name(we used some file identifier parameters (such as batch id, report id, etc.) to compose file name) but the content is another file in batch B.

    This issue only happened once, we tried reprint the wrong content .rtf again, there is no error.

    we checked our source code, the highest possible causes we could think out is the print function of Word.Document, as the name of document we passed to the printout function is the same name we used for the PDF file. we got the right PDF file name, so we can confirm that we passed the right doc to the function.

     void PrintOut(ref object Background = Type.Missing, ref object Append = Type.Missing, ref object Range = Type.Missing, ref object OutputFileName = Type.Missing, ref object From = Type.Missing, ref object To = Type.Missing, ref object Item = Type.Missing, ref object Copies = Type.Missing, ref object Pages = Type.Missing, ref object PageType = Type.Missing, ref object PrintToFile = Type.Missing, ref object Collate = Type.Missing, ref object ActivePrinterMacGX = Type.Missing, ref object ManualDuplexPrint = Type.Missing);

    Have anyone met this kind of issue before, or have any thoughts on it?

    Thanks

    Tuesday, May 7, 2013 10:15 PM

All replies

  • Hi SQ_Yilin,

    Thank you for posting in the MSDN Forum.

    It hard to say since the other part of your code is not available to us.

    One thing I don't understand is that you set OutputFileName parameter to Type.Missing. Shouldn't it be the name of rtf file you were printing.

    I look forward to your reply.

    Best regards,


    Quist Zhang [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, May 9, 2013 6:35 AM
    Moderator
  • Thanks Quist,

    we have a MsWord.cs to control Ms word function in our project, here is the print function in this class:

    msWord.PrintDocument(ReportFileName, GetWatermarkFileNames(), printOutputFileName,    

                        printer.FullName, copiesCount, pageRange, trayIdentifier, useWord95Printing);

        public void PrintDocument(Word.Document document, string printFile,
                string printerName, short copies, string pageRange, int tray, bool useWord95Printing)
            {
                try
                {
                    if (document == null)
                        throw new ArgumentNullException("document");

                    object missing = Missing.Value;

                    if (VerboseTracing)
                        TraceVerbose(string.Format("Preparing to print MS Word document \"{0}\", print file \"{1}\", printer \"{2}\"",
                            document.FullName, printFile, printerName));

                    if (ExtremeTracing)
                        TraceExtreme(string.Format("Print document args: doc name=\"{0}\", print file=\"{1}\", "
                            + "printer=\"{2}\", copies={3}, page range={4}, tray={5}, use Word 95 printing={6}",
                            document.FullName, printFile, printerName, copies, pageRange, tray, useWord95Printing));
                
                    // Make sure the document is un-protected
                    if (document.ProtectionType != Word.WdProtectionType.wdNoProtection)
                        UnProtectDocument(document);

                    // repaginate the document to make sure page numbers are correct
                    document.Repaginate();

                    // render the document as Word 95 did if the option was set
                    if (useWord95Printing)
                    {
                        if (ExtremeTracing)
                            TraceExtreme("Using MS Word 95 compatible printing");
                        document.set_Compatibility(Word.WdCompatibility.wdWW6BorderRules, true);
                        document.set_Compatibility(Word.WdCompatibility.wdUsePrinterMetrics, true);
                    }
                
                    // Select the printer through the old WordBasic method because the VBA way changes the default
                    // printer for the system
                    typeof(object).InvokeMember("FilePrintSetup", BindingFlags.InvokeMethod, null,
                        document.Application.WordBasic, new object[]{printerName, 1},
                        null, null, new string[]{"Printer", "DoNotSetAsSysDefault"});

                    // setup the paper tray to print to
                    Word.WdPaperTray paperTray;
                    if (tray == 0)
                        paperTray = Word.WdPaperTray.wdPrinterDefaultBin;
                    else
                        paperTray = (Word.WdPaperTray)tray;
                    if (ExtremeTracing)
                        TraceExtreme(String.Format("Setting Word document paper tray to {0} ({1})", paperTray, tray));
                    // Set tray info on each document section to avoid Word error at some sites
                    foreach (Word.Section s in document.Sections)
                    {
                        try
                        {
                            s.PageSetup.FirstPageTray = paperTray;
                            s.PageSetup.OtherPagesTray = paperTray;
                        }
                        catch
                        {
                            // This doesn't always work so if doesn't just ignore the exception and continue
                        }
                        finally
                        {
                            // TT5447 - Release interface to COM object
                            Marshal.ReleaseComObject(s);
                        }
                    }

                    // Finally perform the print to file
                    object printBackground = false;
                    object copyCount = copies;
                    object pages = Missing.Value;
                    object printFileObject = printFile;
                    object printToFile = true;
                    object collate = true;

                    // Print to file if an output file was specified, otherwise print directly to printer
                    if ((printFile == null) || (printFile == string.Empty))
                    {
                        printFileObject = missing;
                        printToFile = false;
                    }

                    if (pageRange != null && pageRange.Length > 0)
                        pages = pageRange;

                    if (VerboseTracing)
                    {
                        if ((bool)printToFile)
                            TraceVerbose(string.Format("Printing MS Word document to file \"{0}\"", (string)printFileObject));
                        else
                            TraceVerbose("Printing MS Word document directly to printer");
                    }

            if ((bool)printToFile && File.Exists(printFile))
            {
              if (WarningTracing)
                TraceWarning(string.Format("Pre-existing work file \"{0}\" is being deleted", printFile));
              try
              {
                File.Delete(printFile);
              }
              catch (Exception ex)
              {
                throw new MsWordException(
                  string.Format("Unable to delete pre-existing work file \"{0}\"", printFile), ex);
              }
            }

                    document.PrintOut(
                        ref printBackground,
                        ref missing,
                        ref missing,
                        ref printFileObject,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref copyCount,
                        ref pages,
                        ref missing,
                        ref printToFile,
                        ref collate,
                        ref missing,
                        ref missing);

                    // Some printer drivers may be slow in producing the print-to-file output file.
                    // Specifically, the Toshiba eStudio28-45 driver, but there may be more. If the file is
                    // not immediately available and ready to read, wait a reasonable amount of time before
                    // giving up.
                    if (((bool)printToFile))
                    {
                        int totalDelay = 0;
                        int sleepTime = 25;
                        // allow up to 10 seconds to create the file
                        while ( totalDelay <= 10000 )
                        {
                            if (File.Exists(printFile))
                            {
                                // only log when there was a delay
                                if (VerboseTracing && totalDelay > 0)
                                    TraceVerbose(string.Format("Output file for report \"{0}\" finally exists after {1} ms delay.", printFile, totalDelay));
                                break;
                            }
                            Thread.Sleep(sleepTime);
                            totalDelay += sleepTime;
                        }
                        if (!File.Exists(printFile))
                            throw new MsWordException(string.Format(
                                "Microsoft Word failed to produce an output file at \"{0}\" within {1} ms",    printFile, totalDelay));
                        // allow up to 60 seconds to write the file
                        totalDelay = 0;
                        while ( totalDelay <= 60000 )
                        {
                            try
                            {
                                using (FileStream fsRetry = File.OpenRead(printFile))
                                {
                                    // only log when there was a delay
                                    if (VerboseTracing && totalDelay > 0)
                                        TraceVerbose(string.Format("Output file for report \"{0}\" can finally be opened after {1} ms delay.", printFile, totalDelay));
                                    break;
                                }
                            }
                            catch ( IOException )
                            {
                                Thread.Sleep(sleepTime);
                                totalDelay += sleepTime;
                            }
                        }
                        // final check in case of other unexpected failure while waiting for driver to finish
                        if (!File.Exists(printFile))
                            throw new MsWordException(string.Format(
                                "Microsoft Word failed to completely write an output file at \"{0}\" within {1} ms",    printFile, totalDelay));

                    } // if printToFile

                }
                catch(Exception ex)
                {
                    if ((printFile == null) || (printFile == string.Empty))
                        logSet.Trace.WriteEntry(
                            string.Format("Error occurred while printing Microsoft Word document to printer \"{0}\"", printerName),
                            TraceLogEntryType.Error, "MsWord", "PrintOut", ex.ToString());
                    else
                        logSet.Trace.WriteEntry(
                            string.Format("Error occurred while printing Microsoft Word document to file \"{0}\"", printFile),
                            TraceLogEntryType.Error, "MsWord", "PrintOut", ex.ToString());

                    throw new MsWordException("Error occurred while printing Microsoft Word document to file", ex);
                }
            }

    public void PrintDocument(string sourceDocument, string[] overlayFiles, string printFile,
                string printerName, short copies, string pageRange, int tray, bool useWord95Printing)
            {
                Word.Document document = OpenDocument(sourceDocument);
                try
                {
                    if (overlayFiles != null)
                        UpdateDocWithWaterMarks(document, overlayFiles);
                    PrintDocument(document, printFile, printerName, copies, pageRange, tray, useWord95Printing);
                }
                finally
                {
                    CloseDocument(document);
                }
            }

    In other class, we use this statement to call the print function:

     msWord.PrintDocument(ReportFileName, GetWatermarkFileNames(), printOutputFileName,    
                        printer.FullName, copiesCount, pageRange, trayIdentifier, useWord95Printing);

    and the ReportFileName and printOutputFileName are quite identical :

        protected string ReportFileName
            {
                get
                {
                 
                    if ( DistillerNameType == string.Empty || distillerReportID == string.Empty )
                    {
                        return Path.Combine(WorkFilePath, string.Format("{0}{1}_{2}_{3}.rtf",
                            QueueTypeString, QueueID, BatchID, ItemID));
                    }
                    else
                    {
                        return Path.Combine(WorkFilePath, string.Format("{4}_{0}{1}_{2}_{3}.rtf",
                            QueueTypeString, QueueID, BatchID, ItemID, distillerReportID));
                    }
                }
            }

        public string OutputFileName
            {
                get
                {
                 
                    if ( DistillerNameType == string.Empty || distillerReportID == string.Empty )
                    {
                        return Path.Combine(WorkFilePath, string.Format("{0}{1}_{2}_{3}.prn",
                            QueueTypeString, QueueID, BatchID, ItemID));
                    }
                    else
                    {
                        return Path.Combine(WorkFilePath, string.Format("{4}_{0}{1}_{2}_{3}.prn",
                            QueueTypeString, QueueID, BatchID, ItemID, distillerReportID));
                    }
                }
            }

    Thursday, May 9, 2013 8:34 PM
  • the OpenDocument function  used in the PrintDocument is:

        public Word.Document OpenDocument(string fileName)
            {
                try
                {
                    if (ExtremeTracing)
                        TraceExtreme(String.Format("Opening MS Word document \"{0}\"", fileName));
                    object missing = Missing.Value;
                    object fileNameObject = fileName;
                    return Application.Documents.Open(
                        ref fileNameObject,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing,
                        ref missing);
                }
                catch(Exception ex)
                {
                    throw new MsWordException(String.Format("Error occurred while opening Microsoft Word document \"{0}\"", fileName), ex);
                }
            }

    Thursday, May 9, 2013 8:54 PM