|
Imports System.IO
Imports System.Drawing.Printing
Imports MODI
Imports DocumentProcessing
'Imports Microsoft.Office.Interop.Word
Imports Microsoft.Office.Core
Imports System.Runtime.InteropServices
Imports PrinterQueueWatch
Public Class Form1
Private printFont As Font
Private streamToPrint As StreamReader
Private Shared filePath As String
Private _MODIDocument As MODI.Document = Nothing
Dim Proc As New System.Diagnostics.Process
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
filePath = "E:\Personal\Personal\BackButtonDisable.txt"
'Printing()
'PrintDialog1.PrinterSettings.PrintFileName = filePath
'PrintDialog1.Document = PrintDocument1
'PrintDialog1.ShowDialog()
'PrintFile()
printdoc()
'PrintMyExcelFile()
'PrintPDF("E:\Personal\Personal\Credit Card\PNR IOHPTI\frmViewPassportPage1.pdf")
End Sub
'Print the file.
Public Sub Printing()
Try
streamToPrint = New StreamReader(filePath)
Try
printFont = New Font("Arial", 10)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf pd_PrintPage
'Print the document.
pd.Print()
Finally
streamToPrint.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub 'Printing
Private Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim linesPerPage As Single = 0
Dim yPos As Single = 0
Dim count As Integer = 0
Dim leftMargin As Single = ev.MarginBounds.Left
Dim topMargin As Single = ev.MarginBounds.Top
Dim line As String = Nothing
' Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics)
' Print each line of the file.
While count < linesPerPage
line = streamToPrint.ReadLine()
If line Is Nothing Then
Exit While
End If
yPos = topMargin + count * printFont.GetHeight(ev.Graphics)
ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
count += 1
End While
' If more lines exist, print another page.
If (line IsNot Nothing) Then
ev.HasMorePages = True
Else
ev.HasMorePages = False
End If
End Sub
'Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
' 'Dim linesPerPage As Single = 0
' 'Dim yPos As Single = 0
' 'Dim count As Integer = 0
' 'Dim leftMargin As Single = e.MarginBounds.Left
' 'Dim topMargin As Single = e.MarginBounds.Top
' 'Dim line As String = Nothing
' '' Calculate the number of lines per page.
' 'linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics)
' '' Iterate over the file, printing each line.
' 'While count < linesPerPage
' ' line = streamToPrint.ReadLine()
' ' If line Is Nothing Then
' ' Exit While
' ' End If
' ' yPos = topMargin + count * printFont.GetHeight(e.Graphics)
' ' e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, _
' ' yPos, New StringFormat())
' ' count += 1
' 'End While
' '' If more lines exist, print another page.
' 'If Not (line Is Nothing) Then
' ' e.HasMorePages = True
' 'Else
' ' e.HasMorePages = False
' 'End If
' Dim Image As System.Drawing.Image = pictureBox1.Image
' e.Graphics.DrawImage(Image, New Point(0, 0))
'End Sub
Private Sub PrintFile()
'_filename = filename;
_MODIDocument = New MODI.Document()
_MODIDocument.Create("E:\Personal\Personal\Medical\Saravana_Nov_Activities.doc")
If _MODIDocument IsNot Nothing Then
Dim d As New PrintDialog()
d.AllowSomePages = True
d.AllowSelection = False
d.PrintToFile = False
Dim ps As New PrinterSettings()
ps.MinimumPage = 0
ps.MaximumPage = _MODIDocument.Images.Count - 1
ps.FromPage = 0
ps.ToPage = _MODIDocument.Images.Count - 1
d.PrinterSettings = ps
If d.ShowDialog() = DialogResult.OK Then
_MODIDocument.PrintOut(d.PrinterSettings.FromPage, d.PrinterSettings.ToPage, d.PrinterSettings.Copies, d.PrinterSettings.PrinterName, "", False, _
MODI.MiPRINT_FITMODES.miPRINT_ACTUALSIZE)
End If
End If
End Sub
Public Sub printdoc()
Dim ac As New Microsoft.Office.Interop.Word.Application
Dim app As Microsoft.Office.Interop.Word.Application = ac.Application
Dim lsPriterName As String
' I'm setting all of the alerts to be off as I am trying to get
' this to print in the background
app.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone
' Open the document to print...
Dim filename As Object = "E:\Personal\Personal\Medical\Saravana_Nov_Activities.docx"
Dim missingValue As Object = Type.Missing
' Using OpenOld so as to be compatible with other versions of Word
Dim document As Microsoft.Office.Interop.Word.Document = app.Documents.Open(filename, missingValue, missingValue, missingValue, missingValue, missingValue, _
missingValue, missingValue, missingValue, missingValue)
' Set the active printer
Dim d As New PrintDialog()
If d.ShowDialog() = DialogResult.OK Then
lsPriterName = d.PrinterSettings.PrinterName
Else
Exit Sub
End If
app.ActivePrinter = lsPriterName
Dim myTrue As Object = True
' Print in background
Dim myFalse As Object = False
' Using PrintOutOld to be version independent
app.ActiveDocument.PrintOut(myTrue, myFalse, missingValue, missingValue, missingValue, missingValue, _
missingValue, missingValue, missingValue, missingValue, myFalse, missingValue, _
missingValue, missingValue)
document.Close(missingValue, missingValue, missingValue)
' Make sure all of the documents are gone from the queue
While app.BackgroundPrintingStatus > 0
System.Threading.Thread.Sleep(250)
End While
' Cleanup:
GC.Collect()
GC.WaitForPendingFinalizers()
Marshal.FinalReleaseComObject(app)
Marshal.FinalReleaseComObject(ac)
document = Nothing
End Sub
'Private Sub InvokePrint(ByVal sender As Object, ByVal e As RoutedEventArgs)
' ' Create the print dialog object and set options
' Dim pDialog As New PrintDialog()
' pDialog.PageRangeSelection = PageRangeSelection.AllPages
' pDialog.UserPageRangeEnabled = True
' ' Display the dialog. This returns true if the user presses the Print button.
' Dim print As Nullable(Of [Boolean]) = pDialog.ShowDialog()
' If print = True Then
' Dim xpsDocument As New XpsDocument("C:\FixedDocumentSequence.xps", FileAccess.ReadWrite)
' Dim fixedDocSeq As FixedDocumentSequence = xpsDocument.GetFixedDocumentSequence()
' pDialog.PrintDocument(fixedDocSeq.DocumentPaginator, "Test print job")
' End If
'End Sub
Private Sub PrintMyExcelFile()
Dim excelApp As New Microsoft.Office.Interop.Excel.Application()
' Open the Workbook:
Dim wb As Microsoft.Office.Interop.Excel.Workbook = excelApp.Workbooks.Open("E:\Personal\Personal\Medical\Card.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing)
' Get the first worksheet.
' (Excel uses base 1 indexing, not base 0.)
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = DirectCast(wb.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)
' Print out 1 copy to the default printer:
'Dim app As Microsoft.Office.Interop.Excel.Application = excelApp.Application
'Dim lsPriterName As String
'Dim d As New PrintDialog()
'If d.ShowDialog() = DialogResult.OK Then
' lsPriterName = d.PrinterSettings.PrinterName
'Else
' Exit Sub
'End If
'ws.ActivePrinter = lsPriterName
'ws.ActiveDocument.PrintOutOld(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
' Type.Missing, Type.Missing)
ws.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing)
' Cleanup:
GC.Collect()
GC.WaitForPendingFinalizers()
Marshal.FinalReleaseComObject(ws)
wb.Close(False, Type.Missing, Type.Missing)
Marshal.FinalReleaseComObject(wb)
excelApp.Quit()
Marshal.FinalReleaseComObject(excelApp)
End Sub
Public Function PrintPDF(ByVal PDFFile As String, ByVal PrinterName As String, ByVal Timeout As Integer) As Integer
Dim d As New PrintDialog()
If d.ShowDialog() = DialogResult.OK Then
PrinterName = d.PrinterSettings.PrinterName
Else
Exit Function
End If
If PrinterName.Trim.Length = 0 Then
PrinterName = (New System.Drawing.Printing.PrinterSettings).PrinterName
End If
' Dim Proc As New System.Diagnostics.Process
Proc.EnableRaisingEvents = True
Proc.StartInfo.FileName = PDFFile
Proc.StartInfo.Arguments = Chr(34) + PrinterName + Chr(34)
Proc.StartInfo.Verb = "PrintTo"
Proc.StartInfo.WindowStyle = ProcessWindowStyle.Minimized
Proc.StartInfo.CreateNoWindow = True
' Now start monitoring the printer's queue.
Dim Monitor As New PrinterQueueWatch.PrinterMonitorComponent
Monitor.MonitorJobAddedEvent = False
Monitor.MonitorJobDeletedEvent = False
Monitor.MonitorJobSetEvent = True
Monitor.MonitorJobWrittenEvent = False
Monitor.MonitorPrinterChangeEvent = False
AddHandler Monitor.JobSet, AddressOf SetPrintJob
Monitor.DeviceName = PrinterName
' Now that I am watching, start up Acrobat.
Proc.Start()
Do While Timeout > 0 AndAlso Not Proc.HasExited
System.Threading.Thread.Sleep(1000)
Timeout -= 1
Loop
' Stop monitoring.
RemoveHandler Monitor.JobSet, AddressOf SetPrintJob
Monitor = Nothing
If Not Proc.HasExited Then
Debug.Print("Killing process")
Proc.Kill()
End If
Debug.WriteLine("Closing process")
Proc.Close()
Return 0
End Function
Public Function PrintPDF(ByVal PDFFile As String) As Integer
Return PrintPDF(PDFFile, "", 60)
End Function
Public Function PrintPDF(ByVal PDFFile As String, ByVal Timeout As Integer) As Integer
Return PrintPDF(PDFFile, "", Timeout)
End Function
Private Sub SetPrintJob(ByVal sender As Object, ByVal e As System.EventArgs)
' Print job is set to print.
System.Threading.Thread.Sleep(500)
Proc.Kill()
End Sub
End Class
|
|
|
|
|
Dim excelApp As New Microsoft.Office.Interop.Excel.Application()
Dim wb As Microsoft.Office.Interop.Excel.Workbook = excelApp.Workbooks.Open("E:\Personal\Personal\Medical\Card.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing, Type.Missing)
Dim ws As Microsoft.Office.Interop.Excel.Worksheet = DirectCast(wb.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)
ws.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
Type.Missing, Type.Missing)
GC.Collect()
GC.WaitForPendingFinalizers()
Marshal.FinalReleaseComObject(ws)
wb.Close(False, Type.Missing, Type.Missing)
Marshal.FinalReleaseComObject(wb)
excelApp.Quit()
Marshal.FinalReleaseComObject(excelApp)
|
|
|
|
|
Dim ac As New Microsoft.Office.Interop.Word.Application
Dim app As Microsoft.Office.Interop.Word.Application = ac.Application
app.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone
Dim filename As Object = "E:\Personal\Personal\Medical\Saravana_Nov_Activities.doc"
Dim missingValue As Object = Type.Missing
Dim document As Microsoft.Office.Interop.Word.Document = app.Documents.OpenOld(filename, missingValue, missingValue, missingValue, missingValue, missingValue, _
missingValue, missingValue, missingValue, missingValue)
app.ActivePrinter = "\\hosfs01\PCSWAP01"
Dim myTrue As Object = True
Dim myFalse As Object = False
app.ActiveDocument.PrintOutOld(myTrue, myFalse, missingValue, missingValue, missingValue, missingValue, _
missingValue, missingValue, missingValue, missingValue, myFalse, missingValue, _
missingValue, missingValue)
document.Close(missingValue, missingValue, missingValue)
While app.BackgroundPrintingStatus > 0
System.Threading.Thread.Sleep(250)
End While
ac = Nothing
app = Nothing
filename = Nothing
document = Nothing
myTrue = Nothing
myFalse = Nothing
|
|
|
|
|
The code was well commented and very easy to follow.
|
|
|
|
|
I use this code to print the word document as XPS on disk.
If I run it several time after a few executions the XPS as a result of method m_App.ActiveDocument.PrintOutOld is not correct created.
Do you have any idea of why this is happening?
Thank you very much!
|
|
|
|
|
Would this word if i wanna work with a <b>thermal printer</b>? the size of the doc is just as usual (A4).
And i guess that the cutting part can be configured in the printer...
I would be very glad if you can help me
|
|
|
|
|
|
Hi
Your code helped me.
Anyway, I want to print to PDF.
I already have my Acrobat Pro installed.
To print to PDF, I set the printer to Abobe PDF, I open the document and print.
The code is as follows:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
namespace PdfPrintTest {
public partial class Form1 : Form {
public Form1 () {
InitializeComponent();
}
private object oMissing = System.Reflection.Missing.Value;
private object oDocFileName = @"C:\SB3_document.doc";
private object oTrue = true;
private object oFalse = false;
private void button1_Click (object sender, EventArgs e) {
object oPrintFileName = Path.ChangeExtension(oDocFileName.ToString(), ".pdf");
Word.Application app = new Word.ApplicationClass();
try {
Word.Document doc = app.Documents.Open(ref oDocFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
app.ActivePrinter = "Adobe PDF";
doc.PrintOut(ref oTrue, ref oFalse, ref oMissing, ref oPrintFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oTrue, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
}
finally {
((Word._Application)app).Quit(ref oMissing, ref oMissing, ref oMissing);
}
}
}
}
The problem is that the resulting PDF file is not a valid one (that is, cannot be open with Acrobat reader). For one of my documents, the resulting file has approx. 120KB
It's strange because if I printed the file by opening the file and clicking "Print" would produce a 7KB file that is perfectly recognized...
Any help would be greatly appreciated...
Thanks.
|
|
|
|
|
Hi, I know you wrote this about a year ago, but I've figured out the solution to print PDFs from Word automatically. And I really want to thank you for posting this original code. This could save us thousands of dollars on a component that does this!!
Anyway the solution is not to print as a file or specify the file name. Then, in your default settings for Adobe PDF (in the "Printers and Faxes" dialog), set the Adobe PDF Output Folder to a specific location, uncheck "View Adobe PDF results," and uncheck "do not send fonts to "Adobe PDF."
Works like a charm. Now I'm off to load test to see if this is a feasible replacement for our component.
nano2k wrote: The problem is that the resulting PDF file is not a valid one (that is, cannot be open with Acrobat reader). For one of my documents, the resulting file has approx. 120KB Sniff
It's strange because if I printed the file by opening the file and clicking "Print" would produce a 7KB file OMG that is perfectly recognized...
Any help would be greatly appreciated...
Thanks.
|
|
|
|
|
I'm glad it helped.
Please let us know your conclusion.
Thanks.
|
|
|
|
|
I copied your code into my project but can't get it work. Which reference do I need to include making use of Word.
|
|
|
|
|
I just had to face the same problem,
here is what I found:
download
oxppia.exe (Microsoft Office XP primary interop assemblies (PIAs))
at http://www.microsoft.com/downloads.
after downloading and extraction, you need to register the required dll:
Microsoft.Office.Interop.Word.dll
...which can be done by clicking on the ".reg" file, by the way...
Choose "Add Reference",
Select "browse" tab,
locate the dll,
build the project.
hope that helped.
vrumfundel
|
|
|
|
|
Thanx it worked!!
|
|
|
|
|
Makes thing so much easier when you find people who know what they are doing and where to find it!
Thanks,
Wooka
|
|
|
|
|
<br />
Word.ApplicationClass ac = new Word.ApplicationClass();<br />
Word.Application app = ac.Application;<br />
<br />
app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;<br />
<br />
object filename = "d:\\pruebas.rtf";<br />
object missingValue = System.Reflection.Missing.Value;<br />
<br />
Word.Document document = app.Documents.OpenOld(ref filename,<br />
ref missingValue, ref missingValue, <br />
ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue);<br />
<br />
<br />
object myTrue = true;
object myFalse = false;<br />
<br />
app.ActiveDocument.PrintOutOld(ref myTrue, <br />
ref myFalse, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, <br />
ref missingValue, ref missingValue, ref missingValue, ref myFalse, ref missingValue, ref missingValue, ref missingValue);<br />
<br />
document.Close(ref missingValue, ref missingValue, ref missingValue);<br />
<br />
while(app.BackgroundPrintingStatus > 0)<br />
{<br />
System.Threading.Thread.Sleep(250);<br />
}<br />
<br />
app.Quit(ref missingValue, ref missingValue, ref missingValue);<br />
|
|
|
|
|
Guys
I am trying to get my head around the .Net libraries vis a vis printing.
Are we saying that printing documents like Word and Excel (proprietary non text) objects requires the creating and reading tool (Word, Excel)?
And that printing cannot be done natively in .Net like a text or binary file?
Thanks
Stephengb
Stephengb
|
|
|
|
|
Thanks, it was very useful to me.
|
|
|
|
|
Message Closed
modified 13-Jul-15 3:23am.
|
|
|
|
|