C#/VB.NET: Word 문서 인쇄
목차
NuGet을 통해 설치됨
PM> Install-Package Spire.Doc
관련된 링크들
Word 문서 인쇄는 디지털 텍스트를 실제 사본으로 변환할 수 있는 기본 기술입니다. 보고서, 이력서, 에세이 또는 기타 서면 자료의 하드 카피를 작성해야 하는 경우 Word 문서를 효율적으로 인쇄하는 방법을 이해하면 시간을 절약하고 전문가 수준의 결과를 얻을 수 있습니다. 이 기사에서는 다음을 수행하는 방법을 배웁니다 Spire.Doc for .NET 사용하여 C# 및 VB.NET에서 지정된 인쇄 설정으로 Word 문서를 인쇄합니다.
- C#, VB.NET에서 Word 문서 인쇄
- C#, VB.NET에서 자동으로 Word 문서 인쇄
- C#, VB.NET에서 Word를 PDF로 인쇄
- C#, VB.NET에서 사용자 지정 크기 용지에 Word 인쇄
- C#, VB.NET에서 한 장에 여러 페이지 인쇄
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 PDF 및 Microsoft 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일 평가판 라이선스 요청 자신을 위해.
C#/VB.NET: Stampa documenti Word
Sommario
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
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.
- Stampa documenti Word in C#, VB.NET
- Stampa silenziosamente documenti Word in C#, VB.NET
- Stampa da Word a PDF in C#, VB.NET
- Stampa Word su carta di dimensioni personalizzate in C#, VB.NET
- Stampa più pagine su un foglio in C#, VB.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.
C#/VB.NET : imprimer des documents Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
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.
- Imprimer des documents Word en C#, VB.NET
- Imprimer silencieusement des documents Word en C#, VB.NET
- Imprimer Word en PDF en C#, VB.NET
- Imprimer Word sur un papier de taille personnalisée en C#, VB.NET
- Imprimer plusieurs pages sur une feuille en C#, VB.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.
C#/VB.NET: mesclar documentos do Word
Índice
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);
}
}
}

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);
}
}
}

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.
C#/VB.NET: объединение документов Word
Оглавление
Установлено через NuGet
PM> Install-Package Spire.Doc
Ссылки по теме
Длинные статьи или исследовательские отчеты часто составляются совместно несколькими людьми. Чтобы сэкономить время, каждый человек может работать над назначенными ему частями в отдельных документах, а затем объединять эти документы в один после завершения редактирования. Помимо ручного копирования и вставки содержимого из одного документа Word в другой, в этой статье будут продемонстрированы следующие два способа программного слияния документов Word с помощью Spire.Doc for .NET .
- Объединение документов путем вставки всего файла
- Объединение документов путем клонирования содержимого
Установите Spire.Doc for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.Doc for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.Doc
Объединение документов путем вставки всего файла
Метод Document.InsertTextFromFile(), предоставляемый Spire.Doc for .NET, позволяет объединять документы Word путем полной вставки других документов в документ. При использовании этого метода содержимое вставленного документа будет начинаться с новой страницы. Подробные шаги следующие:
- Создайте экземпляр документа.
- Загрузите исходный документ Word с помощью метода Document.LoadFromFile().
- Вставьте другой документ Word полностью в исходный документ, используя метод Document.InsertTextFromFile().
- Сохраните результирующий документ с помощью метода 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);
}
}
}

Объединение документов путем клонирования содержимого
Если вы хотите объединить документы, не начиная новую страницу, вы можете клонировать содержимое других документов, чтобы добавить их в конец исходного документа. Подробные шаги следующие:
- Загрузите два документа Word.
- Прокрутите второй документ, чтобы получить все разделы, используя свойство Document.Sections, а затем прокрутите все разделы, чтобы получить их дочерние объекты, используя свойство Section.Body.ChildObjects.
- Получите последний раздел первого документа, используя свойство Document.LastSection, а затем добавьте дочерние объекты в последний раздел первого документа, используя метод LastSection.Body.ChildObjects.Add().
- Сохраните результирующий документ с помощью метода 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);
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.
C#/VB.NET: Word-Dokumente zusammenführen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.Doc
verwandte Links
Lange Arbeiten oder Forschungsberichte werden häufig von mehreren Personen gemeinsam erstellt. Um Zeit zu sparen, kann jede Person an den ihnen zugewiesenen Teilen in separaten Dokumenten arbeiten und diese Dokumente nach Abschluss der Bearbeitung zu einem zusammenführen. Abgesehen vom manuellen Kopieren und Einfügen von Inhalten aus einem Word-Dokument in ein anderes werden in diesem Artikel die folgenden zwei Möglichkeiten zum programmgesteuerten Zusammenführen von Word-Dokumenten mit Spire.Doc for .NET .
- Führen Sie Dokumente zusammen, indem Sie die gesamte Datei einfügen
- Dokumente durch Klonen von Inhalten zusammenführen
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
Führen Sie Dokumente zusammen, indem Sie die gesamte Datei einfügen
Die von Spire.Doc for .NET bereitgestellte Methode Document.InsertTextFromFile() ermöglicht das Zusammenführen von Word-Dokumenten, indem andere Dokumente vollständig in ein Dokument eingefügt werden. Bei dieser Methode beginnt der Inhalt des eingefügten Dokuments auf einer neuen Seite. Die detaillierten Schritte sind wie folgt:
- Erstellen Sie eine Document-Instanz.
- Laden Sie das ursprüngliche Word-Dokument mit der Methode Document.LoadFromFile().
- Fügen Sie mit der Methode Document.InsertTextFromFile() ein weiteres Word-Dokument vollständig in das Originaldokument ein.
- Speichern Sie das Ergebnisdokument mit der Methode 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);
}
}
}

Dokumente durch Klonen von Inhalten zusammenführen
Wenn Sie Dokumente zusammenführen möchten, ohne eine neue Seite zu beginnen, können Sie den Inhalt anderer Dokumente klonen und am Ende des Originaldokuments hinzufügen. Die detaillierten Schritte sind wie folgt:
- Laden Sie zwei Word-Dokumente.
- Durchlaufen Sie das zweite Dokument, um alle Abschnitte mithilfe der Document.Sections-Eigenschaft abzurufen, und durchlaufen Sie dann alle Abschnitte, um deren untergeordnete Objekte mithilfe der Section.Body.ChildObjects-Eigenschaft abzurufen.
- Rufen Sie den letzten Abschnitt des ersten Dokuments mit der Eigenschaft „Document.LastSection“ ab und fügen Sie dann die untergeordneten Objekte mit der Methode „LastSection.Body.ChildObjects.Add()“ zum letzten Abschnitt des ersten Dokuments hinzu.
- Speichern Sie das Ergebnisdokument mit der Methode 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);
}
}
}

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.
C#/VB.NET: fusionar documentos de Word
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.Doc
enlaces relacionados
Los documentos largos o los informes de investigación a menudo se completan en colaboración por varias personas. Para ahorrar tiempo, cada persona puede trabajar en sus partes asignadas en documentos separados y luego combinar estos documentos en uno solo después de terminar la edición. Además de copiar y pegar manualmente el contenido de un documento de Word a otro, este artículo demostrará las siguientes dos formas de fusionar documentos de Word mediante programación usando Spire.Doc for .NET .
- Combinar documentos insertando el archivo completo
- Fusionar documentos mediante la clonación de contenidos
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
Combinar documentos insertando el archivo completo
El método Document.InsertTextFromFile() proporcionado por Spire.Doc for .NET permite fusionar documentos de Word insertando otros documentos por completo en un documento. Usando este método, el contenido del documento insertado comenzará desde una nueva página. Los pasos detallados son los siguientes:
- Cree una instancia de documento.
- Cargue el documento de Word original utilizando el método Document.LoadFromFile().
- Inserte otro documento de Word completamente en el documento original utilizando el método Document.InsertTextFromFile().
- Guarde el documento de resultados utilizando el 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);
}
}
}

Fusionar documentos mediante la clonación de contenidos
Si desea fusionar documentos sin comenzar una nueva página, puede clonar el contenido de otros documentos para agregarlos al final del documento original. Los pasos detallados son los siguientes:
- Cargue dos documentos de Word.
- Recorra el segundo documento para obtener todas las secciones usando la propiedad Document.Sections y luego recorra todas las secciones para obtener sus objetos secundarios usando la propiedad Section.Body.ChildObjects.
- Obtenga la última sección del primer documento usando la propiedad Document.LastSection y luego agregue los objetos secundarios a la última sección del primer documento usando el método LastSection.Body.ChildObjects.Add().
- Guarde el documento de resultados utilizando el 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);
}
}
}

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.
C#/VB.NET: Word 문서 병합
NuGet을 통해 설치됨
PM> Install-Package Spire.Doc
관련된 링크들
긴 논문이나 연구 보고서는 종종 여러 사람이 공동으로 작성합니다. 시간을 절약하기 위해 각 사람은 별도의 문서에서 할당된 부분을 작업한 다음 편집을 마친 후 이러한 문서를 하나로 병합할 수 있습니다. 한 Word 문서에서 다른 문서로 콘텐츠를 수동으로 복사하여 붙여넣는 것 외에도 이 기사에서는 Spire.Doc for .NET을 사용하여 프로그래밍 방식으로 Word 문서를 병합하는 다음 두 가지 방법을 보여줍니다.
Spire.Doc for .NET 설치
먼저 Spire.Doc for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.Doc
전체 파일을 삽입하여 문서 병합
Spire.Doc for .NET에서 제공하는 Document.InsertTextFromFile() 메서드를 사용하면 다른 문서를 문서에 완전히 삽입하여 Word 문서를 병합할 수 있습니다. 이 방법을 사용하면 삽입된 문서의 내용이 새 페이지에서 시작됩니다. 자세한 단계는 다음과 같습니다.
- 문서 인스턴스를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 원본 Word 문서를 로드합니다.
- Document.InsertTextFromFile() 메서드를 사용하여 원본 문서에 다른 Word 문서를 완전히 삽입합니다.
- 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);
}
}
}

콘텐츠를 복제하여 문서 병합
새 페이지를 시작하지 않고 문서를 병합하려는 경우 다른 문서의 내용을 복제하여 원본 문서 끝에 추가할 수 있습니다. 자세한 단계는 다음과 같습니다.
- 두 개의 Word 문서를 로드합니다.
- 두 번째 문서를 반복하여 Document.Sections 속성을 사용하여 모든 섹션을 가져온 다음 모든 섹션을 반복하여 Section.Body.ChildObjects 속성을 사용하여 하위 개체를 가져옵니다.
- Document.LastSection 속성을 사용하여 첫 번째 문서의 마지막 섹션을 가져온 다음 LastSection.Body.ChildObjects.Add() 메서드를 사용하여 첫 번째 문서의 마지막 섹션에 자식 개체를 추가합니다.
- 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);
}
}
}

임시 면허 신청
생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.
C#/VB.NET: unisci documenti Word
Sommario
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
Articoli lunghi o rapporti di ricerca sono spesso completati in collaborazione da più persone. Per risparmiare tempo, ogni persona può lavorare sulle parti assegnate in documenti separati e quindi unire questi documenti in uno solo dopo aver terminato la modifica. Oltre a copiare e incollare manualmente il contenuto da un documento di Word a un altro, questo articolo illustrerà i seguenti due modi per unire i documenti di Word a livello di codice 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
Unisci documenti inserendo l'intero file
Il metodo Document.InsertTextFromFile() fornito da Spire.Doc for .NET consente di unire documenti Word inserendo altri documenti interamente in un documento. Utilizzando questo metodo, il contenuto del documento inserito partirà da una nuova pagina. I passaggi dettagliati sono i seguenti:
- Crea un'istanza di Documento.
- Carica il documento Word originale utilizzando il metodo Document.LoadFromFile().
- Inserisci un altro documento Word interamente nel documento originale utilizzando il metodo Document.InsertTextFromFile().
- Salva il documento del risultato utilizzando il metodo 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);
}
}
}

Unisci documenti clonando i contenuti
Se desideri unire documenti senza iniziare una nuova pagina, puoi clonare il contenuto di altri documenti da aggiungere alla fine del documento originale. I passaggi dettagliati sono i seguenti:
- Carica due documenti Word.
- Eseguire il ciclo del secondo documento per ottenere tutte le sezioni utilizzando la proprietà Document.Sections, quindi eseguire il ciclo di tutte le sezioni per ottenere i relativi oggetti figlio utilizzando la proprietà Section.Body.ChildObjects.
- Ottieni l'ultima sezione del primo documento utilizzando la proprietà Document.LastSection, quindi aggiungi gli oggetti figlio all'ultima sezione del primo documento utilizzando il metodo LastSection.Body.ChildObjects.Add().
- Salva il documento del risultato utilizzando il metodo 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);
}
}
}

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.
C#/VB.NET : fusionner des documents Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
Les longs articles ou rapports de recherche sont souvent rédigés en collaboration par plusieurs personnes. Pour gagner du temps, chaque personne peut travailler sur les parties qui lui sont assignées dans des documents séparés, puis fusionner ces documents en un seul après avoir terminé l'édition. Outre la copie et le collage manuels du contenu d'un document Word à un autre, cet article présente les deux manières suivantes de fusionner des documents Word par programmation à 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
Fusionner des documents en insérant le fichier entier
La méthode Document.InsertTextFromFile() fournie par Spire.Doc for .NET permet de fusionner des documents Word en insérant entièrement d'autres documents dans un document. En utilisant cette méthode, le contenu du document inséré commencera à partir d'une nouvelle page. Les étapes détaillées sont les suivantes :
- Créez une instance de document.
- Chargez le document Word d'origine à l'aide de la méthode Document.LoadFromFile().
- Insérez entièrement un autre document Word dans le document d'origine à l'aide de la méthode Document.InsertTextFromFile().
- Enregistrez le document de résultat à l'aide de la méthode 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);
}
}
}

Fusionner des documents en clonant le contenu
Si vous souhaitez fusionner des documents sans commencer une nouvelle page, vous pouvez cloner le contenu d'autres documents à ajouter à la fin du document d'origine. Les étapes détaillées sont les suivantes :
- Chargez deux documents Word.
- Parcourez le deuxième document pour obtenir toutes les sections à l'aide de la propriété Document.Sections, puis parcourez toutes les sections pour obtenir leurs objets enfants à l'aide de la propriété Section.Body.ChildObjects.
- Obtenez la dernière section du premier document à l'aide de la propriété Document.LastSection, puis ajoutez les objets enfants à la dernière section du premier document à l'aide de la méthode LastSection.Body.ChildObjects.Add().
- Enregistrez le document de résultat à l'aide de la méthode 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);
}
}
}

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.
- C#/VB.NET : insérer des listes dans un document Word
- C#/VB.NET : détecter et supprimer les macros VBA des documents Word
- C#/VB.NET : insérer des équations mathématiques dans des documents Word
- C#/VB.NET : comparer deux documents Word
- C#/VB.NET : accepter ou rejeter les modifications suivies dans Word