C#/VB.NET: Dividir PDF em vários arquivos PDF
Índice
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
É útil dividir um único PDF em vários menores em determinadas situações. Por exemplo, você pode dividir grandes contratos, relatórios, livros, trabalhos acadêmicos ou outros documentos em partes menores, facilitando sua revisão ou reutilização. Neste artigo, você aprenderá como dividir PDF em PDFs de página única e como dividir PDF por intervalos de páginas em C# e VB.NET usando o 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 de esse link ou instalado via NuGet.
PM> Install-Package Spire.PDF
Dividir PDF em PDFs de uma página em C#, VB.NET
O Spire.PDF oferece o método Split() para dividir um documento PDF de várias páginas em vários arquivos de uma página. A seguir estão as etapas detalhadas.
- Crie um objeto dfDcoumentP.
- Carregue um documento PDF usando o método PdfDocument.LoadFromFile().
- Divida o documento em PDFs de uma página usando o 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 intervalos de páginas em C #, VB.NET
Nenhum método direto é oferecido para dividir documentos PDF por intervalos de páginas. Para fazer isso, criamos dois ou mais novos documentos PDF e importamos a página ou o intervalo de páginas do documento de origem para eles. Aqui estão as etapas detalhadas.
- Carregue o arquivo PDF de origem ao inicializar o objeto PdfDocument.
- Crie dois objetos PdfDocument adicionais.
- Importe a primeira página do arquivo de origem para o primeiro documento usando o método PdfDocument.InsertPage().
- Importe as páginas restantes do arquivo de origem para o segundo documento usando o método PdfDocument.InsertPageRange().
- Salve os dois documentos como arquivos PDF separados usando o 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 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: разделить PDF на несколько PDF-файлов
Оглавление
Установлено через NuGet
PM> Install-Package Spire.PDF
Ссылки по теме
В определенных ситуациях полезно разделить один PDF-файл на несколько более мелких. Например, вы можете разделить большие контракты, отчеты, книги, академические статьи или другие документы на более мелкие части, чтобы их было легко просматривать или повторно использовать. В этой статье вы узнаете, как разделить PDF на одностраничные PDF-файлы и как разделить PDF по диапазонам страниц в С# и 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 Teilen Sie PDFs in einseitige PDFs auf und wie Teilen Sie PDF nach Seitenbereichen in C# und VB.NET auf durch Verwendung von Spire.PDF for .NET.
Installieren Spire.PDF for .NET
TZunä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 : diviser 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 diviser 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 depuis ce lien ou installé 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 simple 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: Converta várias imagens em um único PDF
Índice
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
Se você tiver várias imagens que deseja combinar em um arquivo para facilitar a distribuição ou armazenamento, convertê-las em um único documento PDF é uma ótima solução. Esse processo não apenas economiza espaço, mas também garante que todas as suas imagens sejam mantidas juntas em um arquivo, facilitando o compartilhamento ou a transferência. Neste artigo, você aprenderá como combine várias imagens em um único documento PDF em C# e VB.NET usando Spire.PDF for .NET.
Instalar 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 de esse link ou instalado via NuGet.
PM> Install-Package Spire.PDF
Combine várias imagens em um único PDF em C# e VB.NET
Para converter todas as imagens em uma pasta em um PDF, iteramos cada imagem, adicionamos uma nova página ao PDF com o mesmo tamanho da imagem e, em seguida, desenhamos a imagem na nova página. A seguir estão as etapas detalhadas.
- Crie um objeto PdfDocument.
- Defina as margens da página como zero usando o método PdfDocument.PageSettings.SetMargins().
- Obtenha a pasta onde as imagens estão armazenadas.
- Percorra cada arquivo de imagem na pasta e obtenha a largura e a altura de uma imagem específica.
- Adicione uma nova página com a mesma largura e altura da imagem ao documento PDF usando o método PdfDocument.Pages.Add().
- Desenhe a imagem na página usando o método PdfPageBase.Canvas.DrawImage().
- Salve o documento usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace ConvertMultipleImagesIntoPdf
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Set the page margins to 0
doc.PageSettings.SetMargins(0);
//Get the folder where the images are stored
DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
//Iterate through the files in the folder
foreach (FileInfo file in folder.GetFiles())
{
//Load a particular image
Image image = Image.FromFile(file.FullName);
//Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
//Add a page that has the same size as the image
PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
//Create a PdfImage object based on the image
PdfImage pdfImage = PdfImage.FromImage(image);
//Draw image at (0, 0) of the page
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
}
//Save to file
doc.SaveToFile("CombinaImagesToPdf.pdf");
doc.Dispose();
}
}
}

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: преобразование нескольких изображений в один файл PDF
Оглавление
Установлено через NuGet
PM> Install-Package Spire.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-файл на C# и VB.NET
Чтобы преобразовать все изображения в папке в PDF, мы перебираем каждое изображение, добавляем новую страницу в PDF с тем же размером, что и изображение, а затем рисуем изображение на новой странице. Ниже приведены подробные шаги.
- Создайте объект PdfDocument.
- Установите поля страницы равными нулю, используя метод PdfDocument.PageSettings.SetMargins().
- Получить папку, в которой хранятся изображения.
- Переберите каждый файл изображения в папке и получите ширину и высоту определенного изображения.
- Добавьте новую страницу той же ширины и высоты, что и изображение, в документ PDF с помощью метода PdfDocument.Pages.Add().
- Нарисуйте изображение на странице с помощью метода PdfPageBase.Canvas.DrawImage().
- Сохраните документ с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace ConvertMultipleImagesIntoPdf
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Set the page margins to 0
doc.PageSettings.SetMargins(0);
//Get the folder where the images are stored
DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
//Iterate through the files in the folder
foreach (FileInfo file in folder.GetFiles())
{
//Load a particular image
Image image = Image.FromFile(file.FullName);
//Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
//Add a page that has the same size as the image
PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
//Create a PdfImage object based on the image
PdfImage pdfImage = PdfImage.FromImage(image);
//Draw image at (0, 0) of the page
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
}
//Save to file
doc.SaveToFile("CombinaImagesToPdf.pdf");
doc.Dispose();
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросите 30-дневную пробную лицензию для себя.
C#/VB.NET: Konvertieren Sie mehrere Bilder in ein einziges PDF
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.PDF
verwandte Links
Si tiene varias imágenes que desea combinar en un solo archivo para distribuirlas o almacenarlas más fácilmente, convertirlas en un solo documento PDF es una excelente solución. Este proceso no solo ahorra espacio, sino que también garantiza que todas sus imágenes se mantengan juntas en un solo archivo, lo que lo hace conveniente para compartir o transferir. En este artículo, aprenderá cómo combine varias imágenes en un único documento PDF 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
Combine múltiples imágenes en un solo PDF en C# y VB.NET
Para convertir todas las imágenes en una carpeta a un PDF, iteramos a través de cada imagen, agregamos una nueva página al PDF con el mismo tamaño que la imagen y luego dibujamos la imagen en la nueva página. Los siguientes son los pasos detallados.
- Cree un objeto PdfDocument.
- Establezca los márgenes de la página en cero utilizando el método PdfDocument.PageSettings.SetMargins().
- Obtenga la carpeta donde se almacenan las imágenes.
- Recorra cada archivo de imagen en la carpeta y obtenga el ancho y el alto de una imagen específica.
- Agregue una nueva página que tenga el mismo ancho y alto que la imagen al documento PDF usando el método PdfDocument.Pages.Add().
- Dibuja la imagen en la página usando el método PdfPageBase.Canvas.DrawImage().
- Guarde el documento usando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace ConvertMultipleImagesIntoPdf
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Set the page margins to 0
doc.PageSettings.SetMargins(0);
//Get the folder where the images are stored
DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
//Iterate through the files in the folder
foreach (FileInfo file in folder.GetFiles())
{
//Load a particular image
Image image = Image.FromFile(file.FullName);
//Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
//Add a page that has the same size as the image
PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
//Create a PdfImage object based on the image
PdfImage pdfImage = PdfImage.FromImage(image);
//Draw image at (0, 0) of the page
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
}
//Save to file
doc.SaveToFile("CombinaImagesToPdf.pdf");
doc.Dispose();
}
}
}

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: convertir múltiples imágenes en un solo PDF
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.PDF
enlaces relacionados
Si tiene varias imágenes que desea combinar en un solo archivo para distribuirlas o almacenarlas más fácilmente, convertirlas en un solo documento PDF es una excelente solución. Este proceso no solo ahorra espacio, sino que también garantiza que todas sus imágenes se mantengan juntas en un solo archivo, lo que lo hace conveniente para compartir o transferir. En este artículo, aprenderá cómo combine varias imágenes en un único documento PDF 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
Combine múltiples imágenes en un solo PDF en C# y VB.NET
Para convertir todas las imágenes en una carpeta a un PDF, iteramos a través de cada imagen, agregamos una nueva página al PDF con el mismo tamaño que la imagen y luego dibujamos la imagen en la nueva página. Los siguientes son los pasos detallados.
- Cree un objeto PdfDocument.
- Establezca los márgenes de la página en cero utilizando el método PdfDocument.PageSettings.SetMargins().
- Obtenga la carpeta donde se almacenan las imágenes.
- Recorra cada archivo de imagen en la carpeta y obtenga el ancho y el alto de una imagen específica.
- Agregue una nueva página que tenga el mismo ancho y alto que la imagen al documento PDF usando el método PdfDocument.Pages.Add().
- Dibuja la imagen en la página usando el método PdfPageBase.Canvas.DrawImage().
- Guarde el documento usando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace ConvertMultipleImagesIntoPdf
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Set the page margins to 0
doc.PageSettings.SetMargins(0);
//Get the folder where the images are stored
DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
//Iterate through the files in the folder
foreach (FileInfo file in folder.GetFiles())
{
//Load a particular image
Image image = Image.FromFile(file.FullName);
//Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
//Add a page that has the same size as the image
PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
//Create a PdfImage object based on the image
PdfImage pdfImage = PdfImage.FromImage(image);
//Draw image at (0, 0) of the page
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
}
//Save to file
doc.SaveToFile("CombinaImagesToPdf.pdf");
doc.Dispose();
}
}
}

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.