C#/VB.NET: разделить PDF на несколько PDF-файлов
Оглавление
Установлено через NuGet
PM> Install-Package Spire.PDF
Ссылки по теме
В определенных ситуациях полезно разделить один PDF-файл на несколько более мелких. Например, вы можете разделить большие контракты, отчеты, книги, академические статьи или другие документы на более мелкие части, чтобы их было легко просматривать или повторно использовать. В этой статье вы узнаете, как разделить PDF на одностраничные PDF-файлы и как разделить PDF по диапазонам страниц в C# и VB.NET с помощью Spire.PDF for .NET.
Установите Spire.PDF for .NET
Для начала вам нужно добавить файлы DLL, включенные в пакет Spire.PDF for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.PDF
Разделить PDF на одностраничные PDF-файлы в C#, VB.NET
Spire.PDF предлагает метод Split() для разделения многостраничного PDF-документа на несколько одностраничных файлов. Ниже приведены подробные шаги.
- Создайте объект PdfDcoument.
- Загрузите документ PDF с помощью метода PdfDocument.LoadFromFile().
- Разделите документ на одностраничные файлы PDF с помощью метода PdfDocument.Split(string destFilePattern, int startNumber).
- C#
- VB.NET
using System;
using Spire.Pdf;
namespace SplitPDFIntoIndividualPages
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.LoadFromFile(inputFile);
//Split the PDF to one-page PDFs
doc.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}

Разделить PDF по диапазонам страниц в C#, VB.NET
Не существует простого метода разделения PDF-документов по диапазонам страниц. Для этого мы создаем два или более новых PDF-документа и импортируем в них страницу или диапазон страниц из исходного документа. Вот подробные шаги.
- Загрузите исходный файл PDF при инициализации объекта PdfDocument.
- Создайте два дополнительных объекта PdfDocument.
- Импортируйте первую страницу из исходного файла в первый документ с помощью метода PdfDocument.InsertPage().
- Импортируйте оставшиеся страницы из исходного файла во второй документ с помощью метода PdfDocument.InsertPageRange().
- Сохраните два документа как отдельные файлы PDF, используя метод PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using System;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Load the source PDF file while initialing the PdfDocument object
PdfDocument sourceDoc = new PdfDocument(inputFile);
//Create two additional PdfDocument objects
PdfDocument newDoc_1 = new PdfDocument();
PdfDocument newDoc_2 = new PdfDocument();
//Insert the first page of source file to the first document
newDoc_1.InsertPage(sourceDoc, 0);
//Insert the rest pages of source file to the second document
newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);
//Save the two documents as PDF files
newDoc_1.SaveToFile(outputDirectory + "output-1.pdf");
newDoc_2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.
C#/VB.NET: PDF in mehrere PDF-Dateien aufteilen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.PDF
verwandte Links
In bestimmten Situationen ist es hilfreich, ein einzelnes PDF in mehrere kleinere aufzuteilen. Sie können beispielsweise große Verträge, Berichte, Bücher, wissenschaftliche Arbeiten oder andere Dokumente in kleinere Teile aufteilen, um sie einfacher zu überprüfen oder wiederzuverwenden. In diesem Artikel erfahren Sie, wie das geht Aufteilen von PDFs in einseitige PDFs und Aufteilen von PDFs nach Seitenbereichen in C# und VB.NET mithilfe von Spire.PDF for .NET.
Installieren Spire.PDF for .NET
Zunächst müssen Sie die im Spire.PDF for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
PM> Install-Package Spire.PDF
Teilen Sie PDF in einseitige PDFs in C#, VB.NET auf
Spire.PDF bietet die Split()-Methode zum Aufteilen eines mehrseitigen PDF-Dokuments in mehrere einseitige Dateien. Im Folgenden finden Sie die detaillierten Schritte.
- Erstellen Sie ein PdfDcoument-Objekt.
- Laden Sie ein PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
- Teilen Sie das Dokument mit der Methode PdfDocument.Split(string destFilePattern, int startNumber) in einseitige PDFs auf.
- C#
- VB.NET
using System;
using Spire.Pdf;
namespace SplitPDFIntoIndividualPages
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.LoadFromFile(inputFile);
//Split the PDF to one-page PDFs
doc.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}

Teilen Sie PDF nach Seitenbereichen in C#, VB.NET
Für die Aufteilung von PDF-Dokumenten nach Seitenbereichen wird keine einfache Methode angeboten. Dazu erstellen wir zwei oder mehr neue PDF-Dokumente und importieren die Seite bzw. den Seitenbereich aus dem Quelldokument in diese. Hier sind die detaillierten Schritte.
- Laden Sie die PDF-Quelldatei, während Sie das PdfDocument-Objekt initialisieren.
- Erstellen Sie zwei zusätzliche PdfDocument-Objekte.
- Importieren Sie die erste Seite aus der Quelldatei mit der Methode PdfDocument.InsertPage() in das erste Dokument.
- Importieren Sie die verbleibenden Seiten aus der Quelldatei mit der Methode PdfDocument.InsertPageRange() in das zweite Dokument.
- Speichern Sie die beiden Dokumente als separate PDF-Dateien mit der Methode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using System;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Load the source PDF file while initialing the PdfDocument object
PdfDocument sourceDoc = new PdfDocument(inputFile);
//Create two additional PdfDocument objects
PdfDocument newDoc_1 = new PdfDocument();
PdfDocument newDoc_2 = new PdfDocument();
//Insert the first page of source file to the first document
newDoc_1.InsertPage(sourceDoc, 0);
//Insert the rest pages of source file to the second document
newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);
//Save the two documents as PDF files
newDoc_1.SaveToFile(outputDirectory + "output-1.pdf");
newDoc_2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}

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: dividir PDF en varios archivos PDF
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.PDF
enlaces relacionados
Es útil dividir un solo PDF en varios más pequeños en ciertas situaciones. Por ejemplo, puede dividir contratos grandes, informes, libros, trabajos académicos u otros documentos en partes más pequeñas para facilitar su revisión o reutilización. En este artículo, aprenderá cómo dividir PDF en PDF de una sola página y como dividir PDF por rangos de página en C# y VB.NET utilizando Spire.PDF for .NET.
Instalar Spire.PDF for .NET
Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF 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.PDF
Dividir PDF en PDF de una página en C#, VB.NET
Spire.PDF ofrece el método Split() para dividir un documento PDF de varias páginas en varios archivos de una sola página. Los siguientes son los pasos detallados.
- Cree un objeto PdfDcoument.
- Cargue un documento PDF utilizando el método PdfDocument.LoadFromFile().
- Divida el documento en archivos PDF de una página con el método PdfDocument.Split(string destFilePattern, int startNumber).
- C#
- VB.NET
using System;
using Spire.Pdf;
namespace SplitPDFIntoIndividualPages
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.LoadFromFile(inputFile);
//Split the PDF to one-page PDFs
doc.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}

Dividir PDF por rangos de páginas en C#, VB.NET
No se ofrece ningún método directo para dividir documentos PDF por rangos de páginas. Para hacerlo, creamos dos o más documentos PDF nuevos e importamos la página o el rango de páginas del documento de origen a ellos. Aquí están los pasos detallados.
- Cargue el archivo PDF de origen mientras inicializa el objeto PdfDocument.
- Cree dos objetos PdfDocument adicionales.
- Importe la primera página del archivo de origen al primer documento utilizando el método PdfDocument.InsertPage().
- Importe las páginas restantes del archivo de origen al segundo documento utilizando el método PdfDocument.InsertPageRange().
- Guarde los dos documentos como archivos PDF separados utilizando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using System;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Load the source PDF file while initialing the PdfDocument object
PdfDocument sourceDoc = new PdfDocument(inputFile);
//Create two additional PdfDocument objects
PdfDocument newDoc_1 = new PdfDocument();
PdfDocument newDoc_2 = new PdfDocument();
//Insert the first page of source file to the first document
newDoc_1.InsertPage(sourceDoc, 0);
//Insert the rest pages of source file to the second document
newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);
//Save the two documents as PDF files
newDoc_1.SaveToFile(outputDirectory + "output-1.pdf");
newDoc_2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}

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: PDF를 여러 PDF 파일로 분할
NuGet을 통해 설치됨
PM> Install-Package Spire.PDF
관련된 링크들
특정 상황에서 단일 PDF를 여러 개의 작은 PDF로 분할하는 것이 유용합니다. 예를 들어 큰 계약서, 보고서, 서적, 학술 논문 또는 기타 문서를 작은 조각으로 나누어 쉽게 검토하거나 재사용할 수 있습니다. 이 기사에서는 다음을 수행하는 방법을 배웁니다 PDF를 단일 페이지 PDF로 분할 그리고 어떻게 C# 및 VB.NET에서 페이지 범위별로 PDF 분할Spire.PDF for .NET사용.
Spire.PDF for .NET 설치
먼저 Spire.PDF for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.PDF
C#, VB.NET에서 PDF를 한 페이지 PDF로 분할
Spire.PDF는 여러 페이지 PDF 문서를 여러 단일 페이지 파일로 분할하는 Split() 메서드를 제공합니다. 다음은 세부 단계입니다.
- PdfDcoument 개체를 만듭니다.
- PdfDocument.LoadFromFile() 메서드를 사용하여 PDF 문서를 로드합니다.
- PdfDocument.Split(string destFilePattern, int startNumber) 메서드를 사용하여 문서를 한 페이지 PDF로 분할합니다.
- C#
- VB.NET
using System;
using Spire.Pdf;
namespace SplitPDFIntoIndividualPages
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.LoadFromFile(inputFile);
//Split the PDF to one-page PDFs
doc.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}

C#, VB.NET의 페이지 범위별로 PDF 분할
PDF 문서를 페이지 범위별로 분할하는 간단한 방법은 없습니다. 이를 위해 두 개 이상의 새 PDF 문서를 만들고 소스 문서의 페이지 또는 페이지 범위를 문서로 가져옵니다. 자세한 단계는 다음과 같습니다.
- PdfDocument 개체를 초기화하는 동안 원본 PDF 파일을 로드합니다.
- 두 개의 추가 PdfDocument 개체를 만듭니다.
- PdfDocument.InsertPage() 메서드를 사용하여 소스 파일의 첫 번째 페이지를 첫 번째 문서로 가져옵니다.
- PdfDocument.InsertPageRange() 메서드를 사용하여 소스 파일의 나머지 페이지를 두 번째 문서로 가져옵니다.
- PdfDocument.SaveToFile() 메서드를 사용하여 두 문서를 별도의 PDF 파일로 저장합니다.
- C#
- VB.NET
using Spire.Pdf;
using System;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Load the source PDF file while initialing the PdfDocument object
PdfDocument sourceDoc = new PdfDocument(inputFile);
//Create two additional PdfDocument objects
PdfDocument newDoc_1 = new PdfDocument();
PdfDocument newDoc_2 = new PdfDocument();
//Insert the first page of source file to the first document
newDoc_1.InsertPage(sourceDoc, 0);
//Insert the rest pages of source file to the second document
newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);
//Save the two documents as PDF files
newDoc_1.SaveToFile(outputDirectory + "output-1.pdf");
newDoc_2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}

임시 면허 신청
생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.
C#/VB.NET: Dividi PDF in più file PDF
Sommario
Installato tramite NuGet
PM> Install-Package Spire.PDF
Link correlati
È utile dividere un singolo PDF in più file più piccoli in determinate situazioni. Ad esempio, puoi dividere contratti, relazioni, libri, documenti accademici o altri documenti di grandi dimensioni in parti più piccole per renderli più facili da rivedere o riutilizzare. In questo articolo imparerai come dividere PDF in PDF a pagina singola e come dividere PDF per intervalli di pagine in C# e VB.NET utilizzando Spire.PDF for .NET.
Installa Spire.PDF for .NET
Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
PM> Install-Package Spire.PDF
Dividi PDF in PDF di una pagina in C#, VB.NET
Spire.PDF offre il metodo Split() per dividere un documento PDF multipagina in più file a pagina singola. Di seguito sono riportati i passaggi dettagliati.
- Crea un oggetto PdfDcoument.
- Carica un documento PDF utilizzando il metodo PdfDocument.LoadFromFile().
- Dividi il documento in PDF di una pagina utilizzando il metodo PdfDocument.Split(string destFilePattern, int startNumber).
- C#
- VB.NET
using System;
using Spire.Pdf;
namespace SplitPDFIntoIndividualPages
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.LoadFromFile(inputFile);
//Split the PDF to one-page PDFs
doc.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}

Dividi PDF per intervalli di pagine in C#, VB.NET
Non viene offerto alcun metodo semplice per suddividere i documenti PDF per intervalli di pagine. Per fare ciò, creiamo due o più nuovi documenti PDF e importiamo in essi la pagina o l'intervallo di pagine dal documento di origine. Ecco i passaggi dettagliati.
- Carica il file PDF di origine durante l'inizializzazione dell'oggetto PdfDocument.
- Creare due oggetti PdfDocument aggiuntivi.
- Importa la prima pagina dal file di origine al primo documento utilizzando il metodo PdfDocument.InsertPage().
- Importa le pagine rimanenti dal file di origine al secondo documento utilizzando il metodo PdfDocument.InsertPageRange().
- Salvare i due documenti come file PDF separati utilizzando il metodo PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using System;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Load the source PDF file while initialing the PdfDocument object
PdfDocument sourceDoc = new PdfDocument(inputFile);
//Create two additional PdfDocument objects
PdfDocument newDoc_1 = new PdfDocument();
PdfDocument newDoc_2 = new PdfDocument();
//Insert the first page of source file to the first document
newDoc_1.InsertPage(sourceDoc, 0);
//Insert the rest pages of source file to the second document
newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);
//Save the two documents as PDF files
newDoc_1.SaveToFile(outputDirectory + "output-1.pdf");
newDoc_2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}

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 : fractionner un PDF en plusieurs fichiers PDF
Table des matières
Installé via NuGet
PM> Install-Package Spire.PDF
Liens connexes
Il est utile de diviser un seul PDF en plusieurs plus petits dans certaines situations. Par exemple, vous pouvez diviser des contrats volumineux, des rapports, des livres, des articles universitaires ou d'autres documents en plus petits éléments, ce qui facilite leur révision ou leur réutilisation. Dans cet article, vous apprendrez à diviser le PDF en PDF d'une seule page et comment divisez le PDF par plages de pages en C# et VB.NET en utilisant Spire.PDF for .NET.
Installer Spire.PDF for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF 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.PDF
Diviser un PDF en PDF d'une page en C#, VB.NET
Spire.PDF propose la méthode Split () pour diviser un document PDF de plusieurs pages en plusieurs fichiers d'une seule page. Voici les étapes détaillées.
- Créez un objet PdfDcoument.
- Chargez un document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Divisez le document en PDF d'une page à l'aide de la méthode PdfDocument.Split(string destFilePattern, int startNumber).
- C#
- VB.NET
using System;
using Spire.Pdf;
namespace SplitPDFIntoIndividualPages
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.LoadFromFile(inputFile);
//Split the PDF to one-page PDFs
doc.Split(outputDirectory + "output-{0}.pdf", 1);
}
}
}

Fractionner un PDF par plages de pages en C#, VB.NET
Aucune méthode directe n'est proposée pour diviser les documents PDF par plages de pages. Pour ce faire, nous créons deux ou plusieurs nouveaux documents PDF et y importons la page ou la plage de pages du document source. Voici les étapes détaillées.
- Chargez le fichier PDF source lors de l'initialisation de l'objet PdfDocument.
- Créez deux objets PdfDocument supplémentaires.
- Importez la première page du fichier source dans le premier document à l'aide de la méthode PdfDocument.InsertPage().
- Importez les pages restantes du fichier source dans le deuxième document à l'aide de la méthode PdfDocument.InsertPageRange().
- Enregistrez les deux documents en tant que fichiers PDF séparés à l'aide de la méthode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using System;
namespace SplitPdfByPageRanges
{
class Program
{
static void Main(string[] args)
{
//Specify the input file path
String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";
//Specify the output directory
String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";
//Load the source PDF file while initialing the PdfDocument object
PdfDocument sourceDoc = new PdfDocument(inputFile);
//Create two additional PdfDocument objects
PdfDocument newDoc_1 = new PdfDocument();
PdfDocument newDoc_2 = new PdfDocument();
//Insert the first page of source file to the first document
newDoc_1.InsertPage(sourceDoc, 0);
//Insert the rest pages of source file to the second document
newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);
//Save the two documents as PDF files
newDoc_1.SaveToFile(outputDirectory + "output-1.pdf");
newDoc_2.SaveToFile(outputDirectory + "output-2.pdf");
}
}
}

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: criptografar ou descriptografar arquivos PDF
Índice
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
A criptografia de PDF é uma tarefa crucial quando se trata de compartilhar documentos confidenciais na Internet. Ao criptografar arquivos PDF com senhas fortes, você pode proteger os dados do arquivo de serem acessados por pessoas não autorizadas. Em certos casos, também pode ser necessário remover a senha para tornar o documento público. Neste artigo, você aprenderá como programar criptografar ou descriptografar um arquivo PDF usando Spire.PDF for .NET.
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 DLLs podem ser baixados deste link ou instalados via NuGet.
PM> Install-Package Spire.PDF
Criptografar um arquivo PDF com senha
Existem dois tipos de senhas para criptografar um arquivo PDF - senha aberta e senha de permissão. O primeiro é configurado para abrir o arquivo PDF, enquanto o último é configurado para restringir impressão, cópia de conteúdo, comentários, etc. Se um arquivo PDF estiver protegido com ambos os tipos de senha, ele poderá ser aberto com qualquer uma das senhas.
O método PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) método oferecido pelo Spire.PDF for .NET permite que você defina a senha aberta e a senha de permissão para criptografar arquivos PDF. As etapas detalhadas são as seguintes.
- Crie um objeto PdfDocument.
- Carregue um arquivo PDF de amostra usando o método PdfDocument.LoadFromFile().
- Obtém os parâmetros de segurança do documento usando a propriedade PdfDocument.Security.
- Criptografe o arquivo PDF com senha aberta e senha de permissão usando o método PdfSecurity.Encrypt(string openPassword, string permissionPassword, permissões PdfPermissionsFlags, PdfEncryptionKeySize keySize).
- Salve o arquivo resultante usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace EncryptPDF
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load a sample PDF file
pdf.LoadFromFile(@"E:\Files\sample.pdf");
//Encrypt the PDF file with password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
//Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
}
}
}

Remova a senha para descriptografar um arquivo PDF
Quando precisar remover a senha de um arquivo PDF, você pode definir a senha de abertura e a senha de permissão como vazias ao chamar o método PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, string originalPermissionPassword). As etapas detalhadas são as seguintes.
- Crie um objeto PdfDocument.
- Carregue o arquivo PDF criptografado com senha usando o método PdfDocument.LoadFromFile (string filename, string password).
- Obtém os parâmetros de segurança do documento usando a propriedade PdfDocument.Security.
- Descriptografe o arquivo PDF definindo a senha de abertura e a senha de permissão para esvaziar usando o método PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags, PdfEncryptionKeySize keySize, string originalPermissionPassword).
- Salve o arquivo resultante usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace DecryptPDF
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load the encrypted PDF file with password
pdf.LoadFromFile("Encrypt.pdf", "open");
//Set the password as empty to decrypt PDF
pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission");
//Save the result file
pdf.SaveToFile("Decrypt.pdf", FileFormat.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 avaliação de 30 dias para você mesmo.
C#/VB.NET: Шифровать или расшифровывать PDF-файлы
Оглавление
Установлено через NuGet
PM> Install-Package Spire.PDF
Ссылки по теме
Шифрование PDF является важной задачей, когда речь идет об обмене конфиденциальными документами в Интернете. Шифруя PDF-файлы с помощью надежных паролей, вы можете защитить данные файла от несанкционированного доступа. В некоторых случаях также может потребоваться удалить пароль, чтобы сделать документ общедоступным. В этой статье вы узнаете, как программно зашифровать или расшифровать файл PDF используя Spire.PDF for .NET.
Установите Spire.PDF for .NET
Для начала вам нужно добавить файлы DLL, включенные в пакет Spire.PDF for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.PDF
Зашифровать файл PDF с помощью пароля
Существует два типа паролей для шифрования файла PDF: открытый пароль и пароль доступа. Первый настроен на открытие файла PDF, а второй — на ограничение печати, копирования содержимого, комментирования и т. д. Если файл PDF защищен обоими типами паролей, его можно открыть любым паролем.
Метод PdfSecurity.Encrypt(string openPassword, string permissionPassword, разрешения PdfPermissionsFlags, PdfEncryptionKeySize keySize), предлагаемый Spire.PDF for .NET, позволяет установить как открытый пароль, так и пароль разрешения для шифрования PDF-файлов. Подробные шаги следующие.
- Создайте объект PdfDocument.
- Загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
- Получает параметры безопасности документа, используя свойство PdfDocument.Security.
- Зашифруйте PDF-файл с открытым паролем и паролем разрешения, используя метод PdfSecurity.Encrypt(string openPassword, string permissionPassword, разрешения PdfPermissionsFlags, PdfEncryptionKeySize keySize).
- Сохраните полученный файл с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace EncryptPDF
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load a sample PDF file
pdf.LoadFromFile(@"E:\Files\sample.pdf");
//Encrypt the PDF file with password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
//Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
}
}
}

Удалить пароль для расшифровки PDF-файла
Если вам нужно удалить пароль из файла PDF, вы можете установить пустой пароль для открытия и пароль разрешения при вызове метода PdfSecurity.Encrypt(string openPassword, string permissionPassword, разрешений PdfPermissionsFlags, PdfEncryptionKeySize keySize, string originalPermissionPassword). Подробные шаги следующие.
- Создайте объект PdfDocument.
- Загрузите зашифрованный файл PDF с паролем, используя метод PdfDocument.LoadFromFile (строковое имя файла, строковый пароль).
- Получает параметры безопасности документа, используя свойство PdfDocument.Security.
- Расшифруйте PDF-файл, установив пустой пароль для открытия и пароль разрешения с помощью метода PdfSecurity.Encrypt(string openPassword, string permissionPassword, разрешений PdfPermissionsFlags, PdfEncryptionKeySize keySize, string originalPermissionPassword).
- Сохраните полученный файл с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace DecryptPDF
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load the encrypted PDF file with password
pdf.LoadFromFile("Encrypt.pdf", "open");
//Set the password as empty to decrypt PDF
pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission");
//Save the result file
pdf.SaveToFile("Decrypt.pdf", FileFormat.PDF);
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.
C#/VB.NET: PDF-Dateien verschlüsseln oder entschlüsseln
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.PDF
verwandte Links
Die PDF-Verschlüsselung ist eine entscheidende Aufgabe, wenn es darum geht, vertrauliche Dokumente im Internet zu teilen. Durch die Verschlüsselung von PDF-Dateien mit starken Passwörtern können Sie die Dateidaten vor dem Zugriff Unbefugter schützen. In bestimmten Fällen kann es auch erforderlich sein, das Passwort zu entfernen, um das Dokument öffentlich zu machen. In diesem Artikel erfahren Sie, wie Sie programmgesteuert vorgehen eine PDF-Datei verschlüsseln oder entschlüsseln Verwendung von Spire.PDF for .NET.
- Verschlüsseln Sie eine PDF-Datei mit einem Passwort
- Entfernen Sie das Passwort, um eine PDF-Datei zu entschlüsseln
Installieren Sie Spire.PDF for .NET
Zunächst müssen Sie die im Spire.PDF for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
PM> Install-Package Spire.PDF
Verschlüsseln Sie eine PDF-Datei mit einem Passwort
Es gibt zwei Arten von Passwörtern zum Verschlüsseln einer PDF-Datei: Offenes Passwort und Berechtigungspasswort.. Ersteres ist so eingestellt, dass die PDF-Datei geöffnet wird, während letzteres das Drucken, Kopieren von Inhalten, Kommentieren usw. einschränkt. Wenn eine PDF-Datei mit beiden Arten von Passwörtern gesichert ist, kann sie mit beiden Passwörtern geöffnet werden.
Mit der von Spire.PDF for .NET angebotenen Methode PdfSecurity.Encrypt(string openPassword, string freedomPassword, PdfPermissionsFlags Berechtigungen, PdfEncryptionKeySize keySize) können Sie sowohl ein Öffnungskennwort als auch ein Berechtigungskennwort zum Verschlüsseln von PDF-Dateien festlegen. Die detaillierten Schritte sind wie folgt.
- Erstellen Sie ein PdfDocument-Objekt.
- Laden Sie eine Beispiel-PDF-Datei mit der Methode PdfDocument.LoadFromFile().
- Ruft die Sicherheitsparameter des Dokuments mithilfe der PdfDocument.Security-Eigenschaft ab.
- Verschlüsseln Sie die PDF-Datei mit dem Öffnungskennwort und dem Berechtigungskennwort mithilfe der Methode PdfSecurity.Encrypt(string openPassword, string freedomPassword, PdfPermissionsFlags Berechtigungen, PdfEncryptionKeySize keySize).
- Speichern Sie die Ergebnisdatei mit der Methode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace EncryptPDF
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load a sample PDF file
pdf.LoadFromFile(@"E:\Files\sample.pdf");
//Encrypt the PDF file with password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
//Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
}
}
}

Entfernen Sie das Passwort, um eine PDF-Datei zu entschlüsseln
Wenn Sie das Passwort aus einer PDF-Datei entfernen müssen, können Sie das Öffnungspasswort und das Berechtigungspasswort auf leer setzen, während Sie die Methode PdfSecurity.Encrypt(string openPassword, string freedomPassword, PdfPermissionsFlags Berechtigungen, PdfEncryptionKeySize keySize, string originalPermissionPassword) aufrufen. Die detaillierten Schritte sind wie folgt.
- Erstellen Sie ein PdfDocument-Objekt.
- Laden Sie die verschlüsselte PDF-Datei mit Passwort mithilfe der Methode PdfDocument.LoadFromFile (String-Dateiname, String-Passwort).
- Ruft die Sicherheitsparameter des Dokuments mithilfe der PdfDocument.Security-Eigenschaft ab.
- Entschlüsseln Sie die PDF-Datei, indem Sie das Öffnungskennwort und das Berechtigungskennwort mit der Methode PdfSecurity.Encrypt(string openPassword, string freedomPassword, PdfPermissionsFlags Berechtigungen, PdfEncryptionKeySize keySize, string originalPermissionPassword) auf leer setzen.
- Speichern Sie die Ergebnisdatei mit der Methode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace DecryptPDF
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load the encrypted PDF file with password
pdf.LoadFromFile("Encrypt.pdf", "open");
//Set the password as empty to decrypt PDF
pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission");
//Save the result file
pdf.SaveToFile("Decrypt.pdf", FileFormat.PDF);
}
}
}

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: cifrar o descifrar archivos PDF
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.PDF
enlaces relacionados
El cifrado de PDF es una tarea crucial cuando se trata de compartir documentos confidenciales en Internet. Al cifrar los archivos PDF con contraseñas seguras, puede proteger los datos del archivo para que no accedan a ellos personas no autorizadas. En determinados casos, también puede ser necesario eliminar la contraseña para hacer público el documento. En este artículo, aprenderá a programar cifrar o descifrar un archivo PDF utilizando Spire.PDF for .NET.
Instalar Spire.PDF for .NET
Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF 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.PDF
Cifrar un archivo PDF con contraseña
Hay dos tipos de contraseñas para cifrar un archivo PDF: contraseña abierta y contraseña de permiso. El primero está configurado para abrir el archivo PDF, mientras que el segundo está configurado para restringir la impresión, la copia de contenido, los comentarios, etc. Si un archivo PDF está protegido con ambos tipos de contraseñas, se puede abrir con cualquiera de ellas.
El método PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permisos, PdfEncryptionKeySize keySize) que ofrece Spire.PDF for .NET le permite establecer una contraseña abierta y una contraseña de permiso para cifrar archivos PDF. Los pasos detallados son los siguientes.
- Cree un objeto PdfDocument.
- Cargue un archivo PDF de muestra utilizando el método PdfDocument.LoadFromFile().
- Obtiene los parámetros de seguridad del documento mediante la propiedad PdfDocument.Security.
- Cifre el archivo PDF con contraseña de apertura y contraseña de permiso mediante el método PdfSecurity.Encrypt(string openPassword, string permissionPassword, permisos de PdfPermissionsFlags, PdfEncryptionKeySize keySize).
- Guarde el archivo de resultados utilizando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace EncryptPDF
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load a sample PDF file
pdf.LoadFromFile(@"E:\Files\sample.pdf");
//Encrypt the PDF file with password
pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
//Save the result file
pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
}
}
}

Eliminar contraseña para descifrar un archivo PDF
Cuando necesite eliminar la contraseña de un archivo PDF, puede configurar la contraseña de apertura y la contraseña de permiso para que queden vacías mientras llama al método PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permisos, PdfEncryptionKeySize keySize, string originalPermissionPassword). Los pasos detallados son los siguientes.
- Cree un objeto PdfDocument.
- Cargue el archivo PDF cifrado con contraseña utilizando el método PdfDocument.LoadFromFile (nombre de archivo de cadena, contraseña de cadena).
- Obtiene los parámetros de seguridad del documento mediante la propiedad PdfDocument.Security.
- Descifre el archivo PDF configurando la contraseña de apertura y la contraseña de permiso para que se vacíe usando el método PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permisos, PdfEncryptionKeySize keySize, string originalPermissionPassword).
- Guarde el archivo de resultados utilizando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace DecryptPDF
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument pdf = new PdfDocument();
//Load the encrypted PDF file with password
pdf.LoadFromFile("Encrypt.pdf", "open");
//Set the password as empty to decrypt PDF
pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission");
//Save the result file
pdf.SaveToFile("Decrypt.pdf", FileFormat.PDF);
}
}
}

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.