! База знаний ITEXT В нашем предыдущем посте мы говорили о ITEXTPDF API для работы с файлами PDF с использованием C#/VB.NET в приложениях .NET. API позволяет создавать, редактировать и манипулировать PDF -документами, не входя в какую -либо внутренний формат файла формата файла PDF. Использование ITEXTPDF легко работать с несколькими строками кода, вы можете начать создавать, читать и манипулировать PDF -файлами. В этой статье мы поговорим об использовании ITEXTPDF в приложении .NET для программного процесса для создания, чтения и сохранения PDF -файлов в нашем приложении C#. Итак, давайте начнем и посмотрим, как мы можем создать PDF в C#.

itextpdf установка {.wp-block heading}

Вы можете установить API ITEXTPDF из NUGET или из Artifactory Server ITEXT**. Прежде чем вы сможете создать свое приложение C# для использования API ITEXTPDF, вам необходимо установить его из любого из этих источников. Вы можете обратиться к статье инструкции для установки API ITEXTPDF для настройки приложения консоли для этой цели.

Обзор основных классов API itextpdf {.wp-block heading}

Некоторые из основных классов ITEXTPDF заключаются в следующем.

pdfdocument {.wp-block heading}

Каждый PDF -документ, созданный с помощью ITEXTPDF, инициируется с использованием объекта класса PDFDOCUMENT.

pdfwriter {.wp-block heading}

Класс PDFWriter отвечает за написание контента PDF в пункт назначения, например, файл или поток. Он предоставляет функциональность для создания документа PDF и указать место для вывода. Некоторые ключевые функции и обязанности класса PDFWriter заключаются в следующем.

Destination ConfigurationThe PdfWriter constructor allows you to specify the output destination for the PDF content. It can accept parameters like a file path, a Stream object, or an instance of IOutputStreamCounter. This determines where the PDF content will be written.
PDF Document CreationWhen you create a new instance of PdfWriter, it automatically creates a new PdfDocument object associated with it. The PdfDocument represents the logical structure of a PDF file and provides methods to manipulate its content.
PDF Compression and Version ControlThe PdfWriter class allows you to configure various aspects of the PDF file, such as compression settings and PDF version compatibility.
Writing PDF ContentOnce you have a PdfWriter instance, you can use it to write content to the associated PdfDocument. You can add pages, create annotations, add text, images, and other graphical elements to the PDF document using the provided methods.
Closing the WriterAfter you finish writing the PDF content, it’s important to close the PdfWriter to ensure the document is finalized and any necessary resources are released.

пункт

Класс абзац представляет собой абзац текста в документе PDF. Он используется для добавления текстового контента в PDF -документ. Вот некоторые ключевые функции и обязанности класса абзаца:

Text ContentThe primary purpose of the Paragraph class is to hold and display textual content within a PDF document. You can pass a string or any other text representation to the Paragraph constructor to initialize its content.
Text FormattingThe Paragraph class allows you to apply various formatting options to the text, such as font size, font family, text color, bold, italic, underline, and more. You can use methods like SetFontSize(), SetFont(), SetBold(), SetItalic(), SetUnderline(), etc., to specify the desired formatting.
Alignment and IndentationThe Paragraph class provides methods to set the alignment of the text within the paragraph. You can align the text to the left, right, or center, or justify it. Additionally, you can apply indentation to control the left and right margins of the paragraph.
Inline ElementsApart from plain text, you can also add inline elements within a Paragraph. For example, you can include phrases or words with different formatting styles, add hyperlinks, insert images, or include other elements supported by iText.
NestingYou can nest multiple paragraphs within each other or combine them with other iText elements like tables, lists, or chunks to create complex document structures.
Integration with DocumentThe Paragraph instances can be added to the Document object using the Add() method. This allows you to include paragraphs in your PDF document at the desired location.

Как создать файл PDF в C#?

Теперь, когда у нас есть хорошее представление о ITEXTPDF и его основных классах, давайте продолжим создавать документ PDF в C# с помощью API ITEXTPDF. Это можно сделать с помощью всего лишь нескольких шагов, как показано ниже.

  1. Создайте новый проект в Visual Studio.
  2. Установите библиотеку ITEXTPDF C#, используя диспетчер пакетов NUGET.
  3. Создайте экземпляры классов PDFDOCUMENT и PDFWRITER
  4. Создайте экземпляры классов документов и абзацев
  5. Закройте документ, используя метод Document.Close ()

C# код фрагмент для генерации PDF-файла {.wp-block heading}

Следующий код C# может использоваться для генерации файла PDF.

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

class Program
{
    static void Main()
    {
        // Specify the output file path
        string outputPath = "example.pdf";
        // Create a new PDF document
        PdfWriter writer = new PdfWriter(outputPath);
        PdfDocument pdf = new PdfDocument(writer);
        // Create a document instance
        Document document = new Document(pdf);
        // Add content to the document
        document.Add(new Paragraph("Hello, World!"));
        // Close the document
        document.Close();
        Console.WriteLine("PDF created successfully.");
    }
}

Как обновить файл PDF в C#?

Обновление/редактирование файла PDF в C# можно легко сделать с помощью ITEXTPDF.

  1. Откройте существующий документ PDF, используя PDFReader объект.
  2. Создайте PDFWriter объект с новым или измененным пунктом назначения (например, файл или потока).
  3. Создайте pdfdocument объект, используя как pdfreader , так и pdfwriter объекты.
  4. Получите доступ к существующим страницам и содержанию документа, используя экземпляр PDFDocument.
  5. Внесите необходимые изменения в документ, такие как добавление или удаление контента, обновление текста, изменение аннотаций и т. Д.
  6. Закройте pdfdocument , который автоматически закрывает связанный pdfreader и pdfwriter , а также сохраняет изменения в пункте назначения вывода.

C# код фрагмент для обновления PDF-файла {.wp-block heading}

Следующий код C# может использоваться для обновления файла PDF.

using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

class Program
{
    static void Main()
    {
        string filePath = "existing.pdf";
        string outputPath = "updated.pdf";
        // Open the existing PDF document
        PdfReader reader = new PdfReader(filePath);
        // Create a new PDF document with modified output destination
        PdfWriter writer = new PdfWriter(outputPath);
        // Create a PdfDocument object with both the reader and writer
        PdfDocument pdfDoc = new PdfDocument(reader, writer);
        // Access the first page of the document
        PdfPage firstPage = pdfDoc.GetPage(1);
        // Create a document instance for the page
        Document document = new Document(pdfDoc, firstPage);
        // Add a new paragraph to the document
        document.Add(new Paragraph("This is a new paragraph added to the existing PDF."));
        // Close the document, which saves the changes
        document.Close();
        // Close the reader
        reader.Close();
        Console.WriteLine("PDF updated successfully.");
    }
}

Заключение {.wp-block heading}

В этой статье мы исследовали API ITEXTPDF для .NET, чтобы узнать о создании и манипулировании PDF -файлами из нашего приложения .NET. API является открытым исходным кодом и размещен в репозитории GitHub как ITEXT-DOTNET. В наших предстоящих блогах мы дополнительно рассмотрим этот API для работы с различными компонентами документа PDF, такими как таблицы, изображения, аннотации, отредактированный PDF и многие другие. Так что следите за обновлениями.