C#/VB.NET: Digitally Sign Word Documents
Table of Contents
Installed via NuGet
PM> Install-Package Spire.Doc
Related Links
A signature confirms that the digital document originated from the signer and has not been tampered with during transit. The use of digital signatures eliminates the need for sending paper documents, and reduces the number of the documents that need to be printed, mailed, and stored, saving you time and money. In this article, you will learn how to digitally sign a Word document in C# and VB.NET using Spire.Doc for .NET.
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Add a Digital Signature to Word in C#, VB.NET
The steps are as follows.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Specify the path and the password of a .pfx certificate.
- Digitally sign the document while saving the document using Document.SaveToFile(string fileName, FileFormat fileFormat, string certificatePath, string securePassword) method. Here are some other methods that you can use to digitally sign a Word document.
- public void SaveToFile(string fileName, FileFormat fileFormat, byte[] certificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] certificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, string certificatePath, string securePassword);
- public static byte[] Document.Sign(Stream sourceStream, byte[] certificateData, string securePassword);
- public static byte[] Document.Sign(Stream sourceStream, string certificatePath, string securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
C#/VB.NET: assinar digitalmente documentos do Word
Índice
Instalado via NuGet
PM> Install-Package Spire.Doc
Links Relacionados
Uma assinatura confirma que o documento digital originou-se do signatário e não foi adulterado durante o trânsito. O uso de assinaturas digitais elimina a necessidade de envio de documentos em papel e reduz a quantidade de documentos que precisam ser impressos, enviados e armazenados, economizando tempo e dinheiro. Neste artigo, você aprenderá como assinar digitalmente um documento Word em C# e VB.NET usando Spire.Doc for .NET
Instale 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
Adicione uma assinatura digital ao Word em C#, VB.NET
As etapas são as seguintes.
- Crie um objeto Documento.
- Carregue um documento do Word usando o método Document.LoadFromFile().
- Especifique o caminho e a senha de um certificado .pfx.
- Assine digitalmente o documento enquanto o salva usando o método Document.SaveToFile(string fileName, FileFormat fileFormat, string CertificatePath, string securePassword). Aqui estão alguns outros métodos que você pode usar para assinar digitalmente um documento do Word.
- public void SaveToFile(string fileName, FileFormat fileFormat, byte[] CertificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] CertificateData, string securePassword);
- public void SaveToStream (fluxo de fluxo, FileFormat fileFormat, string CertificatePath, string securePassword);
- byte estático público [] Document.Sign (Stream sourceStream, byte [] certificadoData, string securePassword);
- byte estático público [] Document.Sign (Stream sourceStream, string CertificatePath, string securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

Solicite uma licença temporária
Se desejar 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 на 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
Шаги следующие.
- Создайте объект Документ.
- Загрузите документ Word с помощью метода Document.LoadFromFile().
- Укажите путь и пароль сертификата .pfx.
- Подпишите документ цифровой подписью при его сохранении с помощью метода Document.SaveToFile(string fileName, FileFormat fileFormat, string certificatePath, string securePassword). Вот несколько других методов, которые можно использовать для цифровой подписи документа Word.
- public void SaveToFile (строка fileName, FileFormat fileFormat, byte[] certificateData, строка securePassword);
- public void SaveToStream (поток потока, FileFormat fileFormat, byte[] certificateData, строка securePassword);
- public void SaveToStream (поток потока, FileFormat fileFormat, строка certificatePath, строка securePassword);
- public static byte[] Document.Sign(Stream sourceStream, byte[] certificateData, string securePassword);
- public static byte[] Document.Sign(Stream sourceStream, строка certificatePath, строка securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
C#/VB.NET: Word-Dokumente digital signieren
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.Doc
verwandte Links
Eine Signatur bestätigt, dass das digitale Dokument vom Unterzeichner stammt und während des Transports nicht manipuliert wurde. Durch die Verwendung digitaler Signaturen entfällt die Notwendigkeit, Papierdokumente zu versenden, und die Anzahl der Dokumente, die gedruckt, verschickt und gespeichert werden müssen, verringert sich, wodurch Sie Zeit und Geld sparen. In diesem Artikel erfahren Sie, wie Sie ein Word-Dokument in C# und VB.NET digital signieren 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
Fügen Sie Word in C#, VB.NET eine digitale Signatur hinzu
Die Schritte sind wie folgt.
- Erstellen Sie ein Document-Objekt.
- Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
- Geben Sie den Pfad und das Passwort eines .pfx-Zertifikats an.
- Signieren Sie das Dokument digital, während Sie es mit der Methode Document.SaveToFile(string fileName, FileFormat fileFormat, string CertificatePath, string securePassword) speichern. Hier sind einige andere Methoden, mit denen Sie ein Word-Dokument digital signieren können.
- public void SaveToFile(string fileName, FileFormat fileFormat, byte[] CertificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] CertificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, string CertificatePath, string securePassword);
- public static byte[] Document.Sign(Stream sourceStream, byte[] CertificateData, string securePassword);
- öffentliches statisches Byte[] Document.Sign(Stream sourceStream, string CertificatePath, string securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

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: Word-Dokumente digital signieren
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.Doc
verwandte Links
Eine Signatur bestätigt, dass das digitale Dokument vom Unterzeichner stammt und während des Transports nicht manipuliert wurde. Durch die Verwendung digitaler Signaturen entfällt die Notwendigkeit, Papierdokumente zu versenden, und die Anzahl der Dokumente, die gedruckt, verschickt und gespeichert werden müssen, verringert sich, wodurch Sie Zeit und Geld sparen. In diesem Artikel erfahren Sie, wie Sie ein Word-Dokument in C# und VB.NET digital signieren 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
Fügen Sie Word in C#, VB.NET eine digitale Signatur hinzu
Die Schritte sind wie folgt.
- Erstellen Sie ein Document-Objekt.
- Laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
- Geben Sie den Pfad und das Passwort eines .pfx-Zertifikats an.
- Signieren Sie das Dokument digital, während Sie es mit der Methode Document.SaveToFile(string fileName, FileFormat fileFormat, string CertificatePath, string securePassword) speichern. Hier sind einige andere Methoden, mit denen Sie ein Word-Dokument digital signieren können.
- public void SaveToFile(string fileName, FileFormat fileFormat, byte[] CertificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] CertificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, string CertificatePath, string securePassword);
- public static byte[] Document.Sign(Stream sourceStream, byte[] CertificateData, string securePassword);
- öffentliches statisches Byte[] Document.Sign(Stream sourceStream, string CertificatePath, string securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

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: firmar digitalmente documentos de Word
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.Doc
enlaces relacionados
Una firma confirma que el documento digital provino del firmante y no ha sido manipulado durante el tránsito. El uso de firmas digitales elimina la necesidad de enviar documentos en papel y reduce la cantidad de documentos que deben imprimirse, enviarse por correo y almacenarse, lo que le ahorra tiempo y dinero. En este artículo, aprenderá cómo firmar digitalmente un documento de Word 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 instalar a través de NuGet.
PM> Install-Package Spire.Doc
Agregar una firma digital a Word en C#, VB.NET
Los pasos son los siguientes.
- Crea un objeto de documento.
- Cargue un documento de Word utilizando el método Document.LoadFromFile().
- Especifique la ruta y la contraseña de un certificado .pfx.
- Firme digitalmente el documento mientras lo guarda usando el método Document.SaveToFile(string fileName, FileFormat fileFormat, string CertificatePath, string SecurePassword). A continuación se muestran algunos otros métodos que puede utilizar para firmar digitalmente un documento de Word.
- public void SaveToFile (cadena nombre de archivo, formato de archivo formato de archivo, byte [] datos del certificado, cadena contraseña segura);
- public void SaveToStream (flujo de flujo, formato de archivo formato de archivo, byte [] certificado de datos, cadena contraseña segura);
- public void SaveToStream (flujo de flujo, formato de archivo formato de archivo, ruta del certificado de cadena, contraseña segura de la cadena);
- byte estático público [] Document.Sign (Stream sourceStream, byte [] CertificateData, cadena SecurePassword);
- byte estático público [] Document.Sign (Stream sourceStream, cadena ruta del certificado, cadena contraseña segura);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

Solicite 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
관련된 링크들
서명은 디지털 문서가 서명자로부터 시작되었으며 전송 중에 변조되지 않았음을 확인합니다. 디지털 서명을 사용하면 종이 문서를 보낼 필요가 없어지고 인쇄, 우편 발송, 저장해야 하는 문서 수가 줄어들어 시간과 비용이 절약됩니다. 이 기사에서는 다음 방법을 배웁니다 C# 및 VB.NET에서 Word 문서에 디지털 서명 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에 디지털 서명 추가
단계는 다음과 같습니다.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 문서를 로드합니다.
- .pfx 인증서의 경로와 비밀번호를 지정합니다.
- Document.SaveToFile(string fileName, FileFormat fileFormat, string CertificatePath, string securePassword) 메서드를 사용하여 문서를 저장하는 동안 문서에 디지털 서명을 합니다. 다음은 Word 문서에 디지털 서명하는 데 사용할 수 있는 몇 가지 다른 방법입니다.
- public void SaveToFile(string fileName, FileFormat fileFormat, byte[] CertificateData, string securePassword);
- 공개 무효 SaveToStream(스트림 스트림, FileFormat fileFormat, byte[] 인증서 데이터, 문자열 securePassword);
- 공개 무효 SaveToStream(스트림 스트림, FileFormat fileFormat, 문자열 인증서 경로, 문자열 securePassword);
- public static byte[] Document.Sign(Stream sourceStream, byte[] CertificateData, string securePassword);
- public static byte[] Document.Sign(Stream sourceStream, 문자열 인증서 경로, 문자열 securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
C#/VB.NET: firma digitale di documenti Word
Installato tramite NuGet
PM> Install-Package Spire.Doc
Link correlati
Una firma conferma che il documento digitale ha avuto origine dal firmatario e non è stato manomesso durante il transito. L'uso delle firme digitali elimina la necessità di inviare documenti cartacei e riduce il numero di documenti che devono essere stampati, spediti per posta e archiviati, risparmiando tempo e denaro. In questo articolo imparerai come firmare digitalmente un documento Word in C# e VB.NET utilizzando Spire.Doc for .NET.
Installa Spire.Doc for .NET
Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.Doc for.NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
PM> Install-Package Spire.Doc
Aggiungi una firma digitale a Word in C#, VB.NET
I passi sono come segue.
- Creare un oggetto Documento.
- Carica un documento Word utilizzando il metodo Document.LoadFromFile().
- Specificare il percorso e la password di un certificato .pfx.
- Firmare digitalmente il documento durante il salvataggio utilizzando il metodo Document.SaveToFile(string fileName, FileFormat fileFormat, string certificatePath, string securePassword). Ecco alcuni altri metodi che puoi utilizzare per firmare digitalmente un documento di Word.
- public void SaveToFile(string fileName, FileFormat fileFormat, byte[] certificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] certificateData, string securePassword);
- public void SaveToStream(Stream stream, FileFormat fileFormat, stringa certificatePath, stringa securePassword);
- public static byte[] Document.Sign(Stream sourceStream, byte[] certificateData, string securePassword);
- byte statico pubblico[] Document.Sign(Stream sourceStream, stringa certificatePath, stringa securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.
C#/VB.NET : signer numériquement des documents Word
Table des matières
Installé via NuGet
PM> Install-Package Spire.Doc
Liens connexes
Une signature confirme que le document numérique provient du signataire et n'a pas été falsifié pendant le transport. L'utilisation de signatures numériques élimine le besoin d'envoyer des documents papier et réduit le nombre de documents à imprimer, à envoyer et à stocker, ce qui vous permet d'économiser du temps et de l'argent. Dans cet article, vous apprendrez comment signer numériquement un document Word 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 comme 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
Ajouter une signature numérique à Word en C#, VB.NET
Les étapes sont les suivantes.
- Créez un objet Document.
- Chargez un document Word à l'aide de la méthode Document.LoadFromFile().
- Spécifiez le chemin et le mot de passe d'un certificat .pfx.
- Signez numériquement le document lors de l'enregistrement du document à l'aide de la méthode Document.SaveToFile (string fileName, FileFormat fileFormat, string certificatePath, string securePassword). Voici quelques autres méthodes que vous pouvez utiliser pour signer numériquement un document Word.
- public void SaveToFile (string fileName, FileFormat fileFormat, byte[] certificateData, string securePassword);
- public void SaveToStream (flux de flux, FileFormat fileFormat, byte[] certificateData, string securePassword);
- public void SaveToStream (flux de flux, FileFormat fileFormat, chaîne certificatePath, chaîne securePassword);
- public static byte[] Document.Sign(Stream sourceStream, byte[] certificateData, string securePassword);
- public static byte[] Document.Sign (Stream sourceStream, chaîne certificatePath, chaîne securePassword);
- C#
- VB.NET
using Spire.Doc;
namespace DigitallySignWord
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document doc = new Document();
//Load a Word file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
//Specify the certificate path
string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";
//Specify the password of the certificate
string password = "e-iceblue";
//Digitally sign the document while saving it to a .docx file
doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
}
}
}

Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
C#/VB.NET: Protect or Unprotect a Word Document
Table of Contents
Installed via NuGet
PM> Install-Package Spire.Doc
Related Links
Word documents can be protected in a variety of ways, depending on the security requirements. To prevent unauthorized people from opening a document, you can encrypt it with a password. To allow users to open the document, but not edit or modify its content, you can make the document read-only or mark it as final. To allow users to modify parts of the document, you can lock the entire document but let specified sections available for editing. This article focuses on how to protect or unprotect a Word document in C# and VB.NET using Spire.Doc for .NET.
- Password Protect a Word Document in C#, VB.NET
- Change Permission of a Word Document in C#, VB.NET
- Lock Specified Sections of a Word Document in C#, VB.NET
- Mark a Word Document as Final in C#, VB.NET
- Remove Password from a Word Document in C#, VB.NET
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Password Protect a Word Document in C#, VB.NET
Encrypting a document with a password makes sure that only you and certain people can read or edit it. The following are the steps to protect a Word document with a password using Spire.Doc for .NET.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Encrypt the document with a password using Document.Encrypt() method.
- Save the document to another Word file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace PasswordProtectWordDocument
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document document = new Document();
//Load a Word file
document.LoadFromFile(@"C:\Users\Administrator\Desktop\test.docx");
//Encrypt the document with a password
document.Encrypt("open-psd");
//Save the document to another Word file
document.SaveToFile("Encryption.docx", FileFormat.Docx);
}
}
}

Change Permission of a Word Document in C#, VB.NET
Documents encrypted with an open password cannot be opened by those who do not know the password. If you’d like to grant people permission to read your document but restrict the types of modifications that someone can make, you can set the document permission. The following are the steps to change permission of a Word document using Spire.Doc for .NET.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Set the document permission and set the permission password using Document.Protect() method.
- Save the document to another Word file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace ChangeDocumentPermission
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document document = new Document();
//Load a Word document
document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");
//Set the document permission and set the permission password
document.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd");
//Save the document to another Word file
document.SaveToFile("Permission.docx");
}
}
}

Lock Specified Sections of a Word Document in C#, VB.NET
When you protect your document, you can lock parts of it so that they cannot be changed and leave the unlocked parts available for editing. The following are the steps to protect specified sections of a Word document using Spire.Doc for .NET.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Set the editing restriction as AllowOnlyFormFields.
- Unprotect a specific section by setting Document.Sections[index].ProtectForm to false. The rest sections will continue to be protected.
- Save the document to another Word file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace ProtectSpecificSection
{
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\sample.docx");
//Set editing restriction as "AllowOnlyFormFields"
doc.Protect(ProtectionType.AllowOnlyFormFields, "permissionPsd");
//Unprotect section 2
doc.Sections[1].ProtectForm = false;
//Save the document to another Word file
doc.SaveToFile("ProtectSection.docx");
}
}
}

Mark a Word Document as Final in C#, VB.NET
By marking a document as Final, you disable typing, editing, and format changes capabilities and a message will appear to any reader that the document has been finalized. The following are the steps to mark a Word document as final using Spire.Doc for .NET.
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Get the CustomDocumentProperties object from the document.
- Add a custom property "_MarkAsFinal" to the document.
- Save the document to another Word file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace MarkAsFinal
{
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\sample.docx");
//Get custom document properties
CustomDocumentProperties customProperties = doc.CustomDocumentProperties;
//Add "_MarkAsFinal" property to the document
customProperties.Add("_MarkAsFinal", true);
//Save the document to another Word file
doc.SaveToFile("MarkAsFinal.docx");
}
}
}

Remove Password from a Word Document in C#, VB.NET
You can remove the password from an encrypted document if the encryption is no longer needed. The following are the detailed steps.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Remove the password using Document.RemoveEncryption() method.
- Save the document to another Word file using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc;
namespace RemovePassword
{
class Program
{
static void Main(string[] args)
{
//Create a Document object
Document document = new Document();
//Load an encrypted Word document
document.LoadFromFile(@"C:\Users\Administrator\Desktop\Encryption.docx", FileFormat.Docx, "open-psd");
//Remove encryption
document.RemoveEncryption();
//Save the document to another Word file
document.SaveToFile("Decryption.docx", FileFormat.Docx);
}
}
}
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.