- Remove From My Forums
-
Question
-
Guys ad like to know how to print a word document using
print file dailog…….using (PrintDialog pd = new PrintDialog()) { pd.ShowDialog(); ProcessStartInfo info = new ProcessStartInfo(@"D:documentsfiletoprint.doc"); info.Verb = "PrintTo"; info.Arguments = pd.PrinterSettings.PrinterName; info.CreateNoWindow = true; info.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(info);
Could someone Please explain to me…my program squels abt refrences that rnt there….can someone help me fix these error and explain to me
Thanx a Lot
Answers
-
-
Proposed as answer by
Wednesday, August 15, 2012 5:29 AM
-
Marked as answer by
Jason Dot Wang
Wednesday, August 15, 2012 5:30 AM
-
Proposed as answer by
-
I hope the following URLs is helpful for you.
http://www.c-sharpcorner.com/uploadfile/mahesh/printdialog-in-C-Sharp/
Please check this sample also
using (PrintDialog pd = new PrintDialog()) { pd.ShowDialog(); ProcessStartInfo info = new ProcessStartInfo(@"D:documentsfiletoprint.doc"); info.Verb = "PrintTo"; info.Arguments = pd.PrinterSettings.PrinterName; info.CreateNoWindow = true; info.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(info); }
With Thanks and Regards
Sambath Raj.C
click «Proposed As Answer by» if this post solves your problem or «Vote As Helpful» if a post has been useful to you
Happy Programming!-
Proposed as answer by
Jason Dot Wang
Wednesday, August 15, 2012 5:29 AM -
Marked as answer by
Jason Dot Wang
Wednesday, August 15, 2012 5:30 AM
-
Proposed as answer by
Introduction
I feel I need to share this pain. I have been struggling for days now to get something simple to work for me. That is to print out a Word document (RTF format) to a printer using Word. It also has to work with multiple versions of Word (so far 2000 and 2003). I thought I would share everything that I have learnt.
If you want this to work for multiple versions, install the earliest version of Word and Add Reference to its COM component and develop against these.
Next to the code…
The Code
Word.ApplicationClass ac = new Word.ApplicationClass(); Word.Application app = ac.Application; app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; object filename = "myFile.rtf"; object missingValue = Type.Type.Missing; Word.Document document = app.Documents.OpenOld(ref filename, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue); app.ActivePrinter = "My Printer Name"; object myTrue = true; object myFalse = false; m_App.ActiveDocument.PrintOutOld(ref myTrue, ref myFalse, ref missingValue, ref missingValue, ref missingValue, missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref myFalse, ref missingValue, ref missingValue, ref m_MissingValue); document.Close(ref missingValue, ref missingValue, ref missingValue); while(m_App.BackgroundPrintingStatus > 0) { System.Threading.Thread.Sleep(250); } app.Quitref missingValue, ref missingValue, ref missingValue);
I do not claim that this is perfect, but it’s as good as I can get. It works on my machine anyway.
History
- 15th July, 2005: Initial post
This member has not yet provided a Biography. Assume it’s interesting and varied, and probably something to do with programming.
I’m using the following code. When I print from notepad it get printed. But when I print from MS Word it get printed without words containing symbols. I think I have to enter doc format in code. How can I do this?
String content="";
private void btnUpload_Click(object sender, EventArgs e)
{
string fileName;
// Show the dialog and get result.
OpenFileDialog ofd = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
fileName = ofd.FileName;
var application = new Microsoft.Office.Interop.Word.Application();
//var document = application.Documents.Open(@"D:ICT.docx");
//read all text into content
content=System.IO.File.ReadAllText(fileName);
//var document = application.Documents.Open(@fileName);
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDialog printDlg = new PrintDialog();
PrintDocument printDoc = new PrintDocument();
printDoc.DocumentName = "fileName";
printDlg.Document = printDoc;
printDlg.AllowSelection = true;
printDlg.AllowSomePages = true;
//Call ShowDialog
if (printDlg.ShowDialog() == DialogResult.OK)
{
printDoc.PrintPage += new PrintPageEventHandler(pd_PrintPage);
printDoc.Print();
}
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
ev.Graphics.DrawString(content,printFont , Brushes.Black,
ev.MarginBounds.Left, 0, new StringFormat());
}
FeliceM
4,1659 gold badges47 silver badges73 bronze badges
asked Dec 27, 2013 at 15:10
1
As far as I know there are no basic functions which support reading the word format and / or printing it with the default Print Functionality in .net .
IF you just want to print the document without any further information you can start a basic windows print process by using the Start method of the Process Class with the PrintTo Verb
s. MSDN Forum Print Word Document in c#
Example form the linkes post:
using (PrintDialog pd = new PrintDialog())
{
pd.ShowDialog();
ProcessStartInfo info = new ProcessStartInfo(@"D:documentsfiletoprint.doc");
info.Verb = "PrintTo";
info.Arguments = pd.PrinterSettings.PrinterName;
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(info);
}
If you need to do more (layout, other data …) you could write your own doc / docx parser or use something like the aspose tools
s. http://www.aspose.com/.net/word-component.aspx
perhaps infragistics / devexpress may also components to read word documents, convert them to HTML or furthermore supporting direct printing of the word.
For all tools trial versions should be aviable
http://www.infragistics.com
https://www.devexpress.com/
answered Dec 27, 2013 at 15:18
Boas EnklerBoas Enkler
12.2k16 gold badges69 silver badges142 bronze badges
With GemBox.Document you can do silent printing or provide a print dialog and print preview, as shown in the examples for printing in WPF and printing in Windows Forms.
You can print Word documents to the default printer or specify any other local or network printer that’s connected to your machine.
The following example shows how you can silently print Word files in C# and VB.NET without the user’s interaction.
using GemBox.Document;
class Program
{
static void Main()
{
// If using the Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
DocumentModel document = DocumentModel.Load("%#Print.docx%");
// Set Word document's page options.
foreach (Section section in document.Sections)
{
PageSetup pageSetup = section.PageSetup;
pageSetup.Orientation = Orientation.Landscape;
pageSetup.LineNumberRestartSetting = LineNumberRestartSetting.NewPage;
pageSetup.LineNumberDistanceFromText = 50;
PageMargins pageMargins = pageSetup.PageMargins;
pageMargins.Top = 20;
pageMargins.Left = 100;
}
// Print Word document to default printer (e.g. 'Microsoft Print to Pdf').
string printerName = null;
document.Print(printerName);
}
}
Imports GemBox.Document
Module Program
Sub Main()
' If using the Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
Dim document As DocumentModel = DocumentModel.Load("%#Print.docx%")
' Set Word document's page options.
For Each section As Section In document.Sections
Dim pageSetup As PageSetup = section.PageSetup
pageSetup.Orientation = Orientation.Landscape
pageSetup.LineNumberRestartSetting = LineNumberRestartSetting.NewPage
pageSetup.LineNumberDistanceFromText = 50
Dim pageMargins As PageMargins = pageSetup.PageMargins
pageMargins.Top = 20
pageMargins.Left = 100
Next
' Print Word document to default printer (e.g. 'Microsoft Print to Pdf').
Dim printerName As String = Nothing
document.Print(printerName)
End Sub
End Module
GemBox.Document uses System.Printing
namespace for managing print queues and print jobs. To leverage advance printing capabilities, like specifying the printer’s paper source (tray) or specifying two-sided (duplex) printing, you can use the PrintTicket
class.
Using the PrintTicket
class, you can create an object that defines or configures the desired printer’s features. You provide that configuration in the form of an XML stream (by calling PrintTicket.GetXmlStream
method) to GemBox.Document’s PrintOptions
.
Print Word documents in a WPF application
In WPF applications you would commonly use PrintDialog
to enable users to select a printer, configure it, and perform a print job. For example, your user may specify to print only certain pages of a Word document, or to print multiple pages on one sheet of paper, or something else.
The following example shows how you can use PrintDialog
to define GemBox.Document’s print options. The example also shows how you can use the DocumentViewer
control for print previewing.
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Printing in WPF application" Height="450" Width="800">
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Margin="5">
<Button x:Name="LoadFileBtn" Content="Load" Width="100" Margin="5,0" Click="LoadFileBtn_Click"/>
<Button x:Name="PrintFileBtn" Content="Print" Width="100" Margin="5,0" Click="PrintFileBtn_Click"/>
</StackPanel>
<DocumentViewer x:Name="DocViewer"/>
</DockPanel>
</Window>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Xps.Packaging;
using Microsoft.Win32;
using GemBox.Document;
public partial class MainWindow : Window
{
private DocumentModel document;
public MainWindow()
{
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
InitializeComponent();
}
private void LoadFileBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter =
"DOCX files (*.docx, *.dotx, *.docm, *.dotm)|*.docx;*.dotx;*.docm;*.dotm" +
"|DOC files (*.doc, *.dot)|*.doc;*.dot" +
"|RTF files (*.rtf)|*.rtf" +
"|HTML files (*.html, *.htm)|*.html;*.htm" +
"|PDF files (*.pdf)|*.pdf" +
"|Word XML files (*.xml)|*.xml" +
"|TXT files (*.txt)|*.txt";
if (openFileDialog.ShowDialog() == true)
{
this.document = DocumentModel.Load(openFileDialog.FileName);
this.ShowPrintPreview();
}
}
private void PrintFileBtn_Click(object sender, RoutedEventArgs e)
{
if (this.document == null)
return;
PrintDialog printDialog = new PrintDialog() { UserPageRangeEnabled = true };
if (printDialog.ShowDialog() == true)
{
PrintOptions printOptions = new PrintOptions(printDialog.PrintTicket.GetXmlStream());
printOptions.FromPage = printDialog.PageRange.PageFrom - 1;
printOptions.ToPage = printDialog.PageRange.PageTo == 0 ? int.MaxValue : printDialog.PageRange.PageTo - 1;
this.document.Print(printDialog.PrintQueue.FullName, printOptions);
}
}
private void ShowPrintPreview()
{
XpsDocument xpsDocument = this.document.ConvertToXpsDocument(SaveOptions.XpsDefault);
// Note, XpsDocument must stay referenced so that DocumentViewer can access additional resources from it.
// Otherwise, GC will collect/dispose XpsDocument and DocumentViewer will no longer work.
this.DocViewer.Tag = xpsDocument;
this.DocViewer.Document = xpsDocument.GetFixedDocumentSequence();
}
}
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Xps.Packaging
Imports Microsoft.Win32
Imports GemBox.Document
Partial Public Class MainWindow
Inherits Window
Dim document As DocumentModel
Public Sub New()
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
InitializeComponent()
End Sub
Private Sub LoadFileBtn_Click(sender As Object, e As RoutedEventArgs)
Dim openFileDialog As New OpenFileDialog()
openFileDialog.Filter =
"DOCX files (*.docx, *.dotx, *.docm, *.dotm)|*.docx;*.dotx;*.docm;*.dotm" &
"|DOC files (*.doc, *.dot)|*.doc;*.dot" &
"|RTF files (*.rtf)|*.rtf" &
"|HTML files (*.html, *.htm)|*.html;*.htm" &
"|PDF files (*.pdf)|*.pdf" &
"|Word XML files (*.xml)|*.xml" &
"|TXT files (*.txt)|*.txt"
If (openFileDialog.ShowDialog() = True) Then
Me.document = DocumentModel.Load(openFileDialog.FileName)
Me.ShowPrintPreview()
End If
End Sub
Private Sub PrintFileBtn_Click(sender As Object, e As RoutedEventArgs)
If document Is Nothing Then Return
Dim printDialog As New PrintDialog() With {.UserPageRangeEnabled = True}
If (printDialog.ShowDialog() = True) Then
Dim printOptions As New PrintOptions(printDialog.PrintTicket.GetXmlStream())
printOptions.FromPage = printDialog.PageRange.PageFrom - 1
printOptions.ToPage = If(printDialog.PageRange.PageTo = 0, Integer.MaxValue, printDialog.PageRange.PageTo - 1)
Me.document.Print(printDialog.PrintQueue.FullName, printOptions)
End If
End Sub
Private Sub ShowPrintPreview()
Dim xpsDocument As XpsDocument = document.ConvertToXpsDocument(SaveOptions.XpsDefault)
' Note, XpsDocument must stay referenced so that DocumentViewer can access additional resources from it.
' Otherwise, GC will collect/dispose XpsDocument and DocumentViewer will no longer work.
Me.DocViewer.Tag = xpsDocument
Me.DocViewer.Document = xpsDocument.GetFixedDocumentSequence()
End Sub
End Class
Print Word documents in a Windows Forms application
You can use the same DocumentViewer
WPF control from the above example to create a print preview in Windows Forms applications as well. You can accomplish this by hosting the WPF control inside the ElementHost
Windows Forms control.
Alternatively, you can use PrintPreviewControl
and preview the Word document by providing the PrintDocument
object to the control. The following example shows how you can render a document’s pages as images and draw those images on a PrintDocument.PrintPage
event for print previewing.
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using GemBox.Document;
public partial class Form1 : Form
{
private DocumentModel document;
public Form1()
{
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
InitializeComponent();
}
private void LoadFileMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter =
"DOCX files (*.docx, *.dotx, *.docm, *.dotm)|*.docx;*.dotx;*.docm;*.dotm" +
"|DOC files (*.doc, *.dot)|*.doc;*.dot" +
"|RTF files (*.rtf)|*.rtf" +
"|HTML files (*.html, *.htm)|*.html;*.htm" +
"|PDF files (*.pdf)|*.pdf" +
"|Word XML files (*.xml)|*.xml" +
"|TXT files (*.txt)|*.txt";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
this.document = DocumentModel.Load(openFileDialog.FileName);
this.ShowPrintPreview();
}
}
private void PrintFileMenuItem_Click(object sender, EventArgs e)
{
if (this.document == null)
return;
PrintDialog printDialog = new PrintDialog() { AllowSomePages = true };
if (printDialog.ShowDialog() == DialogResult.OK)
{
PrinterSettings printerSettings = printDialog.PrinterSettings;
PrintOptions printOptions = new PrintOptions();
// Set PrintOptions properties based on PrinterSettings properties.
printOptions.CopyCount = printerSettings.Copies;
printOptions.FromPage = printerSettings.FromPage == 0 ? 0 : printerSettings.FromPage - 1;
printOptions.ToPage = printerSettings.ToPage == 0 ? int.MaxValue : printerSettings.ToPage - 1;
this.document.Print(printerSettings.PrinterName, printOptions);
}
}
private void ShowPrintPreview()
{
// Create image for each Word document's page.
Image[] images = this.CreatePrintPreviewImages();
int imageIndex = 0;
// Draw each page's image on PrintDocument for print preview.
var printDocument = new PrintDocument();
printDocument.PrintPage += (sender, e) =>
{
using (Image image = images[imageIndex])
{
var graphics = e.Graphics;
var region = graphics.VisibleClipBounds;
// Rotate image if it has landscape orientation.
if (image.Width > image.Height)
image.RotateFlip(RotateFlipType.Rotate270FlipNone);
graphics.DrawImage(image, 0, 0, region.Width, region.Height);
}
++imageIndex;
e.HasMorePages = imageIndex < images.Length;
};
this.PageUpDown.Value = 1;
this.PageUpDown.Maximum = images.Length;
this.PrintPreviewControl.Document = printDocument;
}
private Image[] CreatePrintPreviewImages()
{
var pages = this.document.GetPaginator().Pages;
var images = new Image[pages.Count];
var imageOptions = new ImageSaveOptions();
for (int pageIndex = 0; pageIndex < pages.Count; ++pageIndex)
{
var imageStream = new MemoryStream();
pages[pageIndex].Save(imageStream, imageOptions);
images[pageIndex] = Image.FromStream(imageStream);
}
return images;
}
private void PageUpDown_ValueChanged(object sender, EventArgs e)
{
this.PrintPreviewControl.StartPage = (int)this.PageUpDown.Value - 1;
}
}
Imports System
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.IO
Imports System.Windows.Forms
Imports GemBox.Document
Partial Public Class Form1
Inherits Form
Dim document As DocumentModel
Public Sub New()
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
InitializeComponent()
End Sub
Private Sub LoadFileMenuItem_Click(sender As Object, e As EventArgs) Handles LoadFileMenuItem.Click
Dim openFileDialog As New OpenFileDialog()
openFileDialog.Filter =
"DOCX files (*.docx, *.dotx, *.docm, *.dotm)|*.docx;*.dotx;*.docm;*.dotm" &
"|DOC files (*.doc, *.dot)|*.doc;*.dot" &
"|RTF files (*.rtf)|*.rtf" &
"|HTML files (*.html, *.htm)|*.html;*.htm" &
"|PDF files (*.pdf)|*.pdf" &
"|Word XML files (*.xml)|*.xml" &
"|TXT files (*.txt)|*.txt"
If (openFileDialog.ShowDialog() = DialogResult.OK) Then
Me.document = DocumentModel.Load(openFileDialog.FileName)
Me.ShowPrintPreview()
End If
End Sub
Private Sub PrintFileMenuItem_Click(sender As Object, e As EventArgs) Handles PrintFileMenuItem.Click
If Me.document Is Nothing Then Return
Dim printDialog As New PrintDialog() With {.AllowSomePages = True}
If (printDialog.ShowDialog() = DialogResult.OK) Then
Dim printerSettings As PrinterSettings = printDialog.PrinterSettings
Dim printOptions As New PrintOptions()
' Set PrintOptions properties based on PrinterSettings properties.
printOptions.CopyCount = printerSettings.Copies
printOptions.FromPage = If(printerSettings.FromPage = 0, 0, printerSettings.FromPage - 1)
printOptions.ToPage = If(printerSettings.ToPage = 0, Integer.MaxValue, printerSettings.ToPage - 1)
Me.document.Print(printerSettings.PrinterName, printOptions)
End If
End Sub
Private Sub ShowPrintPreview()
' Create image for each Word document's page.
Dim images As Image() = Me.CreatePrintPreviewImages()
Dim imageIndex As Integer = 0
' Draw each page's image on PrintDocument for print preview.
Dim printDocument = New PrintDocument()
AddHandler printDocument.PrintPage,
Sub(sender, e)
Using image As Image = images(imageIndex)
Dim graphics = e.Graphics
Dim region = graphics.VisibleClipBounds
' Rotate image if it has landscape orientation.
If image.Width > image.Height Then image.RotateFlip(RotateFlipType.Rotate270FlipNone)
graphics.DrawImage(image, 0, 0, region.Width, region.Height)
End Using
imageIndex += 1
e.HasMorePages = imageIndex < images.Length
End Sub
Me.PageUpDown.Value = 1
Me.PageUpDown.Maximum = images.Length
Me.printPreviewControl.Document = printDocument
End Sub
Private Function CreatePrintPreviewImages() As Image()
Dim pages = Me.document.GetPaginator().Pages
Dim images = New Image(pages.Count - 1) {}
Dim imageOptions As New ImageSaveOptions()
For pageIndex As Integer = 0 To pages.Count - 1
Dim imageStream = New MemoryStream()
pages(pageIndex).Save(imageStream, imageOptions)
images(pageIndex) = Image.FromStream(imageStream)
Next
Return images
End Function
Private Sub PageUpDown_ValueChanged(sender As Object, e As EventArgs) Handles PageUpDown.ValueChanged
Me.printPreviewControl.StartPage = Me.PageUpDown.Value - 1
End Sub
End Class
GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API. How about testing it today?
Download Buy
Published: December 13, 2018 | Modified: December 19, 2022 | Author: Damir Stipinovic
Сообщение от Kenedy
C# | ||
|
Попробовал этим способом на разных ПК… выдает ошибку принтера(как будто принтер не доступен, нет бумаги, закончились чернила.. и т.д.)
Добавлено через 5 часов 18 минут
Печать я сделал. Надо было только убрать строку
C# | ||
|
А в предворительном просмотре, я как понимаю, надо преобразовать StreamReader (System.IO) в Microsoft.Office.Interop.Word
Добавлено через 18 часов 36 минут
Сообщение от Kenedy
C# | ||
|
А от кда берется команда «PrintTo»??? я в надстройках офиса не нашел ее
Добавлено через 24 минуты
По поводу предварительного просмотра… конечно можно Word открыть в richTextBox и потом в printPreviewDialog. Но надо сразу в printPreviewDialog(без richTextBox).
Добавлено через 6 часов 51 минуту
Что то мыслей нет про просмотр…