В этом пошаговом руководстве мы подробно расскажем, как распечатать документ Word на C# без взаимодействия и без автоматизации. Мы будем использовать приложение Windows Forms для печати Word DOCX на C# с помощью диалогового окна принтера.
Шаги для печати документа Word в С# без взаимодействия
- Установите пакет Aspose.Words for .NET с сайта NuGet.org.
- Добавить ссылку на пространства имен Aspose.Words и Aspose.Words.Rendering
- Установите лицензию Aspose.Words для .NET с помощью метода SetLicense
- Создайте новый объект Document и загрузите документ DOCX.
- Создайте новый объект PrintDialog и задайте свойства диалогового окна принтера.
- Создайте объект PrintPreviewDialog и установите объект AsposeWordsPrintDocument и другие свойства.
- Прикрепить событие для активации диалогового окна принтера
- Наконец, покажите пользователю диалоговое окно принтера.
В приведенных выше шагах мы загружаем документ Word в объект Document, устанавливаем свойства диалогового окна принтера, а затем передаем документ в созданный экземпляр диалогового окна принтера. Эти шаги помогут распечатать документ Word на C# с помощью диалогового окна принтера Windows. Мы добавим отдельную тему с практическими рекомендациями, чтобы показать, как распечатать документ Word без диалогового окна принтера.
Код для печати документа Word на С# без автоматизации
using System; | |
using System.Windows.Forms; | |
//Add reference to Aspose.Words for .NET API | |
//Use following namespaces to print word document on a printer | |
using Aspose.Words; | |
using Aspose.Words.Rendering; | |
namespace PrintWordDocumentWithoutInterop | |
{ | |
public partial class PrintWordDocumentWithoutInterop : Form | |
{ | |
public PrintWordDocumentWithoutInterop() | |
{ | |
InitializeComponent(); | |
//Set license before printing word document to printer | |
Aspose.Words.License AsposeWordsLicense = new Aspose.Words.License(); | |
AsposeWordsLicense.SetLicense(@"c:\asposelicense\license.lic"); | |
} | |
private void PrintWordDocumentButton_Click(object sender, EventArgs e) | |
{ | |
//load the Microsoft Word document to print in Windows application | |
Document WordDocumentToPrint = new Document("WordDocumentToPrint.docx"); | |
//create Windows Forms print dialog | |
PrintDialog WindowsPrintDialog = new PrintDialog(); | |
//Set properties of the Windows Print Dialog | |
WindowsPrintDialog.PrinterSettings.MinimumPage = 1; | |
WindowsPrintDialog.PrinterSettings.MaximumPage = WordDocumentToPrint.PageCount; | |
WindowsPrintDialog.PrinterSettings.FromPage = 1; | |
WindowsPrintDialog.PrinterSettings.ToPage = WordDocumentToPrint.PageCount; | |
WindowsPrintDialog.AllowSomePages = true; | |
//Do not proceed if user didn't accept printer settings | |
if (WindowsPrintDialog.ShowDialog() != DialogResult.OK) | |
return; | |
//Create PrintDocument boject and pass printer settings | |
AsposeWordsPrintDocument PrintDocument = new AsposeWordsPrintDocument(WordDocumentToPrint); | |
PrintDocument.PrinterSettings = WindowsPrintDialog.PrinterSettings; | |
//Create print preview dialog object and pass on Word document | |
PrintPreviewDialog WindowsPrintPreviewDialog = new PrintPreviewDialog(); | |
WindowsPrintPreviewDialog.Document = PrintDocument; | |
//Set print preview dialog settings | |
WindowsPrintPreviewDialog.Document.DocumentName = WordDocumentToPrint.OriginalFileName; | |
WindowsPrintPreviewDialog.PrintPreviewControl.Zoom = 1; | |
WindowsPrintPreviewDialog.WindowState = FormWindowState.Maximized; | |
WindowsPrintPreviewDialog.MinimizeBox = true; | |
WindowsPrintPreviewDialog.ShowInTaskbar = true; | |
//Attach even to activate print dialog and bring it to front. | |
WindowsPrintPreviewDialog.Shown += WindowsPrintPreviewDialog_Shown; | |
//Display the print preview dialog so user can print | |
WindowsPrintPreviewDialog.ShowDialog(); | |
} | |
private static void WindowsPrintPreviewDialog_Shown(object sender, EventArgs e) | |
{ | |
//activate print view dialog for printing by bringging to the front | |
((PrintPreviewDialog)sender).Activate(); | |
} | |
} | |
} |
Приведенный выше код на C# print Word document без открытия самого файла DOCX или DOC. Он устанавливает свойства диалогового окна печати вместе с передачей самого документа, а затем позволяет пользователю распечатать документ.