! Baza wiedzy iText W naszym poprzednim poście rozmawialiśmy o ITEXTPDF API do pracy z plikami PDF przy użyciu aplikacji C#/vb.net w aplikacjach .NET. API pozwala tworzyć, edytować i manipulować dokumentami PDF bez przechodzenia do żadnych wewnętrznych szczegółów formatu pliku pliku PDF. Korzystanie z ITEXTPDF jest łatwe w obsłudze, z zaledwie kilkoma wierszami kodu, możesz zacząć tworzyć, czytać i manipulować pliki PDF. W tym artykule porozmawiamy o użyciu ITEXTPDF w aplikacji .NET do tworzenia, odczytu i zapisywania plików PDF programowo w naszej aplikacji C#. Zacznijmy więc i spójrzmy, jak możemy stworzyć plik PDF w C#.

ITEXTPDF Instalacja

Możesz zainstalować interfejs API ITEXTPDF z Nuget lub z iText Artefactory Server . Zanim utworzysz aplikację C# do korzystania z interfejsu API ITEXTPDF, musisz zainstalować ją z jednego z tych źródeł. Możesz zapoznać się z instrukcją instrukcji instalacji interfejsu API ITEXTPDF w celu skonfigurowania aplikacji konsoli do tego celu.

Przegląd głównych klas API ITEXTPDF

Niektóre z głównych klas ITEXTPDF są następujące.

pdfDocument

Każdy dokument PDF utworzony z ITEXTPDF jest inicjowany przy użyciu obiektu klasy PDFDOCUME.

pdfwriter

Klasa PDFWriter jest odpowiedzialna za zapisanie zawartości PDF do miejsca docelowego, takiej jak plik lub strumień. Zapewnia funkcjonalność tworzenia dokumentu PDF i określenia miejsca docelowego wyjściowego. Niektóre kluczowe funkcje i obowiązki klasy PDFWriter są następujące.

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.

akapit

Klasa akapitowa reprezentuje akapit tekstu w dokumencie PDF. Służy do dodawania treści tekstowych do dokumentu PDF. Oto kilka kluczowych funkcji i obowiązków klasy akapitowej:

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.

Jak utworzyć plik PDF w C#?

Teraz, gdy mamy dobry pomysł na temat ITEXTPDF i jego głównych klas, kontynuujmy tworzenie dokumentu PDF w C# za pomocą interfejsu API ITEXTPDF. Można to zrobić tylko z kilkoma krokami jak poniżej.

  1. Utwórz nowy projekt w Visual Studio.
  2. Zainstaluj bibliotekę ITEXTPDF C# za pomocą Menedżera pakietów Nuget.
  3. Utwórz instancje klas PDFDocument i PDFWriter
  4. Utwórz instancje klas dokumentów i akapitu
  5. Zamknij dokument za pomocą metody Document.close ()

C# fragment kodowy do generowania pliku pdf

Do generowania pliku PDF można użyć następującego C# .

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.");
    }
}

Jak zaktualizować plik PDF w C#?

Aktualizacja/edycja pliku PDF w C# można łatwo wykonać za pomocą ITEXTPDF.

  1. Otwórz istniejący dokument PDF za pomocą obiektu pdfreader .
  2. Utwórz obiekt PDFWriter z nowym lub zmodyfikowanym miejscem docelowym wyjściowym (takim jak plik lub strumień).
  3. Utwórz obiekt PdfDocument za pomocą obiektów pdfreader i pdfwriter .
  4. Uzyskaj dostęp do istniejących stron i treści dokumentu za pomocą instancji PDFDOCUME.
  5. Dokonaj niezbędnych modyfikacji dokumentu, takich jak dodawanie lub usuwanie treści, aktualizacja tekstu, modyfikowanie adnotacji itp.
  6. Zamknij pdfDocument , który automatycznie zamyka powiązany PDFREADER i PDFWriter i zapisuje zmiany w miejscu wyjściowym.

C# fragment kodowy do aktualizacji pliku pdf

Do aktualizacji pliku PDF można użyć następującego C# .

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.");
    }
}

Wniosek

W tym artykule zbadaliśmy interfejs API ITEXTPDF dla .NET, aby dowiedzieć się o tworzeniu i manipulowaniu plikami PDF z naszej aplikacji .NET. API jest open source i jest hostowany na repozytorium GitHub jako iText-Dotnet. Na naszych nadchodzących blogach zbadamy ten interfejs API do pracy z różnymi komponentami dokumentu PDF, takimi jak tabele, obrazy, adnotacje, zredagowany pdf i wiele innych. Bądźcie na bieżąco.