Как использовать параметры безопасности и шифрование для документов на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите/создайте документ.
  3. Укажите пароль, тип шифрования и разрешения в параметрах сохранения pdf.
  4. Сохраните документ в формате PDF.

Шифрование позволяет Вам надежно защитить содержимое ваших файлов от нежелательных просмотров и от нежелательных действий, таких как печать, выделение текста и так далее. Защита от записи относится к режиму, в котором содержимое документа может быть отредактировано, но документ не может быть разрешен с использованием того же имени файла. Содержит сведения о шифровании и разрешениях доступа к документу. Демонстрирует, как установить разрешения для PDF-документа, созданного Sautinsoft.Document.

Прежде всего, давайте создадим простой документ с надписью "Hello World" и сохраним документ в формате PDF с параметрами безопасности:


               // Let's create a simple inscription.
            dc.Content.End.Insert("Hello World!!!", new CharacterFormat() { FontName = "Verdana", Size = 65.5f, FontColor = Color.Orange });
            
Следующим шагом является добавление: Password Protection, EncryptionAlgorithm, Permissions
so.EncryptionDetails.UserPassword = "12345";
so.EncryptionDetails.EncryptionAlgorithm = PdfEncryptionAlgorithm.RC4_128;
so.EncryptionDetails.Permissions = PdfPermissions.Printing;

И последний шаг - сохранение документа в формате PDF
// Save a document as the PDF file with Security Options
            dc.Save(@"d:\Download\DocumentProperties.pdf", so);

Вы можете найти дополнительную информацию о Document Properties

Отличная работа!

Полный код

using System;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;
using System.IO;
using System.Linq;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            SecureDocument();
        }
		
        /// <summary>
        /// Create and secure a PDF document by password. Also set the permissions for the document.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/security-options-net-csharp-vb.php
        /// </remarks>
        public static void SecureDocument()
        {
            string filePath = @"ProtectedDocument.pdf";

            DocumentCore dc = new DocumentCore();

            // Let's create a simple document.
            dc.Content.End.Insert("Hello World!!!", new CharacterFormat() { FontName = "Verdana", Size = 65.5f, FontColor = Color.Orange });

            PdfSaveOptions so = new PdfSaveOptions();
            // Password Protection
            so.EncryptionDetails.UserPassword = "12345";
            // EncryptionAlgorithm
            so.EncryptionDetails.EncryptionAlgorithm = PdfEncryptionAlgorithm.RC4_128;
            //Permissions: Content Copying, Commenting, Printing, Changing the Document, filing of form fildes etc
            //Printing: Allowed
            so.EncryptionDetails.Permissions = PdfPermissions.Printing;
            
            // Save a document as the PDF file with Security Options.
            dc.Save(filePath, so);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        SecureDocument()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Create and secure a PDF document by password. Also set the permissions for the document.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/security-options-net-csharp-vb.php
    ''' </remarks>
    Sub SecureDocument()
        Dim filePath As String = "ProtectedDocument.pdf"

        Dim dc As New DocumentCore()

        ' Let's create a simple document.
        dc.Content.End.Insert("Hello World!!!", New CharacterFormat() With {
                .FontName = "Verdana",
                .Size = 65.5F,
                .FontColor = Color.Orange
            })

        Dim so As New PdfSaveOptions()
        ' Password Protection
        so.EncryptionDetails.UserPassword = "12345"
        ' EncryptionAlgorithm
        so.EncryptionDetails.EncryptionAlgorithm = PdfEncryptionAlgorithm.RC4_128
        'Permissions: Content Copying, Commenting, Printing, Changing the Document, filing of form fildes etc
        'Printing: Allowed
        so.EncryptionDetails.Permissions = PdfPermissions.Printing

        ' Save a document as the PDF file with Security Options.
        dc.Save(filePath, so)

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(filePath) With {.UseShellExecute = True})
    End Sub
End Module

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.