Tuesday, 01 July 2025 02:50

Spire.Office for Java 10.6.0 is released

We are excited to announce the release of Spire.Office for Java 10.6.0. In this version, Spire.Doc for Java adds support for reading and setting chart formats; Spire.XLS for Java supports using font streams when applying custom fonts; and Spire.Presentation for Java enables copying formulas within paragraphs. In addition, many known issues have been successfully resolved. More details are provided below.

Click the link to download Spire.Office for Java 10.6.0:

Here is a list of changes made in this release

Spire.Doc for Java

Category ID Description
New feature - Supports getting and setting chart formats, including chart titles, data labels, axes, legends, and data tables.
New feature - Optimizes the reading and setting of table formats.
New feature - Optimizes Word-to-PDF conversion performance, reducing processing time and memory usage.
Bug SPIREDOC-10375 Fixes the issue where TOC (Table of Contents) field updates failed.
Bug SPIREDOC-10582
SPIREDOC-11284
Fixes the issue where the “outputToOneSvg” parameter did not take effect during Word-to-SVG conversion.
Bug SPIREDOC-10792
SPIREDOC-11165
Fixes the "Key cannot be null" error when comparing Word documents.
Bug SPIREDOC-11237 Fixes the "Cannot insert an object of type 10 into the 6" error when comparing Word documents.
Bug SPIREDOC-11247 Fixes blank content issues when comparing Word documents.
Bug SPIREDOC-11264 Fixes incorrect content retrieval when calling getText().
Bug SPIREDOC-11281 Fixes incorrect line styles when accepting revisions.

Spire.XLS for Java

Category ID Description
New feature SPIREXLS-5817 Added support for font stream data when applying custom fonts.
Workbook book = new Workbook();
FileInputStream stream = new FileInputStream("fontpath");
book.setCustomFontStreams(new FileInputStream[]{stream});
New feature SPIREXLS-5821 Added support for setting setIsSaveBlankCell to control whether to export extra blank cells when converting Excel to HTML.
Workbook workbook = new Workbook();
workbook.loadFromFile(inputFile);
WorksheetsCollection sheets = workbook.getWorksheets();
HTMLOptions options = new HTMLOptions();
options.setImageEmbedded(true);
options.setStyleDefine(HTMLOptions.StyleDefineType.Inline);
options.setIsSaveBlankCell(true);
New feature SPIREXLS-5822 Added support for retrieving the cell location of embedded images.
Worksheet worksheet=wb.getWorksheets().get(0);
ExcelPicture[] cellimages=worksheet.getCellImages();
cellimages[0].getEmbedCellName()
Bug SPIREXLS-5522 Fixed the issue where sheet.getCellImages() could not retrieve images inserted by Office 365.
Bug SPIREXLS-5803 Fixed the issue where page numbering was incorrect when converting Excel to PDF.
Bug SPIREXLS-5812 Fixed the issue that caused a "NullPointerException" when copying Excel and saving it as .xls.
Bug SPIREXLS-5813 Fixed the issue where text content was truncated when converting Excel to PDF.
Bug SPIREXLS-5815 Fixed the issue that caused the error "For input string: 'OP_ID'" when converting CSV to Excel.
Bug SPIREXLS-5816 Fixed the issue where autoFitColumns() behaved incorrectly.
Bug SPIREXLS-5823 Fixed the issue where cell styling was inconsistent when converting Excel to HTML with setIsFixedTableColWidth enabled.
Bug SPIREXLS-5844 Fixed the issue that caused the error "Specified argument was out of the range of valid values" when converting Excel to HTML.
Bug SPIREXLS-5852
SPIREXLS-5855
Fixed the issue where Excel was rendered incorrectly when converting to HTML.

Spire.PDF for Java

Category ID Description
Bug SPIREPDF-7485 Fixed the issue that spaces were lost after converting PDF to PDFA3B.
Bug SPIREPDF-7497 Fixed the issue that signatures were lost after converting PDF to PDFA1A.
Bug SPIREPDF-7506 Fixed the issue that the program threw NullPointerException after converting OFD to PDF.
Bug SPIREPDF-7524 Fixed the issue that fonts were incorrect after replacing text.
Bug SPIREPDF-7530 Fixed the issue that table layouts were incorrect after creating booklets using PdfBookletCreator.

Spire.Presentation for Java

Category ID Description
New feature SPIREPPT-2856 Supports copying formulas within paragraphs.
Presentation sourcePpt = new Presentation();
sourcePpt.loadFromFile("data1.pptx");
Presentation targetPpt = new Presentation();
targetPpt.loadFromFile("data2.pptx");
copyNotes(sourcePpt.getSlides().get(0),targetPpt.getSlides().get(0));
targetPpt.saveToFile("out.pptx", com.spire.presentation.FileFormat.PPTX_2013);
public static void copyNotes(ISlide sourceSlide, ISlide targetSlide) throws DocumentEditException {
    if (sourceSlide.getNotesSlide() == null) {
        System.out.println(sourceSlide.getName());
        return;
    }
    // The paragraph contains formulas
    System.out.println(sourceSlide.getNotesSlide().getNotesTextFrame().getText());
    ParagraphCollection paragraphs = sourceSlide.getNotesSlide().getNotesTextFrame().getParagraphs();
    targetSlide.getNotesSlide().getNotesTextFrame().getParagraphs().append(paragraphs);
Bug SPIREPPT-2860 Fixes the issue where the height of the shape decreased after adding blank paragraphs.
Bug SPIREPPT-2850
SPIREPPT-2868
SPIREPPT-2869
SPIREPPT-2870
SPIREPPT-2879
SPIREPPT-2883
Fixed the issue where adding LaTeX formulas to PPTX files resulted in incorrect output.
Bug SPIREPPT-2861 Fixed the issue where converting ODP to PDF resulted in an “Unknown file format” error.
Bug SPIREPPT-2870 Fixed the issue where adding LaTeX formulas resulted in a “ClassCastException” error.
Bug SPIREPPT-2884 Fixed the issue where retrieving data resulted in a “NullPointerException” error.
Bug SPIREPPT-2891 Fixed the issue where adding LaTeX formulas caused an error when opening the resulting document.
Bug SPIREPPT-2894 Fixed the issue where retrieving data from a doughnut chart resulted in incorrect output.

We are excited to announce the release of Spire.Presentation for Java 10.6.2. The latest version supports copying formulas within paragraphs. Besides, some known bugs are fixed successfully in the new version, such as the issue that the program threw an "Unknown file format" error when converting ODP to PDF. More details are listed below.

Here is a list of changes made in this release

Category ID Description
New feature SPIREPPT-2856 Supports copying formulas within paragraphs.
Presentation sourcePpt = new Presentation();
sourcePpt.loadFromFile("data1.pptx");

Presentation targetPpt = new Presentation();
targetPpt.loadFromFile("data2.pptx");
copyNotes(sourcePpt.getSlides().get(0),targetPpt.getSlides().get(0));
targetPpt.saveToFile("out.pptx", com.spire.presentation.FileFormat.PPTX_2013);

public static void copyNotes(ISlide sourceSlide, ISlide targetSlide) throws DocumentEditException {
    if (sourceSlide.getNotesSlide() == null) {
        System.out.println(sourceSlide.getName());
        return;
    }

    // The paragraph contains formulas
    System.out.println(sourceSlide.getNotesSlide().getNotesTextFrame().getText());
    ParagraphCollection paragraphs = sourceSlide.getNotesSlide().getNotesTextFrame().getParagraphs();
    targetSlide.getNotesSlide().getNotesTextFrame().getParagraphs().append(paragraphs);
Bug SPIREPPT-2850
SPIREPPT-2868
SPIREPPT-2869
SPIREPPT-2870
SPIREPPT-2879
SPIREPPT-2883
Fixes the issue of incorrect rendering when adding LaTeX formulas to presentations.
Bug SPIREPPT-2861 Fixes the issue that the program threw an "Unknown file format" error when converting ODP to PDF.
Bug SPIREPPT-2870 Fixes the issue that the program threw a "ClassCastException" when adding LaTeX formulas.
Bug SPIREPPT-2884 Fixes the issue that the program threw a "NullPointerException" when retrieving content.
Bug SPIREPPT-2891 Fixes the issue that documents were corrupted when opening files with added LaTeX formulas.
Bug SPIREPPT-2894 Fixes the issue that data retrieval was incorrect for Doughnut Charts.
Click the link below to download Spire.Presentation for Java 10.6.2:
Tuesday, 01 July 2025 02:05

Spire.Office 10.6.0 is released

We’re pleased to announce the release of Spire.Office for .NET 10.6.0. This version introduces three new features, for example, Spire.Doc supports setting rounded corners on rectangle shapes; Spire.XLS supports the SHEETS() function. Meanwhile, a large number of known bugs have been successfully fixed. More details are given below.

In this version, the most recent versions of Spire.Doc, Spire.PDF, Spire.XLS, Spire.Presentation, Spire.Email, Spire.DocViewer, Spire.PDFViewer, Spire.Spreadsheet, Spire.OfficeViewer, Spire.DataExport, Spire.Barcode are included.

DLL Versions:

  • Spire.Doc.dll v13.6.14
  • Spire.Pdf.dll v11.6.18
  • Spire.XLS.dll v15.6.6
  • Spire.Presentation.dll v10.6.4
  • Spire.Barcode.dll v7.3.7
  • Spire.Email.dll v6.6.3
  • Spire.DocViewer.Forms.dll v8.9.1
  • Spire.PdfViewer.Asp.dll v8.1.3
  • Spire.PdfViewer.Forms.dll v8.1.3
  • Spire.Spreadsheet.dll v7.5.2
  • Spire.OfficeViewer.Forms.dll v8.8.0
  • Spire.DataExport.dll v4.9.0
  • Spire.DataExport.ResourceMgr.dll v2.1.0
Click the link to get the version Spire.Office 10.6.0:
More information of Spire.Office new release or hotfix:

Here is a list of changes made in this release

Spire.Doc

Category ID Description
New feature SPIREDOC-11102 Added support for setting rounded corners on rectangle shapes.
if (Cobj is ShapeObject)
{
    ShapeObject shape = (ShapeObject)Cobj;
    if (shape.ShapeType == ShapeType.RoundRectangle)
    {
        double cornerRadius = shape.AdjustHandles.GetRoundRectangleCornerRadius();
        shape.AdjustHandles.AdjustRoundRectangle(20);
    }
}
New feature SPIREDOC-11335 Added support for retrieving move revisions.
DifferRevisions differRevisions = new DifferRevions(Document)
List<DocumentObject> moveRevisions = differRevisions.MoveFromRevisions;
List<DocumentObject> movetoRevisions = differRevisions.MoveToRevisions;
Bug SPIREDOC-11060 Fixed the issue that the paragraph text content retrieved was incorrect.
Bug SPIREDOC-11066 Fixed the issue where the document language displayed incorrectly when ‘LocaleIdASCII’ was set to Hebrew (1037).
Bug SPIREDOC-11332 Fixed the issue where extra blank pages appeared when converting Word to PDF.

Spire.PDF

Category ID Description
Bug SPIREPDF-7302 Fixed the issue that converting PDF to images produced incorrect results.
Bug SPIREPDF-7491 Fixed the issue where the program threw an "ArgumentOutOfRangeException" error when loading a PDF file.
Bug SPIREPDF-7525 Fixed the issue where the program threw a "NullReferenceException" when calling the PdfDocument.Preview() method.
Bug SPIREPDF-4390
SPIREPDF-4462
Fixed the issue that the Arabic text rendering effect was displayed incorrectly.
Bug SPIREPDF-6586 Fixed the issue where the content was incorrect when converting PDF to Excel.
Bug SPIREPDF-7177 Fixed the issue where the bold text styles were lost when converting PDF to Markdown.
Bug SPIREPDF-7381 Fixed the issue where the output was incorrect when converting PDF to Image.
Bug SPIREPDF-7428 Fixed the issue where black background images were generated when converting PDF to Image.
Bug SPIREPDF-7498 Fixed the issue where font size did not auto adjust when setting fonts and "Autosize" for PDF text fields.
Bug SPIREPDF-7522
SPIREPDF-7537
Fixed the issue that it was failed to remove JavaScript from a PDF document.
Bug SPIREPDF-6918
SPIREPDF-6919
Fixed the issue of incorrect rendering when converting PDF to images.
Bug SPIREPDF-7117 Fixed the inconsistency in transparency when converting PDF to images.

Spire.XLS

Category ID Description
New feature SPIREXLS-5806 Added support for the SHEETS function.
sheet.Range["B2"].Formula = "=SHEETS()";
sheet.Range["B3"].Formula = "=SHEETS(Sheet2!C5)";
sheet.Range["B4"].Formula = "=SHEETS(Sheet3:Sheet5!A1)";
sheet.Range["B6"].Formula = "=SHEETS(Sheet4!C5);
Bug SPIREXLS-5802 Fixed the issue where the AutoFitColumns effect was not working correctly.
Bug SPIREXLS-5804 Fixed the issue where the style of shapes was incorrect when copying worksheets.
Bug SPIREXLS-5814
SPIREXLS-5853
Fixed the issue where the data was incorrect when saving a sheet as an image.
Bug SPIREXLS-5819 Fixed the issue where the saved Excel file reported errors when opened.
Bug SPIREXLS-5832 Fixed the issue where saving an Excel file to PDF/A3B was incorrect.
Bug SPIREXLS-5834 Fixed the issue where the left and right margins were incorrect when converting Excel to PDF.
Bug SPIREXLS-5841 Fixed the issue where the content was incorrect when converting a CellRange to an image.

Spire.Prensentation

Category ID Description
Bug SPIREPPT-2876 Fixed the issue where shapes were rendered incorrectly when converting slides to SVG.
Bug SPIREPPT-2892 Fixed the issue where images were cropped during PowerPoint-to-PDF conversion.

Spire.DocViewer

Category ID Description
Bug SPIREDOCVIEWER-108 Fixed the issue where documents displayed incompletely when zoom was set to 120%.
Bug SPIREDOCVIEWER-115 Optimized document rendering performance on the WPF platform.

No mundo do desenvolvimento de software e gerenciamento de documentos, saber como dividir PDF em C# é uma habilidade fundamental para desenvolvedores .NET. Quer você precise separar grandes relatórios em partes menores, extrair páginas específicas para distribuição ou organizar o conteúdo de forma mais eficiente, dividir arquivos PDF programaticamente pode economizar uma quantidade significativa de tempo e esforço.

Guia visual para Dividir Arquivos PDF em C#

Este guia explora como dividir arquivos PDF em C# usando a biblioteca Spire.PDF for .NET — uma solução de processamento de PDF robusta e livre de dependências.

Apresentando o Spire.PDF for .NET

O Spire.PDF é uma biblioteca .NET rica em recursos que oferece:

  • Capacidades abrangentes de manipulação de PDF
  • Zero dependências do Adobe Acrobat
  • Suporte para .NET Framework, .NET Core, .NET 5+, MonoAndroid e Xamarin.iOS

Antes de começar a dividir um PDF em vários arquivos em aplicações C#, é necessário instalar a biblioteca via Gerenciador de Pacotes NuGet.

  1. Abra seu projeto C# no Visual Studio.
  2. Clique com o botão direito no projeto no Gerenciador de Soluções e selecione "Gerenciar Pacotes NuGet".
  3. Na janela do Gerenciador de Pacotes NuGet, procure por "Spire.PDF".
  4. Selecione a versão apropriada da biblioteca e clique em "Instalar". O NuGet fará o download e adicionará as referências necessárias ao seu projeto.

Método Alternativo: Baixe manualmente a DLL do site oficial do Spire.PDF e referencie-a em seu projeto.

Dividir um Documento PDF em C# - Exemplos de Código

Agora que a biblioteca está configurada em seu projeto, vamos ver como dividir um PDF no .NET. Existem diferentes cenários para dividir um PDF, como dividi-lo em páginas individuais ou dividi-lo em vários PDFs com base em um número específico de páginas. Abordaremos ambos os casos comuns.

Dividir PDF em Páginas Individuais

A seguir, o exemplo de código C# para dividir um documento PDF em arquivos PDF individuais, cada um contendo uma única página do documento original:

using Spire.Pdf;

namespace SplitPDFIntoMultipleFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            // Especifique o caminho do arquivo de entrada
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Especifique o diretório de saída
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Crie um objeto PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Carregue um arquivo PDF
            pdf.LoadFromFile(inputFile);

            // Divida o PDF em vários PDFs de uma página
            pdf.Split(outputDirectory + "output-{0}.pdf", 1);
        }
    }
}

Ao chamar o método Split(), você pode dividir o documento PDF de entrada (contendo 10 páginas) em 10 arquivos individuais.

Dividir páginas de PDF em vários arquivos PDF.

Dividir PDF em Vários Arquivos por Intervalos de Páginas

Suponha que você queira dividir um PDF grande em vários PDFs menores, cada um contendo um número especificado de páginas. Você pode criar dois ou mais novos documentos PDF e, em seguida, importar a página ou o intervalo de páginas do PDF de origem para eles.

Aqui estão os passos gerais para dividir um arquivo PDF por páginas em C#:

  • Carregue o PDF de origem.
  • Crie dois PDFs vazios para conter as páginas divididas.
  • Dividir Páginas do PDF:
    • Use o método InsertPage() para importar uma página específica do PDF de origem para o primeiro novo PDF.
    • Use o método InsertPageRange() para importar um intervalo de páginas do PDF de origem para o segundo novo PDF.
  • Salve ambos os novos PDFs no diretório de saída.

Exemplo de código C#:

using Spire.Pdf;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            // Especifique o caminho do arquivo de entrada
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Especifique o diretório de saída
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Carregue o arquivo PDF de origem ao inicializar o objeto PdfDocument
            PdfDocument sourcePdf = new PdfDocument(inputFile);

            // Crie dois novos documentos PDF
            PdfDocument pdf1 = new PdfDocument();
            PdfDocument pdf2 = new PdfDocument();

            // Insira a primeira página do PDF de origem no primeiro documento
            pdf1.InsertPage(sourcePdf, 0);

            // Insira as páginas restantes do PDF de origem no segundo documento
            pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);

            // Salve os dois documentos PDF
            pdf1.SaveToFile(outputDirectory + "output-1.pdf");
            pdf2.SaveToFile(outputDirectory + "output-2.pdf");
        }
    }
}

Ao executar este código, você pode extrair a página 1 e as páginas 2-10 do PDF de entrada em 2 arquivos PDF separados.

Dividir um arquivo PDF por intervalos de páginas personalizados.


Dicas Avançadas para Divisão de PDF

  • Intervalos de Páginas Dinâmicos: Para dividir em vários intervalos (por exemplo, páginas 1-3, 5-7), crie objetos PdfDocument adicionais e ajuste o índice de inserção de página do método InsertPageRange().

  • Convenções de Nomenclatura de Arquivos: Use padrões descritivos ao nomear os arquivos de saída através do parâmetro destFilePattern do método Split() para organizar melhor os arquivos (por exemplo, report_part-{0}.pdf).

  • Tratamento de Erros: Adicione blocos try-catch para tratar exceções durante as operações de arquivo.

try
{
    /* Código de divisão de PDF */
}
catch (Exception ex)
{
    Console.WriteLine("Erro: " + ex.Message);
}

FAQs (demos em VB.NET)

Q1: Como removo marcas d'água no arquivo de saída?

R: Você pode solicitar uma licença de teste aqui (válida por 30 dias) para remover as marcas d'água e limitações. Ou você pode experimentar a edição gratuita da Comunidade.

Q2: A divisão preserva hiperlinks/campos de formulário?

R:

Elementos Preservado?
Hiperlinks ✅ Sim
Campos de Formulário ✅ Sim
Anotações ✅ Sim
Assinaturas Digitais ❌ Não (requer contexto completo do documento)

Q3: Posso dividir uma única página de PDF em várias páginas/arquivos?

R: Sim. O Spire.PDF também suporta a divisão horizontal ou vertical de uma página de PDF em duas ou mais páginas. Tutorial: Dividir uma Página de PDF em Várias Páginas em C#

Q4: Existe uma demonstração em VB.NET для dividir arquivos PDF?

R: Como uma biblioteca .NET nativa, o Spire.PDF funciona de forma idêntica em C# e VB.NET. Portanto, você pode usar alguma ferramenta de conversão de código (por exemplo, Telerik Code Converter) para traduzir instantaneamente os exemplos de C# para VB.NET.


Conclusão

O Spire.PDF simplifica a divisão de PDFs em C# com métodos intuitivos. Se você precisa de uma divisão básica página por página ou de uma divisão mais avançada baseada em intervalos de páginas, a biblioteca fornece a funcionalidade necessária. Seguindo este guia, você pode implementar eficientemente a divisão de PDF em suas aplicações C# ou VB.NET, melhorando a produtividade e o gerenciamento de documentos.

Onde Obter Ajuda

Dica Profissional: Combine a divisão com os recursos de conversão do Spire.PDF para extrair páginas como imagens ou outros formatos de arquivo.

В мире разработки программного обеспечения и управления документами знание того, как разделить PDF на C#, является фундаментальным навыком для разработчиков .NET. Независимо от того, нужно ли вам разделять большие отчеты на более мелкие части, извлекать определенные страницы для распространения или более эффективно организовывать контент, программное разделение файлов PDF может сэкономить значительное количество времени и усилий.

Визуальное руководство по разделению файлов PDF на C#

В этом руководстве рассматривается, как разделять файлы PDF на C# с помощью библиотеки Spire.PDF for .NET — надежного решения для обработки PDF без зависимостей.

Представляем Spire.PDF for .NET

Spire.PDF — это многофункциональная библиотека .NET, предлагающая:

  • Комплексные возможности для работы с PDF
  • Нулевая зависимость от Adobe Acrobat
  • Поддержка .NET Framework, .NET Core, .NET 5+, MonoAndroid и Xamarin.iOS

Прежде чем вы сможете начать разделение PDF на несколько файлов в приложениях C#, необходимо установить библиотеку через менеджер пакетов NuGet.

  1. Откройте свой проект C# в Visual Studio.
  2. Щелкните правой кнопкой мыши по проекту в обозревателе решений и выберите «Управление пакетами NuGet».
  3. В окне менеджера пакетов NuGet найдите «Spire.PDF».
  4. Выберите подходящую версию библиотеки и нажмите «Установить». NuGet загрузит и добавит необходимые ссылки в ваш проект.

Альтернативный метод: вручную загрузите DLL с официального сайта Spire.PDF и сошлитесь на нее в своем проекте.

Разделение документа PDF на C# - Примеры кода

Теперь, когда библиотека настроена в вашем проекте, давайте посмотрим, как разделить PDF в .NET. Существуют различные сценарии разделения PDF, такие как разделение на отдельные страницы или на несколько PDF-файлов на основе определенного количества страниц. Мы рассмотрим оба распространенных случая.

Разделить PDF на отдельные страницы

Ниже приведен пример кода на C# для разделения документа PDF на отдельные PDF-файлы, каждый из которых содержит одну страницу из исходного документа:

using Spire.Pdf;

namespace SplitPDFIntoMultipleFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            // Укажите путь к входному файлу
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Укажите выходной каталог
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Создайте объект PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Загрузите PDF-файл
            pdf.LoadFromFile(inputFile);

            // Разделите PDF на несколько одностраничных PDF-файлов
            pdf.Split(outputDirectory + "output-{0}.pdf", 1);
        }
    }
}

Вызвав метод Split(), вы можете разделить входной PDF-документ (содержащий 10 страниц) на 10 отдельных файлов.

Разделить страницы PDF на несколько PDF-файлов.

Разделить PDF на несколько файлов по диапазонам страниц

Предположим, вы хотите разделить большой PDF-файл на несколько меньших PDF-файлов, каждый из которых содержит указанное количество страниц. Вы можете создать два или более новых документа PDF, а затем импортировать в них страницу или диапазон страниц из исходного PDF.

Вот общие шаги по разделению файла PDF по страницам на C#:

  • Загрузите исходный PDF.
  • Создайте два пустых PDF-файла для хранения разделенных страниц.
  • Разделите страницы PDF:
    • Используйте метод InsertPage() для импорта указанной страницы из исходного PDF в первый новый PDF.
    • Используйте метод InsertPageRange() для импорта диапазона страниц из исходного PDF во второй новый PDF.
  • Сохраните оба новых PDF-файла в выходной каталог.

Пример кода на C#:

using Spire.Pdf;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            // Укажите путь к входному файлу
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Укажите выходной каталог
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Загрузите исходный PDF-файл при инициализации объекта PdfDocument
            PdfDocument sourcePdf = new PdfDocument(inputFile);

            // Создайте два новых документа PDF
            PdfDocument pdf1 = new PdfDocument();
            PdfDocument pdf2 = new PdfDocument();

            // Вставьте первую страницу исходного PDF в первый документ
            pdf1.InsertPage(sourcePdf, 0);

            // Вставьте остальные страницы исходного PDF во второй документ
            pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);

            // Сохраните два документа PDF
            pdf1.SaveToFile(outputDirectory + "output-1.pdf");
            pdf2.SaveToFile(outputDirectory + "output-2.pdf");
        }
    }
}

Выполнив этот код, вы можете извлечь страницу 1 и страницы 2-10 из входного PDF в 2 отдельных PDF-файла.

Разделить PDF-файл по пользовательским диапазонам страниц.


Расширенные советы по разделению PDF

  • Динамические диапазоны страниц: чтобы разделить на несколько диапазонов (например, страницы 1-3, 5-7), создайте дополнительные объекты PdfDocument и настройте индекс вставки страниц метода InsertPageRange().

  • Соглашения об именовании файлов: используйте описательные шаблоны при именовании выходных файлов через параметр destFilePattern метода Split() для лучшей организации файлов (например, report_part-{0}.pdf).

  • Обработка ошибок: добавьте блоки try-catch для обработки исключений во время файловых операций.

try
{
    /* Код для разделения PDF */
}
catch (Exception ex)
{
    Console.WriteLine("Ошибка: " + ex.Message);
}

Часто задаваемые вопросы (демо на VB.NET)

В1: Как удалить водяные знаки в выходном файле?

О: Вы можете запросить пробную лицензию здесь (действительна в течение 30 дней), чтобы удалить водяные знаки и ограничения. Или вы можете попробовать бесплатную версию Community.

В2: Сохраняются ли при разделении гиперссылки/поля форм?

О:

Элементы Сохранено?
Гиперссылки ✅ Да
Поля форм ✅ Да
Аннотации ✅ Да
Цифровые подписи ❌ Нет (требуется полный контекст документа)

В3: Могу ли я разделить одну страницу PDF на несколько страниц/файлов?

О: Да. Spire.PDF также поддерживает горизонтальное или вертикальное разделение страницы PDF на две или более страниц. Руководство: Разделение страницы PDF на несколько страниц на C#

В4: Есть ли демо-версия на VB.NET для разделения PDF-файлов?

О: Будучи нативной библиотекой .NET, Spire.PDF работает одинаково как на C#, так и на VB.NET. Поэтому вы можете использовать какой-либо инструмент для конвертации кода (например, Telerik Code Converter) для мгновенного перевода примеров с C# на VB.NET.


Заключение

Spire.PDF упрощает разделение PDF-файлов на C# с помощью интуитивно понятных методов. Независимо от того, нужно ли вам базовое разделение по страницам или более сложное разделение на основе диапазонов страниц, библиотека предоставляет необходимую функциональность. Следуя этому руководству, вы сможете эффективно реализовать разделение PDF в своих приложениях на C# или VB.NET, повысив производительность и управление документами.

Где получить помощь

Совет профессионала: комбинируйте разделение с функциями преобразования Spire.PDF для извлечения страниц в виде изображений или других форматов файлов.

In der Welt der Softwareentwicklung und des Dokumentenmanagements ist das Wissen, wie man ein PDF in C# teilt, eine grundlegende Fähigkeit für .NET-Entwickler. Ob Sie große Berichte in kleinere Teile zerlegen, bestimmte Seiten für die Verteilung extrahieren oder Inhalte effizienter organisieren müssen, das programmgesteuerte Aufteilen von PDF-Dateien kann eine erhebliche Menge an Zeit und Aufwand sparen.

Visuelle Anleitung zum Aufteilen von PDF-Dateien in C#

Diese Anleitung erläutert, wie man PDF-Dateien in C# teilt mit der Bibliothek Spire.PDF for .NET — eine robuste, abhängigkeitsfreie Lösung zur PDF-Verarbeitung.

Einführung in Spire.PDF for .NET

Spire.PDF ist eine funktionsreiche .NET-Bibliothek, die Folgendes bietet:

  • Umfassende PDF-Manipulationsfähigkeiten
  • Keine Abhängigkeiten von Adobe Acrobat
  • Unterstützung für .NET Framework, .NET Core, .NET 5+, MonoAndroid und Xamarin.iOS

Bevor Sie mit dem Aufteilen eines PDFs in mehrere Dateien in C#-Anwendungen beginnen können, ist es notwendig, die Bibliothek über den NuGet Package Manager zu installieren.

  1. Öffnen Sie Ihr C#-Projekt in Visual Studio.
  2. Klicken Sie mit der rechten Maustaste auf das Projekt im Solution Explorer und wählen Sie „NuGet-Pakete verwalten“.
  3. Suchen Sie im NuGet-Paket-Manager-Fenster nach „Spire.PDF“.
  4. Wählen Sie die entsprechende Version der Bibliothek aus und klicken Sie auf „Installieren“. NuGet lädt die erforderlichen Referenzen herunter und fügt sie Ihrem Projekt hinzu.

Alternative Methode: Laden Sie die DLL manuell von der offiziellen Website von Spire.PDF herunter und referenzieren Sie sie in Ihrem Projekt.

Ein PDF-Dokument in C# teilen - Codebeispiele

Nachdem die Bibliothek in Ihrem Projekt eingerichtet ist, schauen wir uns an, wie man ein PDF in .NET aufteilt. Es gibt verschiedene Szenarien für das Aufteilen eines PDFs, z. B. das Aufteilen in einzelne Seiten oder das Aufteilen in mehrere PDFs basierend auf einer bestimmten Anzahl von Seiten. Wir werden beide häufigen Fälle behandeln.

PDF in einzelne Seiten aufteilen

Das folgende C#-Codebeispiel zeigt, wie ein PDF-Dokument in einzelne PDF-Dateien aufgeteilt wird, von denen jede eine einzelne Seite aus dem Originaldokument enthält:

using Spire.Pdf;

namespace SplitPDFIntoMultipleFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            // Pfad zur Eingabedatei angeben
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Ausgabeverzeichnis angeben
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Ein PdfDocument-Objekt erstellen
            PdfDocument pdf = new PdfDocument();

            // Eine PDF-Datei laden
            pdf.LoadFromFile(inputFile);

            // Das PDF in mehrere einseitige PDFs aufteilen
            pdf.Split(outputDirectory + "output-{0}.pdf", 1);
        }
    }
}

Durch den Aufruf der Methode Split() können Sie das Eingabe-PDF-Dokument (mit 10 Seiten) in 10 einzelne Dateien aufteilen.

PDF-Seiten in mehrere PDF-Dateien aufteilen.

PDF nach Seitenbereichen in mehrere Dateien aufteilen

Angenommen, Sie möchten ein großes PDF in mehrere kleinere PDFs aufteilen, von denen jedes eine bestimmte Anzahl von Seiten enthält. Sie können zwei oder mehr neue PDF-Dokumente erstellen und dann die Seite oder den Seitenbereich aus dem Quell-PDF in diese importieren.

Hier sind die allgemeinen Schritte, um eine PDF-Datei nach Seiten in C# aufzuteilen:

  • Laden Sie das Quell-PDF.
  • Erstellen Sie zwei leere PDFs, um die geteilten Seiten aufzunehmen.
  • PDF-Seiten aufteilen:
    • Verwenden Sie die Methode InsertPage(), um eine bestimmte Seite aus dem Quell-PDF in das erste neue PDF zu importieren.
    • Verwenden Sie die Methode InsertPageRange(), um einen Seitenbereich aus dem Quell-PDF in das zweite neue PDF zu importieren.
  • Speichern Sie beide neuen PDFs im Ausgabeverzeichnis.

Beispielcode in C#:

using Spire.Pdf;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            // Pfad zur Eingabedatei angeben
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Ausgabeverzeichnis angeben
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Die Quell-PDF-Datei laden, während das PdfDocument-Objekt initialisiert wird
            PdfDocument sourcePdf = new PdfDocument(inputFile);

            // Zwei neue PDF-Dokumente erstellen
            PdfDocument pdf1 = new PdfDocument();
            PdfDocument pdf2 = new PdfDocument();

            // Die erste Seite des Quell-PDFs in das erste Dokument einfügen
            pdf1.InsertPage(sourcePdf, 0);

            // Die restlichen Seiten des Quell-PDFs in das zweite Dokument einfügen
            pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);

            // Die beiden PDF-Dokumente speichern
            pdf1.SaveToFile(outputDirectory + "output-1.pdf");
            pdf2.SaveToFile(outputDirectory + "output-2.pdf");
        }
    }
}

Durch Ausführen dieses Codes können Sie die Seite 1 und die Seiten 2-10 des Eingabe-PDFs in 2 separate PDF-Dateien extrahieren.

Eine PDF-Datei nach benutzerdefinierten Seitenbereichen aufteilen.


Erweiterte Tipps zum Aufteilen von PDFs

  • Dynamische Seitenbereiche: Um in mehrere Bereiche aufzuteilen (z. B. Seiten 1-3, 5-7), erstellen Sie zusätzliche PdfDocument-Objekte und passen Sie den Seiteneinfügeindex der Methode InsertPageRange() an.

  • Dateibenennungskonventionen: Verwenden Sie beschreibende Muster bei der Benennung der Ausgabedateien über den Parameter destFilePattern der Methode Split(), um die Dateien besser zu organisieren (z. B. report_part-{0}.pdf).

  • Fehlerbehandlung: Fügen Sie try-catch-Blöcke hinzu, um Ausnahmen während Dateioperationen zu behandeln.

try
{
    /* Code zum Aufteilen von PDF */
}
catch (Exception ex)
{
    Console.WriteLine("Fehler: " + ex.Message);
}

Häufig gestellte Fragen (VB.NET-Demos)

F1: Wie entferne ich Wasserzeichen in der Ausgabedatei?

A: Sie können hier eine Testlizenz anfordern (gültig für 30 Tage), um die Wasserzeichen und Einschränkungen zu entfernen. Oder Sie können die kostenlose Community-Edition ausprobieren.

F2: Bleiben Hyperlinks/Formularfelder beim Aufteilen erhalten?

A:

Elemente Erhalten?
Hyperlinks ✅ Ja
Formularfelder ✅ Ja
Anmerkungen ✅ Ja
Digitale Signaturen ❌ Nein (erfordert vollständigen Dokumentenkontext)

F3: Kann ich eine einzelne PDF-Seite in mehrere Seiten/Dateien aufteilen?

A: Ja. Spire.PDF unterstützt auch das horizontale oder vertikale Aufteilen einer PDF-Seite in zwei oder mehr Seiten. Tutorial: Eine PDF-Seite in mehrere Seiten in C# aufteilen

F4: Gibt es eine VB.NET-Demo zum Aufteilen von PDF-Dateien?

A: Als native .NET-Bibliothek funktioniert Spire.PDF in C# und VB.NET identisch. Daher können Sie ein Code-Konverter-Tool (z. B. Telerik Code Converter) verwenden, um C#-Beispiele sofort in VB.NET zu übersetzen.


Fazit

Spire.PDF vereinfacht das Aufteilen von PDFs in C# mit intuitiven Methoden. Egal, ob Sie eine grundlegende seitenweise Aufteilung oder eine fortgeschrittenere Aufteilung nach Seitenbereichen benötigen, die Bibliothek bietet die notwendige Funktionalität. Indem Sie dieser Anleitung folgen, können Sie das Aufteilen von PDFs effizient in Ihren C#- oder VB.NET-Anwendungen implementieren und so die Produktivität und das Dokumentenmanagement verbessern.

Wo Sie Hilfe finden

Profi-Tipp: Kombinieren Sie das Aufteilen mit den Konvertierungsfunktionen von Spire.PDF, um Seiten als Bilder oder in andere Dateiformate zu extrahieren.

En el mundo del desarrollo de software y la gestión de documentos, saber cómo dividir PDF en C# es una habilidad fundamental para los desarrolladores de .NET. Ya sea que necesite separar informes grandes en partes más pequeñas, extraer páginas específicas para su distribución u organizar el contenido de manera más eficiente, dividir archivos PDF mediante programación puede ahorrar una cantidad significativa de tiempo y esfuerzo.

Guía visual para dividir archivos PDF en C#

Esta guía explora cómo dividir archivos PDF en C# utilizando la biblioteca Spire.PDF for .NET — una solución de procesamiento de PDF robusta y sin dependencias.

Introducción a Spire.PDF for .NET

Spire.PDF es una biblioteca de .NET rica en funciones que ofrece:

  • Capacidades completas de manipulación de PDF
  • Cero dependencias de Adobe Acrobat
  • Soporte para .NET Framework, .NET Core, .NET 5+, MonoAndroid y Xamarin.iOS

Antes de que pueda comenzar a dividir un PDF en múltiples archivos en aplicaciones de C#, es necesario instalar la biblioteca a través del Administrador de paquetes NuGet.

  1. Abra su proyecto de C# en Visual Studio.
  2. Haga clic con el botón derecho en el proyecto en el Explorador de soluciones y seleccione "Administrar paquetes NuGet".
  3. En la ventana del Administrador de paquetes NuGet, busque "Spire.PDF".
  4. Seleccione la versión apropiada de la biblioteca y haga clic en "Instalar". NuGet descargará y agregará las referencias necesarias a su proyecto.

Método alternativo: descargue manualmente la DLL desde el sitio web oficial de Spire.PDF y haga referencia a ella en su proyecto.

Dividir un documento PDF en C# - Ejemplos de código

Ahora que la biblioteca está configurada en su proyecto, veamos cómo dividir un PDF en .NET. Existen diferentes escenarios para dividir un PDF, como dividirlo en páginas individuales o dividirlo en múltiples PDF según un número específico de páginas. Cubriremos ambos casos comunes.

Dividir PDF en páginas individuales

El siguiente es el ejemplo de código en C# para dividir un documento PDF en archivos PDF individuales, cada uno con una sola página del documento original:

using Spire.Pdf;

namespace SplitPDFIntoMultipleFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            // Especificar la ruta del archivo de entrada
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Especificar el directorio de salida
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Crear un objeto PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Cargar un archivo PDF
            pdf.LoadFromFile(inputFile);

            // Dividir el PDF en múltiples PDF de una página
            pdf.Split(outputDirectory + "output-{0}.pdf", 1);
        }
    }
}

Al llamar al método Split(), puede dividir el documento PDF de entrada (que contiene 10 páginas) en 10 archivos individuales.

Dividir páginas de PDF en múltiples archivos PDF.

Dividir PDF en múltiples archivos por rangos de páginas

Suponga que desea dividir un PDF grande en varios PDF más pequeños, cada uno con un número específico de páginas. Puede crear dos o más documentos PDF nuevos y luego importar la página o el rango de páginas del PDF de origen a ellos.

Estos son los pasos generales para dividir un archivo PDF por páginas en C#:

  • Cargue el PDF de origen.
  • Cree dos PDF vacíos para contener las páginas divididas.
  • Dividir páginas de PDF:
    • Use el método InsertPage() para importar una página específica del PDF de origen al primer PDF nuevo.
    • Use el método InsertPageRange() para importar un rango de páginas del PDF de origen al segundo PDF nuevo.
  • Guarde ambos PDF nuevos en el directorio de salida.

Ejemplo de código en C#:

using Spire.Pdf;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            // Especificar la ruta del archivo de entrada
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Especificar el directorio de salida
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Cargar el archivo PDF de origen al inicializar el objeto PdfDocument
            PdfDocument sourcePdf = new PdfDocument(inputFile);

            // Crear dos nuevos documentos PDF
            PdfDocument pdf1 = new PdfDocument();
            PdfDocument pdf2 = new PdfDocument();

            // Insertar la primera página del PDF de origen en el primer documento
            pdf1.InsertPage(sourcePdf, 0);

            // Insertar el resto de las páginas del PDF de origen en el segundo documento
            pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);

            // Guardar los dos documentos PDF
            pdf1.SaveToFile(outputDirectory + "output-1.pdf");
            pdf2.SaveToFile(outputDirectory + "output-2.pdf");
        }
    }
}

Al ejecutar este código, puede extraer la página 1 y las páginas 2-10 del PDF de entrada en 2 archivos PDF separados.

Dividir un archivo PDF por rangos de páginas personalizados.


Consejos avanzados para la división de PDF

  • Rangos de páginas dinámicos: para dividir en múltiples rangos (por ejemplo, páginas 1-3, 5-7), cree objetos PdfDocument adicionales y ajuste el índice de inserción de páginas del método InsertPageRange().

  • Convenciones de nomenclatura de archivos: use patrones descriptivos al nombrar los archivos de salida a través del parámetro destFilePattern del método Split() para organizar mejor los archivos (por ejemplo, report_part-{0}.pdf).

  • Manejo de errores: agregue bloques try-catch para manejar excepciones durante las operaciones de archivo.

try
{
    /* Código de división de PDF */
}
catch (Exception ex)
{
    Console.WriteLine("Error: " + ex.Message);
}

Preguntas frecuentes (demos en VB.NET)

P1: ¿Cómo elimino las marcas de agua en el archivo de salida?

R: Puede solicitar una licencia de prueba aquí (válida por 30 días) para eliminar las marcas de agua y las limitaciones. O puede probar la edición Community gratuita.

P2: ¿La división conserva los hipervínculos/campos de formulario?

R:

Elementos ¿Se conserva?
Hipervínculos ✅ Sí
Campos de formulario ✅ Sí
Anotaciones ✅ Sí
Firmas digitales ❌ No (requiere el contexto completo del documento)

P3: ¿Puedo dividir una sola página de PDF en múltiples páginas/archivos?

R: Sí. Spire.PDF también admite la división horizontal o vertical de una página de PDF en dos o más páginas. Tutorial: Dividir una página de PDF en múltiples páginas en C#

P4: ¿Existe una demostración en VB.NET para dividir archivos PDF?

R: Como biblioteca nativa de .NET, Spire.PDF funciona de manera idéntica tanto en C# como en VB.NET. Por lo tanto, puede usar alguna herramienta de conversión de código (por ejemplo, Telerik Code Converter) para traducir instantáneamente los ejemplos de C# a VB.NET.


Conclusión

Spire.PDF simplifica la división de PDF en C# con métodos intuitivos. Ya sea que necesite una división básica página por página o una división más avanzada basada en rangos de páginas, la biblioteca proporciona la funcionalidad necesaria. Siguiendo esta guía, puede implementar eficientemente la división de PDF en sus aplicaciones de C# o VB.NET, mejorando la productividad y la gestión de documentos.

Dónde obtener ayuda

Consejo profesional: combine la división con las funciones de conversión de Spire.PDF para extraer páginas como imágenes u otros formatos de archivo.

소프트웨어 개발 및 문서 관리 분야에서 C#에서 PDF를 분할하는 방법은 .NET 개발자에게 필수적인 기술입니다. 큰 보고서를 작은 부분으로 나누거나, 배포를 위해 특정 페이지를 추출하거나, 콘텐츠를 더 효율적으로 구성해야 할 때 프로그래밍 방식으로 PDF 파일을 분할하면 상당한 시간과 노력을 절약할 수 있습니다.

C#에서 PDF 파일 분할을 위한 시각적 가이드

이 가이드에서는 강력하고 종속성이 없는 PDF 처리 솔루션인 Spire.PDF for .NET 라이브러리를 사용하여 C#에서 PDF 파일을 분할하는 방법을 살펴봅니다.

Spire.PDF for .NET 소개

Spire.PDF는 다음과 같은 기능을 제공하는 풍부한 기능의 .NET 라이브러리입니다.

  • 포괄적인 PDF 조작 기능
  • Adobe Acrobat에 대한 종속성 없음
  • .NET Framework, .NET Core, .NET 5+, MonoAndroid 및 Xamarin.iOS 지원

C# 애플리케이션에서 PDF를 여러 파일로 분할하기 전에 NuGet 패키지 관리자를 통해 라이브러리를 설치해야 합니다.

  1. Visual Studio에서 C# 프로젝트를 엽니다.
  2. 솔루션 탐색기에서 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 "NuGet 패키지 관리"를 선택합니다.
  3. NuGet 패키지 관리자 창에서 "Spire.PDF"를 검색합니다.
  4. 적절한 버전의 라이브러리를 선택하고 "설치"를 클릭합니다. NuGet이 필요한 참조를 다운로드하여 프로젝트에 추가합니다.

대체 방법: Spire.PDF 공식 웹사이트에서 DLL을 수동으로 다운로드하여 프로젝트에서 참조합니다.

C#에서 PDF 문서 분할 - 코드 예제

이제 라이브러리가 프로젝트에 설정되었으므로 .NET에서 PDF를 분할하는 방법을 살펴보겠습니다. PDF를 개별 페이지로 분할하거나 특정 페이지 수에 따라 여러 PDF로 분할하는 등 다양한 시나리오가 있습니다. 두 가지 일반적인 경우를 모두 다룰 것입니다.

PDF를 개별 페이지로 분할

다음은 PDF 문서를 각기 원본 문서의 한 페이지만 포함하는 개별 PDF 파일로 분할하는 C# 코드 예제입니다.

using Spire.Pdf;

namespace SplitPDFIntoMultipleFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            // 입력 파일 경로 지정
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // 출력 디렉토리 지정
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // PdfDocument 객체 생성
            PdfDocument pdf = new PdfDocument();

            // PDF 파일 로드
            pdf.LoadFromFile(inputFile);

            // PDF를 여러 개의 한 페이지 PDF로 분할
            pdf.Split(outputDirectory + "output-{0}.pdf", 1);
        }
    }
}

Split() 메서드를 호출하여 입력 PDF 문서(10페이지 포함)를 10개의 개별 파일로 분할할 수 있습니다.

PDF 페이지를 여러 PDF 파일로 분할합니다.

페이지 범위별로 PDF를 여러 파일로 분할

큰 PDF를 각각 지정된 수의 페이지를 포함하는 여러 개의 작은 PDF로 분할하려는 경우 두 개 이상의 새 PDF 문서를 만든 다음 원본 PDF에서 페이지 또는 페이지 범위를 가져올 수 있습니다.

C#에서 페이지별로 PDF 파일을 분할하는 일반적인 단계는 다음과 같습니다.

  • 원본 PDF를 로드합니다.
  • 분할된 페이지를 담을 두 개의 빈 PDF를 만듭니다.
  • PDF 페이지 분할:
    • InsertPage() 메서드를 사용하여 원본 PDF에서 지정된 페이지를 첫 번째 새 PDF로 가져옵니다.
    • InsertPageRange() 메서드를 사용하여 원본 PDF에서 페이지 범위를 두 번째 새 PDF로 가져옵니다.
  • 두 개의 새 PDF를 모두 출력 디렉토리에 저장합니다.

C# 샘플 코드:

using Spire.Pdf;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            // 입력 파일 경로 지정
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // 출력 디렉토리 지정
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // PdfDocument 객체를 초기화하면서 원본 PDF 파일 로드
            PdfDocument sourcePdf = new PdfDocument(inputFile);

            // 두 개의 새 PDF 문서 생성
            PdfDocument pdf1 = new PdfDocument();
            PdfDocument pdf2 = new PdfDocument();

            // 원본 PDF의 첫 페이지를 첫 번째 문서에 삽입
            pdf1.InsertPage(sourcePdf, 0);

            // 원본 PDF의 나머지 페이지를 두 번째 문서에 삽입
            pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);

            // 두 PDF 문서 저장
            pdf1.SaveToFile(outputDirectory + "output-1.pdf");
            pdf2.SaveToFile(outputDirectory + "output-2.pdf");
        }
    }
}

이 코드를 실행하여 입력 PDF의 1페이지와 2-10페이지를 2개의 별도 PDF 파일로 추출할 수 있습니다.

사용자 지정 페이지 범위로 PDF 파일 분할.


PDF 분할을 위한 고급 팁

  • 동적 페이지 범위: 여러 범위(예: 1-3페이지, 5-7페이지)로 분할하려면 추가 PdfDocument 객체를 만들고 InsertPageRange() 메서드의 페이지 삽입 인덱스를 조정하십시오.

  • 파일 이름 지정 규칙: Split() 메서드의 destFilePattern 매개변수를 통해 출력 파일의 이름을 지정할 때 설명적인 패턴을 사용하여 파일을 더 잘 정리하십시오(예: report_part-{0}.pdf).

  • 오류 처리: 파일 작업 중 예외를 처리하기 위해 try-catch 블록을 추가하십시오.

try
{
    /* PDF 분할 코드 */
}
catch (Exception ex)
{
    Console.WriteLine("오류: " + ex.Message);
}

자주 묻는 질문 (VB.NET 데모)

Q1: 출력 파일에서 워터마크를 어떻게 제거하나요?

A: 여기에서 평가판 라이선스를 요청하여(30일 유효) 워터마크와 제한 사항을 제거할 수 있습니다. 또는 무료 커뮤니티 에디션을 사용해 볼 수 있습니다.

Q2: 분할 시 하이퍼링크/양식 필드가 보존되나요?

A:

요소 보존 여부?
하이퍼링크 ✅ 예
양식 필드 ✅ 예
주석 ✅ 예
디지털 서명 ❌ 아니요 (전체 문서 컨텍스트 필요)

Q3: 단일 PDF 페이지를 여러 페이지/파일로 분할할 수 있나요?

A: 예. Spire.PDF는 또한 PDF 페이지를 가로 또는 세로로 두 개 이상의 페이지로 분할하는 것을 지원합니다. 튜토리얼: C#에서 PDF 페이지를 여러 페이지로 분할하기

Q4: PDF 파일 분할을 위한 VB.NET 데모가 있나요?

A: 네이티브 .NET 라이브러리인 Spire.PDF는 C#과 VB.NET에서 동일하게 작동합니다. 따라서 일부 코드 변환 도구(예: Telerik Code Converter)를 사용하여 C# 샘플을 VB.NET으로 즉시 변환할 수 있습니다.


결론

Spire.PDF는 직관적인 방법으로 C#에서 PDF 분할을 단순화합니다. 기본 페이지별 분할이 필요하든 페이지 범위에 기반한 고급 분할이 필요하든 라이브러리는 필요한 기능을 제공합니다. 이 가이드를 따르면 C# 또는 VB.NET 애플리케이션에서 PDF 분할을 효율적으로 구현하여 생산성과 문서 관리를 향상시킬 수 있습니다.

도움 받을 곳

프로 팁: Spire.PDF의 변환 기능과 분할을 결합하여 페이지를 이미지나 다른 파일 형식으로 추출하십시오.

Nel mondo dello sviluppo software e della gestione dei documenti, sapere come dividere un PDF in C# è una competenza fondamentale per gli sviluppatori .NET. Che tu abbia bisogno di separare grandi report in parti più piccole, estrarre pagine specifiche per la distribuzione o organizzare i contenuti in modo più efficiente, dividere i file PDF a livello di codice può farti risparmiare una notevole quantità di tempo e fatica.

Guida visiva per dividere file PDF in C#

Questa guida esplora come dividere file PDF in C# utilizzando la libreria Spire.PDF for .NET — una soluzione di elaborazione PDF robusta e priva di dipendenze.

Introduzione a Spire.PDF for .NET

Spire.PDF è una libreria .NET ricca di funzionalità che offre:

  • Funzionalità complete di manipolazione dei PDF
  • Nessuna dipendenza da Adobe Acrobat
  • Supporto per .NET Framework, .NET Core, .NET 5+, MonoAndroid e Xamarin.iOS

Prima di poter iniziare a dividere un PDF in più file nelle applicazioni C#, è necessario installare la libreria tramite NuGet Package Manager.

  1. Apri il tuo progetto C# in Visual Studio.
  2. Fai clic con il pulsante destro del mouse sul progetto in Esplora soluzioni e seleziona "Gestisci pacchetti NuGet".
  3. Nella finestra di Gestione pacchetti NuGet, cerca "Spire.PDF".
  4. Seleziona la versione appropriata della libreria e fai clic su "Installa". NuGet scaricherà e aggiungerà i riferimenti necessari al tuo progetto.

Metodo alternativo: scarica manualmente la DLL dal sito web ufficiale di Spire.PDF e fai riferimento ad essa nel tuo progetto.

Dividere un documento PDF in C# - Esempi di codice

Ora che la libreria è configurata nel tuo progetto, vediamo come dividere un PDF in .NET. Esistono diversi scenari per la divisione di un PDF, come dividerlo in singole pagine o in più PDF in base a un numero specifico di pagine. Tratteremo entrambi i casi comuni.

Dividere un PDF in singole pagine

Di seguito è riportato l'esempio di codice C# per dividere un documento PDF in file PDF singoli, ciascuno contenente una singola pagina del documento originale:

using Spire.Pdf;

namespace SplitPDFIntoMultipleFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            // Specifica il percorso del file di input
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Specifica la directory di output
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Crea un oggetto PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Carica un file PDF
            pdf.LoadFromFile(inputFile);

            // Dividi il PDF in più PDF di una pagina
            pdf.Split(outputDirectory + "output-{0}.pdf", 1);
        }
    }
}

Chiamando il metodo Split(), puoi dividere il documento PDF di input (contenente 10 pagine) in 10 file singoli.

Dividere le pagine di un PDF in più file PDF.

Dividere un PDF in più file per intervalli di pagine

Supponiamo di voler dividere un PDF di grandi dimensioni in più PDF più piccoli, ciascuno contenente un numero specificato di pagine. Puoi creare due o più nuovi documenti PDF e quindi importare la pagina o l'intervallo di pagine dal PDF di origine in essi.

Ecco i passaggi generali per dividere un file PDF per pagine in C#:

  • Carica il PDF di origine.
  • Crea due PDF vuoti per contenere le pagine divise.
  • Dividi pagine PDF:
    • Usa il metodo InsertPage() per importare una pagina specifica dal PDF di origine al primo nuovo PDF.
    • Usa il metodo InsertPageRange() per importare un intervallo di pagine dal PDF di origine al secondo nuovo PDF.
  • Salva entrambi i nuovi PDF nella directory di output.

Codice di esempio in C#:

using Spire.Pdf;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            // Specifica il percorso del file di input
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Specifica la directory di output
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Carica il file PDF di origine durante l'inizializzazione dell'oggetto PdfDocument
            PdfDocument sourcePdf = new PdfDocument(inputFile);

            // Crea due nuovi documenti PDF
            PdfDocument pdf1 = new PdfDocument();
            PdfDocument pdf2 = new PdfDocument();

            // Inserisci la prima pagina del PDF di origine nel primo documento
            pdf1.InsertPage(sourcePdf, 0);

            // Inserisci le pagine rimanenti del PDF di origine nel secondo documento
            pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);

            // Salva i due documenti PDF
            pdf1.SaveToFile(outputDirectory + "output-1.pdf");
            pdf2.SaveToFile(outputDirectory + "output-2.pdf");
        }
    }
}

Eseguendo questo codice, puoi estrarre la pagina 1 e le pagine 2-10 del PDF di input in 2 file PDF separati.

Dividere un file PDF per intervalli di pagine personalizzati.


Consigli avanzati per la divisione di PDF

  • Intervalli di pagine dinamici: per dividere in più intervalli (ad es. pagine 1-3, 5-7), crea oggetti PdfDocument aggiuntivi e regola l'indice di inserimento delle pagine del metodo InsertPageRange().

  • Convenzioni di denominazione dei file: usa modelli descrittivi quando nomini i file di output tramite il parametro destFilePattern del metodo Split() per organizzare meglio i file (ad es. report_part-{0}.pdf).

  • Gestione degli errori: aggiungi blocchi try-catch per gestire le eccezioni durante le operazioni sui file.

try
{
    /* Codice di divisione PDF */
}
catch (Exception ex)
{
    Console.WriteLine("Errore: " + ex.Message);
}

FAQ (demo in VB.NET)

Q1: Come rimuovo le filigrane nel file di output?

R: Puoi richiedere una licenza di prova qui (valida per 30 giorni) per rimuovere le filigrane e le limitazioni. Oppure puoi provare l'edizione Community gratuita.

Q2: La divisione preserva i collegamenti ipertestuali/i campi modulo?

R:

Elementi Conservato?
Collegamenti ipertestuali ✅ Sì
Campi modulo ✅ Sì
Annotazioni ✅ Sì
Firme digitali ❌ No (richiede il contesto completo del documento)

Q3: Posso dividere una singola pagina PDF in più pagine/file?

R: Sì. Spire.PDF supporta anche la divisione orizzontale o verticale di una pagina PDF in due o più pagine. Tutorial: Dividere una pagina PDF in più pagine in C#

Q4: Esiste una demo in VB.NET per la divisione di file PDF?

R: Essendo una libreria .NET nativa, Spire.PDF funziona in modo identico sia in C# che in VB.NET. Pertanto, è possibile utilizzare uno strumento di conversione del codice (ad es. Telerik Code Converter) per tradurre istantaneamente gli esempi da C# a VB.NET.


Conclusione

Spire.PDF semplifica la divisione dei PDF in C# con metodi intuitivi. Sia che tu abbia bisogno di una divisione di base pagina per pagina o di una divisione più avanzata basata su intervalli di pagine, la libreria fornisce la funzionalità necessaria. Seguendo questa guida, puoi implementare in modo efficiente la divisione di PDF nelle tue applicazioni C# o VB.NET, migliorando la produttività e la gestione dei documenti.

Dove trovare aiuto

Consiglio da professionista: combina la divisione con le funzionalità di conversione di Spire.PDF per estrarre le pagine come immagini o altri formati di file.

Dans le monde du développement de logiciels et de la gestion de documents, savoir comment diviser un PDF en C# est une compétence fondamentale pour les développeurs .NET. Que vous ayez besoin de séparer de grands rapports en parties plus petites, d'extraire des pages spécifiques pour la distribution ou d'organiser le contenu plus efficacement, la division de fichiers PDF par programmation peut faire gagner un temps et des efforts considérables.

Guide visuel pour diviser des fichiers PDF en C#

Ce guide explore comment diviser des fichiers PDF en C# à l'aide de la bibliothèque Spire.PDF for .NET — une solution de traitement de PDF robuste et sans dépendances.

Présentation de Spire.PDF for .NET

Spire.PDF est une bibliothèque .NET riche en fonctionnalités offrant :

  • Des capacités complètes de manipulation de PDF
  • Aucune dépendance à Adobe Acrobat
  • Prise en charge de .NET Framework, .NET Core, .NET 5+, MonoAndroid et Xamarin.iOS

Avant de pouvoir commencer à diviser un PDF en plusieurs fichiers dans des applications C#, il est nécessaire d'installer la bibliothèque via le gestionnaire de paquets NuGet.

  1. Ouvrez votre projet C# dans Visual Studio.
  2. Faites un clic droit sur le projet dans l'Explorateur de solutions et sélectionnez « Gérer les paquets NuGet ».
  3. Dans la fenêtre du gestionnaire de paquets NuGet, recherchez « Spire.PDF ».
  4. Sélectionnez la version appropriée de la bibliothèque et cliquez sur « Installer ». NuGet téléchargera et ajoutera les références nécessaires à votre projet.

Méthode alternative : Téléchargez manuellement la DLL depuis le site officiel de Spire.PDF et référencez-la dans votre projet.

Diviser un document PDF en C# - Exemples de code

Maintenant que la bibliothèque est configurée dans votre projet, voyons comment diviser un PDF en .NET. Il existe différents scénarios pour diviser un PDF, comme le diviser en pages individuelles ou le diviser en plusieurs PDF en fonction d'un nombre spécifique de pages. Nous couvrirons les deux cas courants.

Diviser un PDF en pages individuelles

Voici l'exemple de code C# pour diviser un document PDF en fichiers PDF individuels, chacun contenant une seule page du document original :

using Spire.Pdf;

namespace SplitPDFIntoMultipleFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            // Spécifier le chemin du fichier d'entrée
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Spécifier le répertoire de sortie
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Créer un objet PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Charger un fichier PDF
            pdf.LoadFromFile(inputFile);

            // Diviser le PDF en plusieurs PDF d'une seule page
            pdf.Split(outputDirectory + "output-{0}.pdf", 1);
        }
    }
}

En appelant la méthode Split(), vous pouvez diviser le document PDF d'entrée (contenant 10 pages) en 10 fichiers individuels.

Diviser les pages d'un PDF en plusieurs fichiers PDF.

Diviser un PDF en plusieurs fichiers par plages de pages

Supposons que vous souhaitiez diviser un grand PDF en plusieurs PDF plus petits, chacun contenant un nombre spécifié de pages. Vous pouvez créer deux ou plusieurs nouveaux documents PDF, puis y importer la page ou la plage de pages du PDF source.

Voici les étapes générales pour diviser un fichier PDF par pages en C# :

  • Chargez le PDF source.
  • Créez deux PDF vides pour contenir les pages divisées.
  • Diviser les pages du PDF :
    • Utilisez la méthode InsertPage() pour importer une page spécifique du PDF source dans le premier nouveau PDF.
    • Utilisez la méthode InsertPageRange() pour importer une plage de pages du PDF source dans le deuxième nouveau PDF.
  • Enregistrez les deux nouveaux PDF dans le répertoire de sortie.

Exemple de code C# :

using Spire.Pdf;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            // Spécifier le chemin du fichier d'entrée
            string inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            // Spécifier le répertoire de sortie
            string outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // Charger le fichier PDF source en initialisant l'objet PdfDocument
            PdfDocument sourcePdf = new PdfDocument(inputFile);

            // Créer deux nouveaux documents PDF
            PdfDocument pdf1 = new PdfDocument();
            PdfDocument pdf2 = new PdfDocument();

            // Insérer la première page du PDF source dans le premier document
            pdf1.InsertPage(sourcePdf, 0);

            // Insérer les pages restantes du PDF source dans le deuxième document
            pdf2.InsertPageRange(sourcePdf, 1, sourcePdf.Pages.Count - 1);

            // Enregistrer les deux documents PDF
            pdf1.SaveToFile(outputDirectory + "output-1.pdf");
            pdf2.SaveToFile(outputDirectory + "output-2.pdf");
        }
    }
}

En exécutant ce code, vous pouvez extraire la page 1 et les pages 2 à 10 du PDF d'entrée dans 2 fichiers PDF distincts.

Diviser un fichier PDF par plages de pages personnalisées.


Conseils avancés pour la division de PDF

  • Plages de pages dynamiques : pour diviser en plusieurs plages (par exemple, pages 1-3, 5-7), créez des objets PdfDocument supplémentaires et ajustez l'index d'insertion des pages de la méthode InsertPageRange().

  • Conventions de nommage des fichiers : utilisez des modèles descriptifs lors du nommage des fichiers de sortie via le paramètre destFilePattern de la méthode Split() pour mieux organiser les fichiers (par exemple, report_part-{0}.pdf).

  • Gestion des erreurs : ajoutez des blocs try-catch pour gérer les exceptions pendant les opérations sur les fichiers.

try
{
    /* Code de division de PDF */
}
catch (Exception ex)
{
    Console.WriteLine("Erreur : " + ex.Message);
}

FAQ (démos en VB.NET)

Q1 : Comment supprimer les filigranes dans le fichier de sortie ?

R : Vous pouvez demander une licence d'essai ici (valable 30 jours) pour supprimer les filigranes et les limitations. Ou vous pouvez essayer l'édition Community gratuite.

Q2 : La division préserve-t-elle les hyperliens/champs de formulaire ?

R :

Éléments Préservé ?
Hyperliens ✅ Oui
Champs de formulaire ✅ Oui
Annotations ✅ Oui
Signatures numériques ❌ Non (nécessite le contexte complet du document)

Q3 : Puis-je diviser une seule page PDF en plusieurs pages/fichiers ?

R : Oui. Spire.PDF prend également en charge la division horizontale ou verticale d'une page PDF en deux ou plusieurs pages. Tutoriel : Diviser une page PDF en plusieurs pages en C#

Q4 : Existe-t-il une démo VB.NET pour la division de fichiers PDF ?

R : En tant que bibliothèque .NET native, Spire.PDF fonctionne de manière identique en C# et en VB.NET. Par conséquent, vous pouvez utiliser un outil de conversion de code (par exemple, Telerik Code Converter) pour traduire instantanément les exemples C# en VB.NET.


Conclusion

Spire.PDF simplifie la division des PDF en C# avec des méthodes intuitives. Que vous ayez besoin d'une division de base page par page ou d'une division plus avancée basée sur des plages de pages, la bibliothèque fournit les fonctionnalités nécessaires. En suivant ce guide, vous pouvez mettre en œuvre efficacement la division de PDF dans vos applications C# ou VB.NET, améliorant ainsi la productivité et la gestion des documents.

Où obtenir de l'aide

Conseil de pro : combinez la division avec les fonctionnalités de conversion de Spire.PDF pour extraire des pages sous forme d'images ou d'autres formats de fichiers.