C#/VB.NET: Erstellen Sie ein Word-Dokument
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
Non c'è dubbio che il documento Word sia oggi uno dei tipi di file di documento più popolari. Poiché il documento Word è un formato di file ideale per generare lettere, appunti, relazioni, tesine, romanzi e riviste, ecc. In questo articolo imparerai come creare un semplice documento Word da zero in C# e VB.NET utilizzando Spire.Doc for .NET.
Spire.Doc for .NET fornisce la classe Document per rappresentare un modello di documento Word, consentendo agli utenti di leggere e modificare documenti esistenti o crearne di nuovi. Un documento Word deve contenere almeno una sezione (rappresentata dalla classe Section) e ogni sezione è un contenitore per gli elementi base di Word come paragrafi, tabelle, intestazioni, piè di pagina e così via. La tabella seguente elenca le classi e i metodi importanti coinvolti in questo tutorial.
| Membro | Descrizione |
| Classe documento | Rappresenta un modello di documento di Word. |
| Classe di sezione | Rappresenta una sezione in un documento di Word. |
| Classe paragrafo | Rappresenta un paragrafo in una sezione. |
| Classe ParagraphStyle | Definisce le informazioni sulla formattazione del carattere che possono essere applicate a un paragrafo. |
| Metodo Section.AddParagraph() | Aggiunge un paragrafo a una sezione. |
| Metodo Paragraph.AppendText() | Aggiunge il testo a un paragrafo alla fine. |
| Metodo Paragraph.ApplyStyle() | Applica uno stile a un paragrafo. |
| Metodo Document.SaveToFile() | Salva il documento in un file Word con estensione .doc o .docx. Questo metodo supporta anche il salvataggio del documento in PDF, XPS, HTML, PLC, ecc. |
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
Crea un semplice documento Word
Di seguito sono riportati i passaggi per creare un semplice documento di Word contenente diversi paragrafi utilizzando Spire.Doc for .NET.
- Creare un oggetto documento.
- Aggiungere una sezione utilizzando il metodo Document.AddSection().
- Impostare i margini della pagina tramite la proprietà Section.PageSetUp.Margins.
- Aggiungi diversi paragrafi alla sezione usando il metodo Section.AddParagraph().
- Aggiungi testo ai paragrafi usando il metodo Paragraph.AppendText().
- Crea un oggetto ParagraphStyle e applicalo a un paragrafo specifico utilizzando il metodo Paragraph.ApplyStyle().
- Salvare il documento in un file Word utilizzando il metodo Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace CreateWordDocument
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Add a section
Section section = doc.AddSection();
//Set the page margins
section.PageSetup.Margins.All = 40f;
//Add a paragraph as title
Paragraph titleParagraph = section.AddParagraph();
titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
//Add two paragraphs as body
Paragraph bodyParagraph_1 = section.AddParagraph();
bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
"for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
"(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
Paragraph bodyParagraph_2 = section.AddParagraph();
bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
"be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
"document creation capabilities into any developers' .NET applications.");
//Create a style for title paragraph
ParagraphStyle style1 = new ParagraphStyle(doc);
style1.Name = "titleStyle";
style1.CharacterFormat.Bold = true;
style1.CharacterFormat.TextColor = Color.Purple;
style1.CharacterFormat.FontName = "Times New Roman";
style1.CharacterFormat.FontSize = 12;
doc.Styles.Add(style1);
titleParagraph.ApplyStyle("titleStyle");
//Create a style for body paragraphs
ParagraphStyle style2 = new ParagraphStyle(doc);
style2.Name = "paraStyle";
style2.CharacterFormat.FontName = "Times New Roman";
style2.CharacterFormat.FontSize = 12;
doc.Styles.Add(style2);
bodyParagraph_1.ApplyStyle("paraStyle");
bodyParagraph_2.ApplyStyle("paraStyle");
//Set the horizontal alignment of paragraphs
titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
//Set the first line indent
bodyParagraph_1.Format.FirstLineIndent = 30;
bodyParagraph_2.Format.FirstLineIndent = 30;
//Set the after spacing
titleParagraph.Format.AfterSpacing = 10;
bodyParagraph_1.Format.AfterSpacing = 10;
//Save to file
doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
}
}
}

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 : créer un document Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
Il ne fait aucun doute que le document Word est l'un des types de fichiers de documents les plus populaires aujourd'hui. Parce que le document Word est un format de fichier idéal pour générer des lettres, des mémos, des rapports, des dissertations, des romans et des magazines, etc. Dans cet article, vous apprendrez à créer un document Word simple à partir de zéro en C# et VB.NET en utilisant Spire.Doc for .NET.
Spire.Doc for .NET fournit la classe Document pour représenter un modèle de document Word, permettant aux utilisateurs de lire et de modifier des documents existants ou d'en créer de nouveaux. Un document Word doit contenir au moins une section (représentée par la classe Section) et chaque section est un conteneur pour les éléments Word de base tels que les paragraphes, les tableaux, les en-têtes, les pieds de page, etc. Le tableau ci-dessous répertorie les classes et méthodes importantes impliquées dans ce didacticiel.
| Member | Description |
| Classe de documents | Représente un modèle de document Word. |
| Classe de section | Représente une section dans un document Word. |
| Classe de paragraphe | Représente un paragraphe dans une section. |
| Classe ParagraphStyle | Définit les informations de formatage de la police pouvant être appliquées à un paragraphe. |
| Méthode Section.AddParagraph() | Ajoute un paragraphe à une section. |
| Méthode Paragraph.AppendText() | Ajoute du texte à un paragraphe à la fin. |
| Méthode Paragraph.ApplyStyle() | Applique un style à un paragraphe. |
| Méthode Document.SaveToFile() | Enregistre le document dans un fichier Word avec une extension .doc ou .docx. Cette méthode prend également en charge l'enregistrement du document au format PDF, XPS, HTML, PLC, etc. |
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
Créer un document Word simple
Voici les étapes pour créer un document Word simple contenant plusieurs paragraphes à l'aide de Spire.Doc for .NET.
- Créez un objet Document.
- Ajoutez une section à l'aide de la méthode Document.AddSection().
- Définissez les marges de la page via la propriété Section.PageSetUp.Margins.
- Ajoutez plusieurs paragraphes à la section à l'aide de la méthode Section.AddParagraph().
- Ajoutez du texte aux paragraphes à l'aide de la méthode Paragraph.AppendText().
- Créez un objet ParagraphStyle et appliquez-le à un paragraphe spécifique à l'aide de la méthode Paragraph.ApplyStyle().
- Enregistrez le document dans un fichier Word à l'aide de la méthode Document.SaveToFile().
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
namespace CreateWordDocument
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Add a section
Section section = doc.AddSection();
//Set the page margins
section.PageSetup.Margins.All = 40f;
//Add a paragraph as title
Paragraph titleParagraph = section.AddParagraph();
titleParagraph.AppendText("Introduction of Spire.Doc for .NET");
//Add two paragraphs as body
Paragraph bodyParagraph_1 = section.AddParagraph();
bodyParagraph_1.AppendText("Spire.Doc for .NET is a professional Word.NET library specifically designed " +
"for developers to create, read, write, convert, compare and print Word documents on any.NET platform " +
"(.NET Framework, .NET Core, .NET Standard, Xamarin & Mono Android) with fast and high-quality performance.");
Paragraph bodyParagraph_2 = section.AddParagraph();
bodyParagraph_2.AppendText("As an independent Word .NET API, Spire.Doc for .NET doesn't need Microsoft Word to " +
"be installed on neither the development nor target systems. However, it can incorporate Microsoft Word " +
"document creation capabilities into any developers' .NET applications.");
//Create a style for title paragraph
ParagraphStyle style1 = new ParagraphStyle(doc);
style1.Name = "titleStyle";
style1.CharacterFormat.Bold = true;
style1.CharacterFormat.TextColor = Color.Purple;
style1.CharacterFormat.FontName = "Times New Roman";
style1.CharacterFormat.FontSize = 12;
doc.Styles.Add(style1);
titleParagraph.ApplyStyle("titleStyle");
//Create a style for body paragraphs
ParagraphStyle style2 = new ParagraphStyle(doc);
style2.Name = "paraStyle";
style2.CharacterFormat.FontName = "Times New Roman";
style2.CharacterFormat.FontSize = 12;
doc.Styles.Add(style2);
bodyParagraph_1.ApplyStyle("paraStyle");
bodyParagraph_2.ApplyStyle("paraStyle");
//Set the horizontal alignment of paragraphs
titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
bodyParagraph_1.Format.HorizontalAlignment = HorizontalAlignment.Justify;
bodyParagraph_2.Format.HorizontalAlignment = HorizontalAlignment.Justify;
//Set the first line indent
bodyParagraph_1.Format.FirstLineIndent = 30;
bodyParagraph_2.Format.FirstLineIndent = 30;
//Set the after spacing
titleParagraph.Format.AfterSpacing = 10;
bodyParagraph_1.Format.AfterSpacing = 10;
//Save to file
doc.SaveToFile("WordDocument.docx", FileFormat.Docx2013);
}
}
}

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
C#/VB.NET: Converter Word para XPS
Instalado via NuGet
PM> Install-Package Spire.Doc
Links Relacionados
XPS (XML Paper Specification) é um formato de documento de layout fixo projetado para preservar a fidelidade do documento e fornecer aparência de documento independente do dispositivo. É semelhante ao PDF, mas é baseado em XML em vez de PostScript. Se você deseja salvar um documento do Word em um formato de arquivo de layout fixo, o XPS seria uma opção. Este artigo demonstrará como converter documentos do Word em XPS 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
Converter Word para XPS em C# e VB.NET
A seguir estão as etapas detalhadas para converter um documento do Word em XPS usando o Spire.Doc for .NET:
- Inicialize uma instância da classe Document.
- Carregue um documento do Word usando o método Document.LoadFromFile().
- Salve o documento do Word em XPS usando o método Document.SaveToFile(string filePath, FileFormat fileFormat).
- C#
- VB.NET
using Spire.Doc;
namespace ConvertWordToXps
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("Sample.docx");
//convert the document to XPS
doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
}
}
}

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 в XPS
Установлено через NuGet
PM> Install-Package Spire.Doc
Ссылки по теме
XPS (XML Paper Specification) — это формат документа с фиксированным макетом, предназначенный для сохранения точности документа и обеспечения независимого от устройства внешнего вида документа. Он похож на PDF, но основан на XML, а не на PostScript. Если вы хотите сохранить документ Word в формате файла с фиксированным макетом, вам подойдет XPS. В этой статье показано, как преобразовать документы Word в XPS на 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 в XPS в C# и VB.NET
Ниже приведены подробные инструкции по преобразованию документа Word в XPS с помощью Spire.Doc for .NET:
- Инициализировать экземпляр класса Document.
- Загрузите документ Word с помощью метода Document.LoadFromFile().
- Сохраните документ Word в XPS, используя метод Document.SaveToFile(string filePath, FileFormat fileFormat).
- C#
- VB.NET
using Spire.Doc;
namespace ConvertWordToXps
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("Sample.docx");
//convert the document to XPS
doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.
C#/VB.NET: Word in XPS konvertieren
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.Doc
verwandte Links
XPS (XML Paper Specification) ist ein Dokumentformat mit festem Layout, das darauf ausgelegt ist, die Wiedergabetreue des Dokuments zu wahren und ein geräteunabhängiges Erscheinungsbild des Dokuments zu ermöglichen. Es ähnelt PDF, basiert jedoch auf XML und nicht auf PostScript. Wenn Sie ein Word-Dokument in einem Dateiformat mit festem Layout speichern möchten, wäre XPS eine Option. Dieser Artikel zeigt, wie das geht Konvertieren Sie Word-Dokumente in XPS in C# und VB.NET verwenden Spire.Doc for .NET.
Installieren 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
Konvertieren Sie Word in XPS in C# und VB.NET
Im Folgenden finden Sie die detaillierten Schritte zum Konvertieren eines Word-Dokuments in XPS mit Spire.Doc for .NET:
- Initialisieren Sie eine Instanz der Document-Klasse.
- Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
- Speichern Sie das Word-Dokument mit der Methode Document.SaveToFile(string filePath, FileFormat fileFormat) in XPS.
- C#
- VB.NET
using Spire.Doc;
namespace ConvertWordToXps
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("Sample.docx");
//convert the document to XPS
doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
}
}
}

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: convertir Word a XPS
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.Doc
enlaces relacionados
XPS (Especificación de papel XML) es un formato de documento de diseño fijo diseñado para preservar la fidelidad del documento y proporcionar una apariencia de documento independiente del dispositivo. Es similar a PDF, pero se basa en XML en lugar de PostScript. Si desea guardar un documento de Word en un formato de archivo de diseño fijo, XPS sería una opción. Este artículo demostrará cómo convertir documentos de Word a XPS en C# y VB.NET usando 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 instalado a través de NuGet.
PM> Install-Package Spire.Doc
Convierta Word a XPS en C# y VB.NET
Los siguientes son los pasos detallados para convertir un documento de Word a XPS utilizando Spire.Doc for .NET:
- Inicializa una instancia de la clase Documento.
- Cargue un documento de Word utilizando el método Document.LoadFromFile().
- Guarde el documento de Word en XPS usando el método Document.SaveToFile(string filePath, FileFormat fileFormat).
- C#
- VB.NET
using Spire.Doc;
namespace ConvertWordToXps
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("Sample.docx");
//convert the document to XPS
doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
}
}
}

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를 XPS로 변환
NuGet을 통해 설치됨
PM> Install-Package Spire.Doc
관련된 링크들
XPS(XML Paper Specification)는 문서 충실도를 유지하고 장치 독립적인 문서 모양을 제공하도록 설계된 고정 레이아웃 문서 형식입니다. PDF와 유사하지만 PostScript가 아닌 XML을 기반으로 합니다. Word 문서를 고정 레이아웃 파일 형식으로 저장하려면 XPS가 옵션입니다. 이 문서에서는 다음을 수행하는 방법을 보여줍니다 C# 및 VB.NET에서 Word 문서를 XPS로 변환 Spire.Doc for .NET 사용.
Spire.Doc for .NET 설치
먼저 Spire.Doc for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.Doc
C# 및 VB.NET에서 Word를 XPS로 변환
다음은 Spire.Doc for .NET을 사용하여 Word 문서를 XPS로 변환하는 자세한 단계입니다.
- Document 클래스의 인스턴스를 초기화합니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- Document.SaveToFile(string filePath, FileFormat fileFormat) 메서드를 사용하여 Word 문서를 XPS에 저장합니다.
- C#
- VB.NET
using Spire.Doc;
namespace ConvertWordToXps
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("Sample.docx");
//convert the document to XPS
doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
}
}
}

임시 면허 신청
생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.
C#/VB.NET: Converti Word in XPS
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
XPS (XML Paper Specification) è un formato di documento a layout fisso progettato per preservare la fedeltà del documento e fornire un aspetto del documento indipendente dal dispositivo. È simile al PDF, ma si basa su XML anziché su PostScript. Se desideri salvare un documento Word in un formato di file a layout fisso, XPS sarebbe un'opzione. Questo articolo dimostrerà come convertire i documenti di Word in XPS 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
Converti Word in XPS in C# e VB.NET
Di seguito sono riportati i passaggi dettagliati per convertire un documento Word in XPS utilizzando Spire.Doc for .NET:
- Inizializza un'istanza della classe Document.
- Carica un documento Word usando il metodo Document.LoadFromFile().
- Salvare il documento Word in XPS utilizzando il metodo Document.SaveToFile(string filePath, FileFormat fileFormat).
- C#
- VB.NET
using Spire.Doc;
namespace ConvertWordToXps
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("Sample.docx");
//convert the document to XPS
doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
}
}
}

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 : convertir Word en XPS
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
XPS (XML Paper Specification) est un format de document à mise en page fixe conçu pour préserver la fidélité du document et fournir une apparence de document indépendante du périphérique. Il est similaire au PDF, mais est basé sur XML plutôt que sur PostScript. Si vous souhaitez enregistrer un document Word dans un format de fichier à mise en page fixe, XPS serait une option. Cet article explique comment onvertir des documents Word en XPS 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
Convertir Word en XPS en C# et VB.NET
Voici les étapes détaillées pour convertir un document Word en XPS à l'aide de Spire.Doc for .NET:
- Initialiser une instance de la classe Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Enregistrez le document Word dans XPS à l'aide de la méthode Document.SaveToFile (string filePath, FileFormat fileFormat).
- C#
- VB.NET
using Spire.Doc;
namespace ConvertWordToXps
{
class Program
{
static void Main(string[] args)
{
//Create a Document instance
Document doc = new Document();
//Load a Word document
doc.LoadFromFile("Sample.docx");
//convert the document to XPS
doc.SaveToFile("ToXPS.xps", FileFormat.XPS);
}
}
}

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: Converter HTML em PDF
Índice
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
A conversão de conteúdo HTML em PDF oferece muitas vantagens, incluindo a capacidade de lê-lo off-line, além de preservar o conteúdo e a formatação com alta fidelidade. O Spire.PDF fornece dois métodos para converter HTML em PDF, um é usar o plugin QT Web, o outro é não usar o plugin. Recomendamos que você use o plugin QT para fazer a conversão.
As seções a seguir demonstram como renderizar uma página da Web HTML (URL) ou uma string HTML em um documento PDF usando Spire.PDF for .NET com ou sem plug-in QT.
- Converta um URL para PDF com o QT Plugin
- Converter uma string HTML em PDF com o plug-in QT
- Converter um URL em PDF sem plug-in
- Converter uma string HTML em PDF sem plug-in
Instalar o Spire.PDF for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF 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.PDF
Baixar plug-in
Se você escolher o método de plug-in, faça o download do plug-in adequado ao seu sistema operacional no link a seguir.
Descompacte o pacote em algum lugar do seu disco para obter a pasta "plugins". Neste exemplo, salvamos o plug-in no caminho "F:\Libraries\Plugin\plugins-windows-x64\plugins".

Além disso, recomendamos que você defina a "Platform target" do seu projeto para x64 ou x86 de acordo.

Converta um URL para PDF com o QT Plugin
A seguir estão as etapas para converter um URL em PDF usando o Spire.PDF com o plug-in QT.
- Especifique o caminho da URL para converter.
- Especifique o caminho do arquivo PDF gerado.
- Especifique o caminho do plug-in e atribua-o como o valor da propriedade HtmlConverter.PluginPath.
- Chame o método HtmlConverter.Convert(string url, string fileName, bool enableJavaScript, int timeout, SizeF pageSize, margens PdfMargins) para converter um URL em um documento PDF.
- C#
- VB.NET
using Spire.Pdf.Graphics;
using Spire.Pdf.HtmlConverter.Qt;
using System.Drawing;
namespace ConvertUrlToPdf
{
class Program
{
static void Main(string[] args)
{
//Specify the URL path
string url = "https://www.wikipedia.org/";
//Specify the output file path
string fileName = "UrlToPdf.pdf";
//Specify the plugin path
string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";
//Set the plugin path
HtmlConverter.PluginPath = pluginPath;
//Convert URL to PDF
HtmlConverter.Convert(url, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0));
}
}
}
Converter uma string HTML em PDF com o plug-in QT
A seguir estão as etapas para converter uma string HTML em PDF usando o Spire.PDF com o plug-in QT.
- Obtenha a string HTML de um arquivo .html.
- Especifique o caminho do arquivo PDF gerado.
- Especifique o caminho do plug-in e atribua-o como o valor da propriedade HtmlConverter.PluginPath.
- Chame o método HtmlConverter.Convert(string htmlString, string fileName, bool enableJavaScript, int timeout, SizeF pageSize, PdfMargins, Spire.Pdf.HtmlConverter.LoadHtmlType htmlType) para converter string HTML em um documento PDF.
Observação: somente o estilo CSS embutido e o estilo CSS interno podem ser renderizados corretamente no PDF. Se você tiver uma folha de estilo CSS externa, converta-a em estilo CSS embutido ou interno.
- C#
- VB.NET
using System.IO;
using Spire.Pdf.HtmlConverter.Qt;
using System.Drawing;
using Spire.Pdf.Graphics;
namespace ConvertHtmlStringToPdfWithPlugin
{
class Program
{
static void Main(string[] args)
{
//Get the HTML string from a .html file
string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");
//Specify the output file path
string fileName = "HtmlStringToPdf.pdf";
//Specify the plugin path
string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";
//Set plugin path
HtmlConverter.PluginPath = pluginPath;
//Convert HTML string to PDF
HtmlConverter.Convert(htmlString, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0), Spire.Pdf.HtmlConverter.LoadHtmlType.SourceCode);
}
}
}
Converter um URL em PDF sem plug-in
A seguir estão as etapas para converter um URL em PDF usando Spire.PDF sem plug-in.
- Crie um objeto PdfDocument.
- Crie um objeto PdfPageSettings e defina o tamanho da página e as margens por meio dele.
- Crie um objeto PdfHtmlLayoutFormat e defina a propriedade sWaiting dele como true.
- Especifique o caminho da URL para converter.
- Carregue o HTML do caminho da URL usando o método PdfDocument.LoadFromHTML().
- Salve o documento em um arquivo PDF usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using System;
using Spire.Pdf;
using System.Threading;
using Spire.Pdf.HtmlConverter;
using System.Drawing;
namespace ConverUrlToPdfWithoutPlugin
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Create a PdfPageSettings object
PdfPageSettings setting = new PdfPageSettings();
//Save page size and margins through the object
setting.Size = new SizeF(1000, 1000);
setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
//Create a PdfHtmlLayoutFormat object
PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
//Set IsWaiting property to true
htmlLayoutFormat.IsWaiting = true;
//Specific the URL path to convert
String url = "https://www.wikipedia.org/";
//Load HTML from a URL path using LoadFromHTML method
Thread thread = new Thread(() =>
{ doc.LoadFromHTML(url, true, true, false, setting, htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
//Save the document to a PDF file
doc.SaveToFile("UrlToPdf.pdf");
doc.Close();
}
}
}
Converter uma string HTML em PDF sem plug-in
A seguir estão as etapas para converter uma string HTML em PDF usando Spire.PDF sem plug-in.
- Crie um objeto PdfDocument.
- Crie um objeto PdfPageSettings e defina o tamanho da página e as margens por meio dele.
- Crie um objeto PdfHtmlLayoutFormat e defina a propriedade IsWaiting dele como true.
- Leia a string HTML de um arquivo .html.
- Carregue o HTML da string HTML usando o método PdfDocument.LoadFromHTML().
- Salve o documento em um arquivo PDF usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.HtmlConverter;
using System.IO;
using System.Threading;
using System.Drawing;
namespace ConvertHtmlStringToPdfWithoutPlugin
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Create a PdfPageSettings object
PdfPageSettings setting = new PdfPageSettings();
//Save page size and margins through the object
setting.Size = new SizeF(1000, 1000);
setting.Margins = new Spire.Pdf.Graphics.PdfMargins(20);
//Create a PdfHtmlLayoutFormat object
PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
//Set IsWaiting property to true
htmlLayoutFormat.IsWaiting = true;
//Read html string from a .html file
string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");
//Load HTML from html string using LoadFromHTML method
Thread thread = new Thread(() =>
{ doc.LoadFromHTML(htmlString, true, setting, htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
//Save to a PDF file
doc.SaveToFile("HtmlStringToPdf.pdf");
}
}
}
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.