! Itext Connaissance Base Dans notre article précédent, nous avons parlé de API ItextPDF pour travailler avec les fichiers PDF en utilisant C # / VB.NET dans les applications .NET. L’API vous permet de créer, modifier et manipuler les documents PDF sans entrer dans les détails du format de fichier interne du format de fichier PDF. L’utilisation de ITExtPDF est facile à travailler avec et avec seulement quelques lignes de code, vous pouvez commencer à créer, lire et manipuler fichiers PDF. Dans cet article, nous parlerons de l’utilisation de ITEXTPDF dans l’application .NET pour créer, lire et enregistrer des fichiers PDF par programme dans notre application C #. Alors, commençons et examinons comment nous pouvons créer un PDF en C #.

ITEXTPDF Installation

Vous pouvez installer l’API ITEXTPDF à partir de NuGet ou de Itext Arfactory Server . Avant de pouvoir créer votre application C # pour l’utilisation de l’API ITEXTPDF, vous devez l’installer à partir de l’une de ces sources. Vous pouvez vous référer à l’article Instructions pour l’installation de l’API ITEXTPDF pour configurer votre application de console à cet effet.

Présentation des classes API principales de l’ITExtPDF

Certaines des principales classes ITEXTPDF sont les suivantes.

pdfDocument

Chaque document PDF créé avec ITextPDF est initié à l’aide d’un objet de la classe PDFDocument.

pdfwriter

La classe PDFWriter est responsable de l’écriture du contenu PDF vers une destination, comme un fichier ou un flux. Il fournit la fonctionnalité pour créer un document PDF et spécifier la destination de sortie. Certaines fonctionnalités et responsabilités clés de la classe PDFWriter sont les suivantes.

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.

paragraphe

La classe de paragraphe représente un paragraphe de texte dans un document PDF. Il est utilisé pour ajouter du contenu textuel à un document PDF. Voici quelques fonctionnalités et responsabilités clés de la classe de paragraphe:

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.

Comment créer un fichier PDF en C #?

Maintenant que nous avons une bonne idée de ITExtPDF et de ses principales classes, procédons à créer un document PDF en C # à l’aide de l’API ITEXTPDF. Cela peut être fait avec quelques étapes comme ci-dessous.

  1. Créez un nouveau projet dans Visual Studio.
  2. Installez la bibliothèque ITEXTPDF C # à l’aide du gestionnaire de package NuGet.
  3. Créez des instances de classes PDFDocument et PDFWriter
  4. Créez des instances de classes de documents et de paragraphes
  5. Fermez le document à l’aide du document.close () Méthode

C # Code Snippet Pour générer un fichier PDF

Le code C # suivant peut être utilisé pour générer un fichier 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.");
    }
}

Comment mettre à jour un fichier PDF en C #?

Mise à jour / modification d’un fichier PDF dans C # peut facilement être effectué à l’aide de ITEXTPDF.

  1. Ouvrez le document PDF existant à l’aide d’un objet pdfreader .
  2. Créez un objet PDFWriter avec une destination de sortie nouvelle ou modifiée (comme un fichier ou un flux).
  3. Créez un objet PDFDocument à l’aide des objets PDFREADER et PDFWRIRT .
  4. Accédez aux pages existantes et au contenu du document à l’aide de l’instance PDFDocument.
  5. Faire les modifications nécessaires du document, telles que l’ajout ou la suppression du contenu, la mise à jour du texte, la modification des annotations, etc.
  6. Fermez le PDFDocument , qui ferme automatiquement le PDFREADER associé et PDFWriter**également, et enregistre les modifications de la destination de sortie.

C # Code Snippet pour mettre à jour le fichier PDF

Le code C # suivant peut être utilisé pour mettre à jour un fichier 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.");
    }
}

Conclusion

Dans cet article, nous avons exploré l’API ITEXTPDF pour .NET pour en savoir plus sur la création et la manipulation des fichiers PDF à partir de notre application .NET. L’API est open-source et est hébergée sur le référentiel github comme iText-dotnet. Dans nos prochains blogs, nous explorerons davantage cette API pour travailler avec différentes composantes d’un document PDF telles que des tables, des images, des annotations, un PDF expurgé et bien d’autres. Alors restez à l’écoute.