Il n'est pas rare au travail que nous recevions deux versions d'un document Word et que nous soyons confrontés à la nécessité de trouver les différences entre elles. La comparaison de documents est particulièrement importante et populaire dans les domaines des lois, des réglementations et de l'éducation. Dans cet article, vous apprendrez à comparer deux documents Word en C# et VB.NET en utilisant Spire.Doc for .NET.

Vous trouverez ci-dessous une capture d'écran des deux documents Word qui seront comparés.

C#/VB.NET: Compare Two Word Documents

Installer Spire.Doc for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc for .NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.Doc

Comparez deux documents et enregistrez le résultat dans un troisième document Word

L'enregistrement du résultat de la comparaison dans un document Word séparé nous permet de voir toutes les modifications apportées au document d'origine, y compris les insertions, les suppressions ainsi que les modifications de formatage. Voici les étapes pour comparer deux documents et enregistrer le résultat dans un troisième document Word à l'aide de Spire.Doc for .NET.

  • Chargez deux documents Word séparément lors de l'initialisation des objets Document.
  • Comparez ces deux documents à l'aide de la méthode Document.Compare().
  • Enregistrez le résultat dans un troisième document Word à l'aide de la méthode ;Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace CompareDocuments
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load one Word document
                Document doc1 = new Document("C:\\Users\\Administrator\\Desktop\\original.docx");
    
                //Load the other Word document
                Document doc2 = new Document("C:\\Users\\Administrator\\Desktop\\revised.docx");
    
                //Compare two documents
                doc1.Compare(doc2, "John");
    
                //Save the differences in a third document
                doc1.SaveToFile("Differences.docx", FileFormat.Docx2013);
                doc1.Dispose();
            }
        }
    }

C#/VB.NET: Compare Two Word Documents

Comparer deux documents et renvoyer les insertions et les suppressions dans les listes

Les développeurs peuvent vouloir uniquement obtenir les insertions et les suppressions au lieu de toutes les différences. Voici les étapes pour obtenir des insertions et des suppressions dans deux listes distinctes.

  • Chargez deux documents Word séparément lors de l'initialisation des objets Document.
  • Comparez deux documents à l'aide de la méthode Document.Compare().
  • Obtenez les révisions à l'aide de la fonction constructeur de la classe DifferRevisions ;.
  • Obtenez une liste des insertions via la propriété DifferRevisions.InsertRevisions.
  • Obtenez une liste des suppressions via la propriété DifferRevisions.DeleteRevisions.
  • Parcourez les éléments des deux listes pour obtenir l'insertion et la suppression spécifiques.
  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Fields;
    using System;
    
    namespace GetDifferencesInList
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load one Word document
                Document doc1 = new Document("C:\\Users\\Administrator\\Desktop\\original.docx");
    
                //Load the other Word document
                Document doc2 = new Document("C:\\Users\\Administrator\\Desktop\\revised.docx");
    
                //Compare the two Word documents
                doc1.Compare(doc2, "Author");
    
                //Get the revisions
                DifferRevisions differRevisions = new DifferRevisions(doc1);
    
                //Return the insertion revisions in a list
                var insetRevisionsList = differRevisions.InsertRevisions;
    
                //Return the deletion revisions in a list
                var deletRevisionsList = differRevisions.DeleteRevisions;
    
                //Create two int variables
                int m = 0;
                int n = 0;
    
                //Loop through the insertion revision list
                for (int i = 0; i < insetRevisionsList.Count; i++)
                {
                    if (insetRevisionsList[i] is TextRange)
                    {
                        m += 1;
                        //Get the specific revision and get its content
                        TextRange textRange = insetRevisionsList[i] as TextRange;
                        Console.WriteLine("Insertion #" + m + ":" + textRange.Text);
                    }
                }
                Console.WriteLine("=====================");
    
                //Loop through the deletion revision list
                for (int i = 0; i < deletRevisionsList.Count; i++)
                {
                    if (deletRevisionsList[i] is TextRange)
                    {
                        n += 1;
                        //Get the specific revision and get its content
                        TextRange textRange = deletRevisionsList[i] as TextRange;
                        Console.WriteLine("Deletion #" + n + ":" + textRange.Text);
                    }
                }
                Console.ReadKey();
            }
        }
    }

C#/VB.NET: Compare Two Word Documents

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Monday, 31 July 2023 07:21

C#/VB.NET: imprimir documentos do Word

A impressão de documentos do Word é uma habilidade fundamental que permite converter seu texto digital em cópias físicas. Se você precisa criar cópias impressas de relatórios, currículos, redações ou qualquer outro material escrito, entender como imprimir documentos do Word com eficiência pode economizar tempo e garantir resultados com aparência profissional. Neste artigo, você aprenderá como imprimir um documento do Word com as configurações de impressão especificadas em C# e VB.NET usando o Spire.Doc for .NET.

Instalar o Spire.Doc for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for .NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.Doc

Imprimir documentos do Word em C#, VB.NET

Com a ajuda da classe PrintDocument, os programadores podem enviar um documento do Word para uma impressora específica e especificar as configurações de impressão, como intervalo de páginas, número de cópias, impressão duplex e tamanho do papel. As etapas detalhadas para imprimir um documento do Word usando o Spire.Doc for NET são as seguintes.

  • Crie um objeto Documento.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha o objeto PrintDocument através da propriedade Document.PrintDocument.
  • Especifique o nome da impressora por meio da propriedade PrintDocument.PrinterSettings.PrinterName.
  • Especifique o intervalo de páginas a imprimir por meio da propriedade PrintDocument.PrinterSettings.PrinterName.
  • Defina o número de cópias a serem impressas por meio da propriedade PrintDocument.PrinterSettings.Copies.
  • Imprima o documento usando o método PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the range of pages to print
                printDoc.PrinterSettings.FromPage = 1;
                printDoc.PrinterSettings.ToPage = 10;
    
                //Set the number of copies to print
                printDoc.PrinterSettings.Copies = 1;
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprimir silenciosamente documentos do Word em C#, VB.NET

A impressão silenciosa é um método de impressão que não mostra nenhum processo ou status de impressão. Para ativar a impressão silenciosa, defina o controlador de impressão como StandardPrintController. A seguir estão as etapas detalhadas.

  • Crie um objeto Documento.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha o objeto PrintDocument através da propriedade Document.PrintDocument.
  • Especifique o nome da impressora por meio da propriedade PrintDocument.PrinterSettings.PrinterName.
  • Defina o controlador de impressão como StandardPrintController por meio da propriedade PrintDocument.PrintController.
  • Imprima o documento usando o método PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace SilentlyPrintWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the print controller to StandardPrintController
                printDoc.PrintController = new StandardPrintController();
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprimir Word para PDF em C #, VB.NET

Além de imprimir documentos do Word com uma impressora física, você também pode imprimir documentos com impressoras virtuais, como Microsoft Print to PDF e Microsoft XPS Document Writer. A seguir estão as etapas para imprimir Word em PDF usando o Spire.Doc for .NET.

  • Crie um objeto Documento.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha o objeto PrintDocument através da propriedade Document.PrintDocument.
  • Especifique o nome da impressora como “Microsoft Print to PDF” por meio da propriedade PrintDocument.PrinterSettings.PrinterName.
  • Especifique o caminho e o nome do arquivo de saída por meio da propriedade PrintDocument.PrinterSettings.PrintFileName.
  • Imprima o documento usando o método PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordToPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Print the document to file
                printDoc.PrinterSettings.PrintToFile = true;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    
                //Specify the output file path and name
                printDoc.PrinterSettings.PrintFileName = @"C:\Users\Administrator\Desktop\ToPDF.pdf";
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprima o Word em um papel de tamanho personalizado em C#, VB.NET

A configuração do tamanho do papel é necessária quando você precisa garantir que a saída impressa atenda aos requisitos de tamanho específicos ou se adapte a uma finalidade específica. A seguir estão as etapas para imprimir o Word em um pager de tamanho personalizado usando o Spire.Doc for .NET.

  • Crie um objeto Documento.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha o objeto PrintDocument através da propriedade Document.PrintDocument.
  • Especifique o nome da impressora por meio da propriedade PrintDocument.PrinterSettings.PrinterName.
  • Especifique o tamanho do papel através da propriedade PrintDocument.DefaultPageSettings.PaperSize.
  • Imprima o documento usando o método PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintOnCustomSizedPaper
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF(HP Color LaserJet MFP M281fdw)";
    
                //Specify the paper size
                printDoc.DefaultPageSettings.PaperSize = new PaperSize("custom", 500, 800);
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprima várias páginas em uma folha em C #, VB.NET

Imprimir várias páginas em uma única folha de papel pode ajudar a economizar papel e criar manuais ou livretos compactos. As etapas para imprimir várias páginas em uma folha são as seguintes.

  • Crie um objeto Documento.
  • Carregue um documento do Word usando o método Document.LoadFromFile().
  • Obtenha o objeto PrintDocument através da propriedade Document.PrintDocument.
  • Especifique o nome da impressora por meio da propriedade PrintDocument.PrinterSettings.PrinterName.
  • Especifique o número de páginas a serem impressas em uma página e imprima o documento usando o método Doucment.PrintMultipageToOneSheet().

Observação: esse recurso NÃO se aplica ao .NET Framework 5.0 ou superior.

  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Printing;
    using System.Drawing.Printing;
    
    namespace PrintMultiplePagesOnOneSheet
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Instantiate an instance of the Document class
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Enable single-sided printing
                printDoc.PrinterSettings.Duplex = Duplex.Simplex;
    
                //Specify the number of pages to be printed on one page and print the document
                doc.PrintMultipageToOneSheet(PagesPreSheet.TwoPages, false);
            }
        }
    }

Solicitar uma licença temporária

Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Печать документов Word — это фундаментальный навык, позволяющий преобразовывать цифровой текст в физические копии. Независимо от того, нужно ли вам создавать печатные копии отчетов, резюме, эссе или любых других письменных материалов, понимание того, как эффективно печатать документы Word, может сэкономить время и обеспечить профессиональные результаты. В этой статье вы узнаете, как распечатать документ Word с указанными параметрами печати в C# и VB.NET с помощью Spire.Doc for .NET.

Установите Spire.Doc for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.Doc

Печать документов Word на C#, VB.NET

С помощью класса PrintDocument программисты могут отправить документ Word на определенный принтер и указать параметры печати, такие как диапазон страниц, количество копий, двусторонняя печать и размер бумаги. Ниже приведены подробные инструкции по печати документа Word с помощью Spire.Doc for NET.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера через свойство PrintDocument.PrinterSettings.PrinterName.
  • Укажите диапазон страниц для печати через свойство PrintDocument.PrinterSettings.PrinterName.
  • Задайте количество копий для печати через свойство PrintDocument.PrinterSettings.Copies.
  • Распечатайте документ с помощью метода PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the range of pages to print
                printDoc.PrinterSettings.FromPage = 1;
                printDoc.PrinterSettings.ToPage = 10;
    
                //Set the number of copies to print
                printDoc.PrinterSettings.Copies = 1;
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Автоматическая печать документов Word на C#, VB.NET

Тихая печать — это метод печати, при котором процесс или состояние печати не отображаются. Чтобы включить автоматическую печать, установите для контроллера печати значение StandardPrintController. Ниже приведены подробные шаги.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера через свойство PrintDocument.PrinterSettings.PrinterName.
  • Установите для контроллера печати значение StandardPrintController через свойство PrintDocument.PrintController.
  • Распечатайте документ с помощью метода PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace SilentlyPrintWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the print controller to StandardPrintController
                printDoc.PrintController = new StandardPrintController();
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Печать Word в PDF на C#, VB.NET

Помимо печати документов Word на физическом принтере, вы также можете печатать документы на виртуальных принтерах, таких как Microsoft Print to PDF и Microsoft XPS Document Writer. Ниже приведены шаги для печати Word в PDF с помощью Spire.Doc for .NET.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера как «Microsoft Print to PDF» через свойство PrintDocument.PrinterSettings.PrinterName.
  • Укажите путь и имя выходного файла через свойство PrintDocument.PrinterSettings.PrintFileName.
  • Распечатайте документ с помощью метода PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordToPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Print the document to file
                printDoc.PrinterSettings.PrintToFile = true;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    
                //Specify the output file path and name
                printDoc.PrinterSettings.PrintFileName = @"C:\Users\Administrator\Desktop\ToPDF.pdf";
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Печать Word на бумаге нестандартного размера в C#, VB.NET

Установка размера бумаги необходима, когда вам нужно убедиться, что распечатка соответствует определенным требованиям к размеру или адаптируется к определенной цели. Ниже приведены шаги для печати Word на пейджере нестандартного размера с использованием Spire.Doc for .NET.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера через свойство PrintDocument.PrinterSettings.PrinterName.
  • Укажите размер бумаги через свойство PrintDocument.DefaultPageSettings.PaperSize.
  • Распечатайте документ с помощью метода PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintOnCustomSizedPaper
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF(HP Color LaserJet MFP M281fdw)";
    
                //Specify the paper size
                printDoc.DefaultPageSettings.PaperSize = new PaperSize("custom", 500, 800);
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Печать нескольких страниц на одном листе в C#, VB.NET

Печать нескольких страниц на одном листе бумаги позволяет сэкономить бумагу и создавать компактные справочники или буклеты. Шаги для печати нескольких страниц на одном листе следующие.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера через свойство PrintDocument.PrinterSettings.PrinterName.
  • Укажите количество страниц, которое должно быть напечатано на одной странице, и распечатайте документ с помощью метода Doucment.PrintMultipageToOneSheet().

Примечание. Эта функция НЕ применима к .NET Framework 5.0 или выше.

  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Printing;
    using System.Drawing.Printing;
    
    namespace PrintMultiplePagesOnOneSheet
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Instantiate an instance of the Document class
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Enable single-sided printing
                printDoc.PrinterSettings.Duplex = Duplex.Simplex;
    
                //Specify the number of pages to be printed on one page and print the document
                doc.PrintMultipageToOneSheet(PagesPreSheet.TwoPages, false);
            }
        }
    }

Подать заявку на временную лицензию

Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.

Смотрите также

Monday, 31 July 2023 07:19

Print-Word-Documents-in-C-and-VB.NET

Печать документов Word — это фундаментальный навык, позволяющий преобразовывать цифровой текст в физические копии. Независимо от того, нужно ли вам создавать печатные копии отчетов, резюме, эссе или любых других письменных материалов, понимание того, как эффективно печатать документы Word, может сэкономить время и обеспечить профессиональные результаты. В этой статье вы узнаете, как распечатать документ Word с указанными параметрами печати в C# и VB.NET с помощью Spire.Doc for .NET.

Установите Spire.Doc for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.Doc

Печать документов Word на C#, VB.NET

С помощью класса PrintDocument программисты могут отправить документ Word на определенный принтер и указать параметры печати, такие как диапазон страниц, количество копий, двусторонняя печать и размер бумаги. Ниже приведены подробные инструкции по печати документа Word с помощью Spire.Doc for NET.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера через свойство PrintDocument.PrinterSettings.PrinterName.
  • Укажите диапазон страниц для печати через свойство PrintDocument.PrinterSettings.PrinterName.
  • Задайте количество копий для печати через свойство PrintDocument.PrinterSettings.Copies.
  • Распечатайте документ с помощью метода PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
using System.Drawing.Printing;

namespace PrintWordDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Load a Word document
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");

            //Get the PrintDocument object
            PrintDocument printDoc = doc.PrintDocument;

            //Specify the printer name
            printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";

            //Specify the range of pages to print
            printDoc.PrinterSettings.FromPage = 1;
            printDoc.PrinterSettings.ToPage = 10;

            //Set the number of copies to print
            printDoc.PrinterSettings.Copies = 1;

            //Print the document
            printDoc.Print();
        }
    }
}

Автоматическая печать документов Word на C#, VB.NET

Тихая печать — это метод печати, при котором процесс или состояние печати не отображаются. Чтобы включить автоматическую печать, установите для контроллера печати значение StandardPrintController. Ниже приведены подробные шаги.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера через свойство PrintDocument.PrinterSettings.PrinterName.
  • Установите для контроллера печати значение StandardPrintController через свойство PrintDocument.PrintController.
  • Распечатайте документ с помощью метода PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
using System.Drawing.Printing;

namespace SilentlyPrintWord
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Load a Word document
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");

            //Get the PrintDocument object
            PrintDocument printDoc = doc.PrintDocument;

            //Specify the printer name
            printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";

            //Specify the print controller to StandardPrintController
            printDoc.PrintController = new StandardPrintController();

            //Print the document
            printDoc.Print();
        }
    }
}

Печать Word в PDF на C#, VB.NET

Помимо печати документов Word на физическом принтере, вы также можете печатать документы на виртуальных принтерах, таких как Microsoft Print to PDF и Microsoft XPS Document Writer. Ниже приведены шаги для печати Word в PDF с помощью Spire.Doc for .NET.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера как «Microsoft Print to PDF» через свойство PrintDocument.PrinterSettings.PrinterName.
  • Укажите путь и имя выходного файла через свойство PrintDocument.PrinterSettings.PrintFileName.
  • Распечатайте документ с помощью метода PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
using System.Drawing.Printing;

namespace PrintWordToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Load a Word document
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");

            //Get the PrintDocument object
            PrintDocument printDoc = doc.PrintDocument;

            //Print the document to file
            printDoc.PrinterSettings.PrintToFile = true;

            //Specify the printer name
            printDoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";

            //Specify the output file path and name
            printDoc.PrinterSettings.PrintFileName = @"C:\Users\Administrator\Desktop\ToPDF.pdf";

            //Print the document
            printDoc.Print();
        }
    }
}

Печать Word на бумаге нестандартного размера в C#, VB.NET

Установка размера бумаги необходима, когда вам нужно убедиться, что распечатка соответствует определенным требованиям к размеру или адаптируется к определенной цели. Ниже приведены шаги для печати Word на пейджере нестандартного размера с использованием Spire.Doc for .NET.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера через свойство PrintDocument.PrinterSettings.PrinterName.
  • Укажите размер бумаги через свойство PrintDocument.DefaultPageSettings.PaperSize.
  • Распечатайте документ с помощью метода PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
using System.Drawing.Printing;

namespace PrintOnCustomSizedPaper
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Load a Word document
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");

            //Get the PrintDocument object
            PrintDocument printDoc = doc.PrintDocument;

            //Specify the printer name
            printDoc.PrinterSettings.PrinterName = "NPI7FE2DF(HP Color LaserJet MFP M281fdw)";

            //Specify the paper size
            printDoc.DefaultPageSettings.PaperSize = new PaperSize("custom", 500, 800);

            //Print the document
            printDoc.Print();
        }
    }
}

Печать нескольких страниц на одном листе в C#, VB.NET

Печать нескольких страниц на одном листе бумаги позволяет сэкономить бумагу и создавать компактные справочники или буклеты. Шаги для печати нескольких страниц на одном листе следующие.

  • Создайте объект документа.
  • Загрузите документ Word с помощью метода Document.LoadFromFile().
  • Получить объект PrintDocument через свойство Document.PrintDocument.
  • Укажите имя принтера через свойство PrintDocument.PrinterSettings.PrinterName.
  • Укажите количество страниц, которое должно быть напечатано на одной странице, и распечатайте документ с помощью метода Doucment.PrintMultipageToOneSheet().

Примечание. Эта функция НЕ применима к .NET Framework 5.0 или выше.

  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Printing;
using System.Drawing.Printing;

namespace PrintMultiplePagesOnOneSheet
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an instance of the Document class
            Document doc = new Document();

            //Load a Word document
            doc.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\input.docx");

            //Get the PrintDocument object
            PrintDocument printDoc = doc.PrintDocument;

            //Enable single-sided printing
            printDoc.PrinterSettings.Duplex = Duplex.Simplex;

            //Specify the number of pages to be printed on one page and print the document
            doc.PrintMultipageToOneSheet(PagesPreSheet.TwoPages, false);
        }
    }
}

Подать заявку на временную лицензию

Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.

Monday, 31 July 2023 07:18

C#/VB.NET: Word-Dokumente drucken

Das Drucken von Word-Dokumenten ist eine grundlegende Fähigkeit, die es Ihnen ermöglicht, Ihren digitalen Text in physische Kopien umzuwandeln. Ganz gleich, ob Sie Berichte, Lebensläufe, Aufsätze oder anderes schriftliches Material in Papierform erstellen müssen: Wenn Sie wissen, wie Sie Word-Dokumente effizient drucken, können Sie Zeit sparen und professionell aussehende Ergebnisse erzielen. In diesem Artikel erfahren Sie, wie das geht Drucken Sie ein Word-Dokument mit den angegebenen Druckeinstellungen in C# und VB.NET Verwendung von Spire.Doc for .NET.

Installieren Sie Spire.Doc for .NET

Zunächst müssen Sie die im Spire.Doc for .NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.Doc

Drucken Sie Word-Dokumente in C#, VB.NET

Mit Hilfe der PrintDocument-Klasse können Programmierer ein Word-Dokument an einen bestimmten Drucker senden und die Druckeinstellungen wie Seitenbereich, Anzahl der Kopien, Duplexdruck und Papierformat festlegen. Die detaillierten Schritte zum Drucken eines Word-Dokuments mit Spire.Doc for NET sind wie folgt.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie das PrintDocument-Objekt über die Document.PrintDocument-Eigenschaft ab.
  • Geben Sie den Druckernamen über die Eigenschaft PrintDocument.PrinterSettings.PrinterName an.
  • Geben Sie den Bereich der zu druckenden Seiten über die Eigenschaft PrintDocument.PrinterSettings.PrinterName an.
  • Legen Sie die Anzahl der zu druckenden Kopien über die Eigenschaft PrintDocument.PrinterSettings.Copies fest.
  • Drucken Sie das Dokument mit der Methode PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the range of pages to print
                printDoc.PrinterSettings.FromPage = 1;
                printDoc.PrinterSettings.ToPage = 10;
    
                //Set the number of copies to print
                printDoc.PrinterSettings.Copies = 1;
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Word-Dokumente in C# und VB.NET stillschweigend drucken

Beim stillen Drucken handelt es sich um eine Druckmethode, bei der kein Druckvorgang oder Status angezeigt wird. Um stilles Drucken zu aktivieren, stellen Sie den Druckcontroller auf StandardPrintController ein. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie das PrintDocument-Objekt über die Document.PrintDocument-Eigenschaft ab.
  • Geben Sie den Druckernamen über die Eigenschaft PrintDocument.PrinterSettings.PrinterName an.
  • Stellen Sie den Druckcontroller über die Eigenschaft PrintDocument.PrintController auf StandardPrintController ein.
  • Drucken Sie das Dokument mit der Methode PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace SilentlyPrintWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the print controller to StandardPrintController
                printDoc.PrintController = new StandardPrintController();
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Drucken Sie Word in C#, VB.NET als PDF

Zusätzlich zum Drucken von Word-Dokumenten mit einem physischen Drucker können Sie Dokumente auch mit virtuellen Druckern wie Microsoft Print to PDF und Microsoft XPS Document Writer drucken. Im Folgenden finden Sie die Schritte zum Drucken von Word als PDF mit Spire.Doc for .NET.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie das PrintDocument-Objekt über die Document.PrintDocument-Eigenschaft ab.
  • Geben Sie über die Eigenschaft „PrintDocument.PrinterSettings.PrinterName“ den Druckernamen „Microsoft Print to PDF“ an.
  • Geben Sie den Pfad und Namen der Ausgabedatei über die Eigenschaft PrintDocument.PrinterSettings.PrintFileName an.
  • Drucken Sie das Dokument mit der Methode PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordToPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Print the document to file
                printDoc.PrinterSettings.PrintToFile = true;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    
                //Specify the output file path and name
                printDoc.PrinterSettings.PrintFileName = @"C:\Users\Administrator\Desktop\ToPDF.pdf";
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Drucken Sie Word auf einem benutzerdefinierten Papierformat in C#, VB.NET

Das Festlegen des Papierformats ist erforderlich, wenn Sie sicherstellen möchten, dass die gedruckte Ausgabe bestimmte Größenanforderungen erfüllt oder an einen bestimmten Zweck angepasst werden kann. Im Folgenden finden Sie die Schritte zum Drucken von Word auf einem Pager in benutzerdefinierter Größe mit Spire.Doc for .NET.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie das PrintDocument-Objekt über die Document.PrintDocument-Eigenschaft ab.
  • Geben Sie den Druckernamen über die Eigenschaft PrintDocument.PrinterSettings.PrinterName an.
  • Geben Sie das Papierformat über die Eigenschaft PrintDocument.DefaultPageSettings.PaperSize an.
  • Drucken Sie das Dokument mit der Methode PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintOnCustomSizedPaper
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF(HP Color LaserJet MFP M281fdw)";
    
                //Specify the paper size
                printDoc.DefaultPageSettings.PaperSize = new PaperSize("custom", 500, 800);
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Drucken Sie mehrere Seiten auf einem Blatt in C#, VB.NET

Durch das Drucken mehrerer Seiten auf ein einziges Blatt Papier können Sie Papier sparen und kompakte Handbücher oder Broschüren erstellen. Die Schritte zum Drucken mehrerer Seiten auf einem Blatt sind wie folgt.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
  • Rufen Sie das PrintDocument-Objekt über die Document.PrintDocument-Eigenschaft ab.
  • Geben Sie den Druckernamen über die Eigenschaft PrintDocument.PrinterSettings.PrinterName an.
  • Geben Sie die Anzahl der Seiten an, die auf einer Seite gedruckt werden sollen, und drucken Sie das Dokument mit der Methode Doucment.PrintMultipageToOneSheet().

Hinweis: Diese Funktion gilt NICHT für .NET Framework 5.0 oder höher.

  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Printing;
    using System.Drawing.Printing;
    
    namespace PrintMultiplePagesOnOneSheet
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Instantiate an instance of the Document class
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Enable single-sided printing
                printDoc.PrinterSettings.Duplex = Duplex.Simplex;
    
                //Specify the number of pages to be printed on one page and print the document
                doc.PrintMultipageToOneSheet(PagesPreSheet.TwoPages, false);
            }
        }
    }

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Monday, 31 July 2023 07:17

C#/VB.NET: Imprimir documentos de Word

Imprimir documentos de Word es una habilidad fundamental que le permite convertir su texto digital en copias físicas. Ya sea que necesite crear copias impresas de informes, currículos, ensayos o cualquier otro material escrito, comprender cómo imprimir documentos de Word de manera eficiente puede ahorrar tiempo y garantizar resultados de aspecto profesional. En este artículo, aprenderá a imprimir un documento de Word con la configuración de impresión especificada en C# y VB.NET utilizando Spire.Doc for .NET.

Instalar Spire.Doc for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.Doc for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

PM> Install-Package Spire.Doc

Imprimir documentos de Word en C#, VB.NET

Con la ayuda de la clase PrintDocument, los programadores pueden enviar un documento de Word a una impresora específica y especificar la configuración de impresión, como el rango de páginas, el número de copias, la impresión dúplex y el tamaño del papel. Los pasos detallados para imprimir un documento de Word usando Spire.Doc for NET son los siguientes.

  • Cree un objeto Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Obtenga el objeto PrintDocument a través de la propiedad Document.PrintDocument.
  • Especifique el nombre de la impresora a través de la propiedad PrintDocument.PrinterSettings.PrinterName.
  • Especifique el rango de páginas para imprimir a través de la propiedad PrintDocument.PrinterSettings.PrinterName.
  • Establezca el número de copias para imprimir a través de la propiedad PrintDocument.PrinterSettings.Copies.
  • Imprima el documento utilizando el método PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the range of pages to print
                printDoc.PrinterSettings.FromPage = 1;
                printDoc.PrinterSettings.ToPage = 10;
    
                //Set the number of copies to print
                printDoc.PrinterSettings.Copies = 1;
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprima silenciosamente documentos de Word en C#, VB.NET

La impresión silenciosa es un método de impresión que no muestra ningún proceso o estado de impresión. Para habilitar la impresión silenciosa, establezca el controlador de impresión en StandardPrintController. Los siguientes son los pasos detallados.

  • Cree un objeto Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Obtenga el objeto PrintDocument a través de la propiedad Document.PrintDocument.
  • Especifique el nombre de la impresora a través de la propiedad PrintDocument.PrinterSettings.PrinterName.
  • Establezca el controlador de impresión en StandardPrintController a través de la propiedad PrintDocument.PrintController.
  • Imprima el documento utilizando el método PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace SilentlyPrintWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the print controller to StandardPrintController
                printDoc.PrintController = new StandardPrintController();
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprimir Word a PDF en C#, VB.NET

Además de imprimir documentos de Word con una impresora física, también puede imprimir documentos con impresoras virtuales, como Microsoft Print to PDF y Microsoft XPS Document Writer. Los siguientes son los pasos para imprimir Word a PDF utilizando Spire.Doc for .NET.

  • Cree un objeto Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Obtenga el objeto PrintDocument a través de la propiedad Document.PrintDocument.
  • Especifique el nombre de la impresora como "Microsoft Print to PDF" a través de la propiedad PrintDocument.PrinterSettings.PrinterName.
  • Especifique la ruta y el nombre del archivo de salida a través de la propiedad PrintDocument.PrinterSettings.PrintFileName.
  • Imprima el documento utilizando el método PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordToPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Print the document to file
                printDoc.PrinterSettings.PrintToFile = true;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    
                //Specify the output file path and name
                printDoc.PrinterSettings.PrintFileName = @"C:\Users\Administrator\Desktop\ToPDF.pdf";
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprima Word en un papel de tamaño personalizado en C#, VB.NET

La configuración del tamaño del papel es necesaria cuando necesita asegurarse de que la salida impresa cumpla con los requisitos de tamaño específicos o se adapte a un propósito particular. Los siguientes son los pasos para imprimir Word en un buscapersonas de tamaño personalizado utilizando Spire.Doc for .NET.

  • Cree un objeto Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Obtenga el objeto PrintDocument a través de la propiedad Document.PrintDocument.
  • Especifique el nombre de la impresora a través de la propiedad PrintDocument.PrinterSettings.PrinterName.
  • Especifique el tamaño del papel a través de la propiedad PrintDocument.DefaultPageSettings.PaperSize.
  • Imprima el documento utilizando el método PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintOnCustomSizedPaper
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF(HP Color LaserJet MFP M281fdw)";
    
                //Specify the paper size
                printDoc.DefaultPageSettings.PaperSize = new PaperSize("custom", 500, 800);
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprima varias páginas en una hoja en C#, VB.NET

La impresión de varias páginas en una sola hoja de papel puede ayudar a ahorrar papel y crear manuales o cuadernillos compactos. Los pasos para imprimir varias páginas en una hoja son los siguientes.

  • Cree un objeto Documento.
  • Cargue un documento de Word utilizando el método Document.LoadFromFile().
  • Obtenga el objeto PrintDocument a través de la propiedad Document.PrintDocument.
  • Especifique el nombre de la impresora a través de la propiedad PrintDocument.PrinterSettings.PrinterName.
  • Especifique el número de páginas que se imprimirán en una página e imprima el documento utilizando el método Doucment.PrintMultipageToOneSheet().

Nota: esta función NO se aplica a .NET Framework 5.0 o superior.

  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Printing;
    using System.Drawing.Printing;
    
    namespace PrintMultiplePagesOnOneSheet
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Instantiate an instance of the Document class
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Enable single-sided printing
                printDoc.PrinterSettings.Duplex = Duplex.Simplex;
    
                //Specify the number of pages to be printed on one page and print the document
                doc.PrintMultipageToOneSheet(PagesPreSheet.TwoPages, false);
            }
        }
    }

Solicitar una Licencia Temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.

Ver también

Monday, 31 July 2023 07:16

C#/VB.NET: Word 문서 인쇄

Word 문서 인쇄는 디지털 텍스트를 실제 사본으로 변환할 수 있는 기본 기술입니다. 보고서, 이력서, 에세이 또는 기타 서면 자료의 하드 카피를 작성해야 하는 경우 Word 문서를 효율적으로 인쇄하는 방법을 이해하면 시간을 절약하고 전문가 수준의 결과를 얻을 수 있습니다. 이 기사에서는 다음을 수행하는 방법을 배웁니다 Spire.Doc for .NET 사용하여 C# 및 VB.NET에서 지정된 인쇄 설정으로 Word 문서를 인쇄합니다.

Spire.Doc for .NET 설치

먼저 Spire.Doc for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 다음에서 다운로드할 수 있습니다 이 링크 또는 NuGet을 통해 설치됩니다.

PM> Install-Package Spire.Doc

C#, VB.NET에서 Word 문서 인쇄

PrintDocument 클래스의 도움으로 프로그래머는 Word 문서를 특정 프린터로 보내고 페이지 범위, 매수, 양면 인쇄 및 용지 크기와 같은 인쇄 설정을 지정할 수 있습니다. Spire.Doc for NET을 사용하여 Word 문서를 인쇄하는 자세한 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.PrintDocument 속성을 통해 PrintDocument 개체를 가져옵니다.
  • PrintDocument.PrinterSettings.PrinterName 속성을 통해 프린터 이름을 지정합니다.
  • PrintDocument.PrinterSettings.PrinterName 속성을 통해 인쇄할 페이지 범위를 지정합니다.
  • PrintDocument.PrinterSettings.Copies 속성을 통해 출력할 매수를 설정합니다.
  • PrintDocument.Print() 메서드를 사용하여 문서를 인쇄합니다.
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the range of pages to print
                printDoc.PrinterSettings.FromPage = 1;
                printDoc.PrinterSettings.ToPage = 10;
    
                //Set the number of copies to print
                printDoc.PrinterSettings.Copies = 1;
    
                //Print the document
                printDoc.Print();
            }
        }
    }

C#, VB.NET에서 자동으로 Word 문서 인쇄

무음 인쇄는 인쇄 과정이나 상태를 표시하지 않는 인쇄 방법입니다. 자동 인쇄를 활성화하려면 인쇄 컨트롤러를 StandardPrintController로 설정하십시오. 다음은 세부 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.PrintDocument 속성을 통해 PrintDocument 개체를 가져옵니다.
  • PrintDocument.PrinterSettings.PrinterName 속성을 통해 프린터 이름을 지정합니다.
  • PrintDocument.PrintController 속성을 통해 인쇄 컨트롤러를 StandardPrintController로 설정합니다.
  • PrintDocument.Print() 메서드를 사용하여 문서를 인쇄합니다.
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace SilentlyPrintWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the print controller to StandardPrintController
                printDoc.PrintController = new StandardPrintController();
    
                //Print the document
                printDoc.Print();
            }
        }
    }

C#, VB.NET에서 Word를 PDF로 인쇄

실제 프린터로 Word 문서를 인쇄하는 것 외에도 Microsoft Print to PDFMicrosoft XPS Document Writer와 같은 가상 프린터로 문서를 인쇄할 수도 있습니다. 다음은 Spire.Doc for .NET을 사용하여 Word를 PDF로 인쇄하는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.PrintDocument 속성을 통해 PrintDocument 개체를 가져옵니다.
  • PrintDocument.PrinterSettings.PrinterName 속성을 통해 프린터 이름을 "Microsoft Print to PDF"로 지정합니다.
  • PrintDocument.PrinterSettings.PrintFileName 속성을 통해 출력 파일 경로 및 이름을 지정합니다.
  • PrintDocument.Print() 메서드를 사용하여 문서를 인쇄합니다.
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordToPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Print the document to file
                printDoc.PrinterSettings.PrintToFile = true;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    
                //Specify the output file path and name
                printDoc.PrinterSettings.PrintFileName = @"C:\Users\Administrator\Desktop\ToPDF.pdf";
    
                //Print the document
                printDoc.Print();
            }
        }
    }

C#, VB.NET에서 사용자 지정 크기 용지에 Word 인쇄

인쇄된 출력이 특정 크기 요구 사항을 충족하거나 특정 목적에 맞게 조정되도록 하려면 용지 크기를 설정해야 합니다. 다음은 Spire.Doc for .NET 사용하여 사용자 정의 크기 페이저에서 Word를 인쇄하는 단계입니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.PrintDocument 속성을 통해 PrintDocument 개체를 가져옵니다.
  • PrintDocument.PrinterSettings.PrinterName 속성을 통해 프린터 이름을 지정합니다.
  • PrintDocument.DefaultPageSettings.PaperSize 속성을 통해 용지 크기를 지정합니다.
  • PrintDocument.Print() 메서드를 사용하여 문서를 인쇄합니다.
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintOnCustomSizedPaper
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF(HP Color LaserJet MFP M281fdw)";
    
                //Specify the paper size
                printDoc.DefaultPageSettings.PaperSize = new PaperSize("custom", 500, 800);
    
                //Print the document
                printDoc.Print();
            }
        }
    }

C#, VB.NET에서 한 장에 여러 페이지 인쇄

한 장의 용지에 여러 페이지를 인쇄하면 용지를 절약하고 소형 핸드북이나 소책자를 만들 수 있습니다. 한 장에 여러 페이지를 인쇄하는 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
  • Document.PrintDocument 속성을 통해 PrintDocument 개체를 가져옵니다.
  • PrintDocument.PrinterSettings.PrinterName 속성을 통해 프린터 이름을 지정합니다.
  • 한 페이지에 인쇄할 페이지 수를 지정하고 Doucment.PrintMultipageToOneSheet() 메서드를 사용하여 문서를 인쇄합니다. method.

참고: 이 기능은 .NET Framework 5.0 이상에는 적용되지 않습니다.

  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Printing;
    using System.Drawing.Printing;
    
    namespace PrintMultiplePagesOnOneSheet
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Instantiate an instance of the Document class
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Enable single-sided printing
                printDoc.PrinterSettings.Duplex = Duplex.Simplex;
    
                //Specify the number of pages to be printed on one page and print the document
                doc.PrintMultipageToOneSheet(PagesPreSheet.TwoPages, false);
            }
        }
    }

임시 면허 신청

생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.

또한보십시오

Monday, 31 July 2023 07:15

C#/VB.NET: Stampa documenti Word

La stampa di documenti Word è un'abilità fondamentale che ti consente di convertire il tuo testo digitale in copie fisiche. Sia che tu abbia bisogno di creare copie cartacee di rapporti, curriculum, saggi o qualsiasi altro materiale scritto, capire come stampare documenti Word in modo efficiente può farti risparmiare tempo e garantire risultati dall'aspetto professionale. In questo articolo imparerai come stampare un documento Word con le impostazioni di stampa specificate in C# e VB.NET utilizzando Spire.Doc for .NET.

Installa Spire.Doc for .NET

Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.Doc for .NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.Doc

Stampa documenti Word in C#, VB.NET

Con l'aiuto della classe PrintDocument, i programmatori possono inviare un documento Word a una stampante specifica e specificare le impostazioni di stampa come l'intervallo di pagine, il numero di copie, la stampa fronte/retro e il formato della carta. I passaggi dettagliati per stampare un documento Word utilizzando Spire.Doc for NET sono i seguenti.

  • Creare un oggetto documento.
  • Carica un documento Word usando il metodo Document.LoadFromFile().
  • Ottenere l'oggetto PrintDocument tramite la proprietà Document.PrintDocument.
  • Specificare il nome della stampante tramite la proprietà PrintDocument.PrinterSettings.PrinterName.
  • Specificare l'intervallo di pagine da stampare tramite la proprietà PrintDocument.PrinterSettings.PrinterName.
  • Impostare il numero di copie da stampare tramite la proprietà PrintDocument.PrinterSettings.Copies.
  • Stampare il documento utilizzando il metodo PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the range of pages to print
                printDoc.PrinterSettings.FromPage = 1;
                printDoc.PrinterSettings.ToPage = 10;
    
                //Set the number of copies to print
                printDoc.PrinterSettings.Copies = 1;
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Stampa silenziosamente documenti Word in C#, VB.NET

La stampa silenziosa è un metodo di stampa che non mostra alcun processo o stato di stampa. Per abilitare la stampa silenziosa, impostare il controller di stampa su StandardPrintController. Di seguito sono riportati i passaggi dettagliati.

  • Creare un oggetto documento.
  • Carica un documento Word usando il metodo Document.LoadFromFile().
  • Ottenere l'oggetto PrintDocument tramite la proprietà Document.PrintDocument.
  • Specificare il nome della stampante tramite la proprietà PrintDocument.PrinterSettings.PrinterName.
  • Impostare il controller di stampa su StandardPrintController tramite la proprietà PrintDocument.PrintController.
  • Stampare il documento utilizzando il metodo PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace SilentlyPrintWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the print controller to StandardPrintController
                printDoc.PrintController = new StandardPrintController();
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Stampa da Word a PDF in C#, VB.NET

Oltre a stampare documenti Word con una stampante fisica, puoi anche stampare documenti con stampanti virtuali, come Microsoft Print to PDF e Microsoft XPS Document Writer. Di seguito sono riportati i passaggi per stampare da Word a PDF utilizzando Spire.Doc for .NET.

  • Creare un oggetto documento.
  • Carica un documento Word usando il metodo Document.LoadFromFile().
  • Ottenere l'oggetto PrintDocument tramite la proprietà Document.PrintDocument.
  • Specificare il nome della stampante come "Microsoft Print to PDF" tramite la proprietà PrintDocument.PrinterSettings.PrinterName.
  • Specificare il percorso e il nome del file di output tramite la proprietà PrintDocument.PrinterSettings.PrintFileName.
  • Stampare il documento utilizzando il metodo PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordToPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Print the document to file
                printDoc.PrinterSettings.PrintToFile = true;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    
                //Specify the output file path and name
                printDoc.PrinterSettings.PrintFileName = @"C:\Users\Administrator\Desktop\ToPDF.pdf";
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Stampa Word su carta di dimensioni personalizzate in C#, VB.NET

L'impostazione del formato carta è necessaria quando è necessario garantire che l'output stampato soddisfi requisiti di formato specifici o si adatti a uno scopo particolare. Di seguito sono riportati i passaggi per stampare Word su un cercapersone di dimensioni personalizzate utilizzando Spire.Doc for .NET.

  • Creare un oggetto documento.
  • Carica un documento Word usando il metodo Document.LoadFromFile().
  • Ottenere l'oggetto PrintDocument tramite la proprietà Document.PrintDocument.
  • Specificare il nome della stampante tramite la proprietà PrintDocument.PrinterSettings.PrinterName.
  • Specificare il formato carta tramite la proprietà PrintDocument.DefaultPageSettings.PaperSize.
  • Stampare il documento utilizzando il metodo PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintOnCustomSizedPaper
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF(HP Color LaserJet MFP M281fdw)";
    
                //Specify the paper size
                printDoc.DefaultPageSettings.PaperSize = new PaperSize("custom", 500, 800);
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Stampa più pagine su un foglio in C#, VB.NET

La stampa di più pagine su un singolo foglio di carta può aiutare a risparmiare carta e creare manuali o opuscoli compatti. I passaggi per stampare più pagine su un foglio sono i seguenti.

  • Creare un oggetto documento.
  • Carica un documento Word usando il metodo Document.LoadFromFile().
  • Ottenere l'oggetto PrintDocument tramite la proprietà Document.PrintDocument.
  • Specificare il nome della stampante tramite la proprietà PrintDocument.PrinterSettings.PrinterName.
  • Specificare il numero di pagine da stampare su una pagina e stampare il documento utilizzando il metodo Doucment.PrintMultipageToOneSheet().

Nota: questa funzionalità NON è applicabile a .NET Framework 5.0 o versioni successive.

  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Printing;
    using System.Drawing.Printing;
    
    namespace PrintMultiplePagesOnOneSheet
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Instantiate an instance of the Document class
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Enable single-sided printing
                printDoc.PrinterSettings.Duplex = Duplex.Simplex;
    
                //Specify the number of pages to be printed on one page and print the document
                doc.PrintMultipageToOneSheet(PagesPreSheet.TwoPages, false);
            }
        }
    }

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

L'impression de documents Word est une compétence fondamentale qui vous permet de convertir votre texte numérique en copies physiques. Que vous ayez besoin de créer des copies papier de rapports, de CV, d'essais ou de tout autre document écrit, comprendre comment imprimer efficacement des documents Word peut vous faire gagner du temps et garantir des résultats d'aspect professionnel. Dans cet article, vous apprendrez à imprimer un document Word avec les paramètres d'impression spécifiés en C# et VB.NET à l'aide de Spire.Doc for .NET.

Installer Spire.Doc for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc for .NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.Doc

Imprimer des documents Word en C#, VB.NET

Avec l'aide de la classe PrintDocument, les programmeurs peuvent envoyer un document Word à une imprimante spécifique et spécifier les paramètres d'impression tels que la plage de pages, le nombre de copies, l'impression recto verso et la taille du papier. Les étapes détaillées pour imprimer un document Word à l'aide de Spire.Doc for NET sont les suivantes.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Obtenez l'objet PrintDocument via la propriété Document.PrintDocument.
  • Spécifiez le nom de l'imprimante via la propriété PrintDocument.PrinterSettings.PrinterName.
  • Spécifiez la plage de pages à imprimer via la propriété PrintDocument.PrinterSettings.PrinterName.
  • Définissez le nombre de copies à imprimer via la propriété PrintDocument.PrinterSettings.Copies.
  • Imprimez le document à l'aide de la méthode PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordDocument
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the range of pages to print
                printDoc.PrinterSettings.FromPage = 1;
                printDoc.PrinterSettings.ToPage = 10;
    
                //Set the number of copies to print
                printDoc.PrinterSettings.Copies = 1;
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprimer silencieusement des documents Word en C#, VB.NET

L'impression silencieuse est une méthode d'impression qui ne montre aucun processus ou état d'impression. Pour activer l'impression silencieuse, définissez le contrôleur d'impression sur StandardPrintController. Voici les étapes détaillées.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Obtenez l'objet PrintDocument via la propriété Document.PrintDocument.
  • Spécifiez le nom de l'imprimante via la propriété PrintDocument.PrinterSettings.PrinterName.
  • Définissez le contrôleur d'impression sur StandardPrintController via la propriété PrintDocument.PrintController.
  • Imprimez le document à l'aide de la méthode PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace SilentlyPrintWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF (HP Color LaserJet MFP M281fdw)";
    
                //Specify the print controller to StandardPrintController
                printDoc.PrintController = new StandardPrintController();
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprimer Word en PDF en C#, VB.NET

En plus d'imprimer des documents Word avec une imprimante physique, vous pouvez également imprimer des documents avec des imprimantes virtuelles, telles que Microsoft Print to PDF et Microsoft XPS Document Writer. Voici les étapes pour imprimer Word au format PDF à l'aide de Spire.Doc for .NET.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Obtenez l'objet PrintDocument via la propriété Document.PrintDocument.
  • Spécifiez le nom de l'imprimante en tant que "Microsoft Print to PDF" via la propriété PrintDocument.PrinterSettings.PrinterName.
  • Spécifiez le chemin et le nom du fichier de sortie via la propriété PrintDocument.PrinterSettings.PrintFileName.
  • Imprimez le document à l'aide de la méthode PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintWordToPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Print the document to file
                printDoc.PrinterSettings.PrintToFile = true;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    
                //Specify the output file path and name
                printDoc.PrinterSettings.PrintFileName = @"C:\Users\Administrator\Desktop\ToPDF.pdf";
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprimer Word sur un papier de taille personnalisée en C#, VB.NET

La définition du format de papier est nécessaire lorsque vous devez vous assurer que la sortie imprimée répond à des exigences de format spécifiques ou s'adapte à un objectif particulier. Voici les étapes à suivre pour imprimer Word sur un pager de taille personnalisée à l'aide de Spire.Doc for .NET.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Obtenez l'objet PrintDocument via la propriété Document.PrintDocument.
  • Spécifiez le nom de l'imprimante via la propriété PrintDocument.PrinterSettings.PrinterName.
  • Spécifiez le format de papier via la propriété PrintDocument.DefaultPageSettings.PaperSize.
  • Imprimez le document à l'aide de la méthode PrintDocument.Print().
  • C#
  • VB.NET
using Spire.Doc;
    using System.Drawing.Printing;
    
    namespace PrintOnCustomSizedPaper
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Specify the printer name
                printDoc.PrinterSettings.PrinterName = "NPI7FE2DF(HP Color LaserJet MFP M281fdw)";
    
                //Specify the paper size
                printDoc.DefaultPageSettings.PaperSize = new PaperSize("custom", 500, 800);
    
                //Print the document
                printDoc.Print();
            }
        }
    }

Imprimer plusieurs pages sur une feuille en C#, VB.NET

L'impression de plusieurs pages sur une seule feuille de papier peut vous aider à économiser du papier et à créer des manuels ou des livrets compacts. Les étapes pour imprimer plusieurs pages sur une feuille sont les suivantes.

  • Créez un objet Document.
  • Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
  • Obtenez l'objet rintDocumentP via la propriété Document.PrintDocument.
  • Spécifiez le nom de l'imprimante via la propriété PrintDocument.PrinterSettings.PrinterName.
  • Spécifiez le nombre de pages à imprimer sur une page et imprimez le document à l'aide de la méthode Doucment.PrintMultipageToOneSheet().

Remarque: cette fonctionnalité ne s'applique PAS à .NET Framework 5.0 ou supérieur.

  • C#
  • VB.NET
using Spire.Doc;
    using Spire.Doc.Printing;
    using System.Drawing.Printing;
    
    namespace PrintMultiplePagesOnOneSheet
    {
        internal class Program
        {
            static void Main(string[] args)
            {
                //Instantiate an instance of the Document class
                Document doc = new Document();
    
                //Load a Word document
                doc.LoadFromFile(@"C:\\Users\\Administrator\\Desktop\\input.docx");
    
                //Get the PrintDocument object
                PrintDocument printDoc = doc.PrintDocument;
    
                //Enable single-sided printing
                printDoc.PrinterSettings.Duplex = Duplex.Simplex;
    
                //Specify the number of pages to be printed on one page and print the document
                doc.PrintMultipageToOneSheet(PagesPreSheet.TwoPages, false);
            }
        }
    }

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Monday, 31 July 2023 07:11

C#/VB.NET: mesclar documentos do Word

Instalado via NuGet

PM> Install-Package Spire.Doc

Links Relacionados

Artigos longos ou relatórios de pesquisa geralmente são concluídos de forma colaborativa por várias pessoas. Para economizar tempo, cada pessoa pode trabalhar em suas partes atribuídas em documentos separados e, em seguida, mesclar esses documentos em um após concluir a edição. Além de copiar e colar manualmente o conteúdo de um documento do Word para outro, este artigo demonstrará as duas maneiras a seguir de mesclar documentos do Word programaticamente usando Spire.Doc for .NET .

Instalar o Spire.Doc for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.Doc for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.Doc

Mesclar documentos inserindo o arquivo inteiro

O método Document.InsertTextFromFile() fornecido pelo Spire.Doc for .NET permite mesclar documentos do Word inserindo outros documentos inteiramente em um documento. Usando este método, o conteúdo do documento inserido começará em uma nova página. As etapas detalhadas são as seguintes:

  • Crie uma instância de Documento.
  • Carregue o documento original do Word usando o método Document.LoadFromFile().
  • Insira outro documento do Word inteiramente no documento original usando o método Document.InsertTextFromFile().
  • Salve o documento resultante usando o método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MergeWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document instance
                Document document = new Document();
    
                //Load the original Word document
                document.LoadFromFile("Doc1.docx", FileFormat.Docx);
    
                //Insert another Word document entirely to the original document
                document.InsertTextFromFile("Doc2.docx", FileFormat.Docx);
    
                //Save the result document
                document.SaveToFile("MergedWord.docx", FileFormat.Docx);
            }
        }
    }

C#/VB.NET: Merge Word Documents

Mesclar documentos clonando conteúdo

Se você deseja mesclar documentos sem iniciar uma nova página, pode clonar o conteúdo de outros documentos para adicionar ao final do documento original. As etapas detalhadas são as seguintes:

  • Carregue dois documentos do Word.
  • Percorra o segundo documento para obter todas as seções usando a propriedade Document.Sections e, em seguida, percorra todas as seções para obter seus objetos filhos usando a propriedade Section.Body.ChildObjects.
  • Obtenha a última seção do primeiro documento usando a propriedade Document.LastSection e adicione os objetos filhos à última seção do primeiro documento usando o método LastSection.Body.ChildObjects.Add().
  • Salve o documento resultante usando o método Document.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace MergeWord
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Load two Word documents
                Document doc1 = new Document("Doc1.docx");
                Document doc2 = new Document("Doc2.docx");
    
                //Loop through the second document to get all the sections
                foreach (Section section in doc2.Sections)
                {
    
                    //Loop through the sections of the second document to get their child objects
                    foreach (DocumentObject obj in section.Body.ChildObjects)
                    {
    
                        // Get the last section of the first document
                         Section lastSection = doc1.LastSection;
    
                        //Add all child objects to the last section of the first document
                        lastSection.Body.ChildObjects.Add(obj.Clone());
                    }
                }
    
                // Save the result document
                doc1.SaveToFile("MergeDocuments.docx", FileFormat.Docx);
            }
        }
    } 

C#/VB.NET: Merge Word Documents

Solicitar uma licença temporária

Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também