Inserting Text into Existing PDFs with iTextSharp: A Technical Guide

Dec 04, 2025 · Programming · 7 views · 7.8

Keywords: C# | ASP.NET | PDF | iTextSharp | PDF Generation

Abstract: This guide provides a comprehensive method for adding text to existing PDF files using iTextSharp in C# and ASP.NET environments, without relying on PDF forms. It distills core concepts, including reading PDFs, creating new documents, adding text content, and handling multi-page scenarios, with rewritten code examples and step-by-step explanations.

Introduction

PDF manipulation is a common requirement in software development, and iTextSharp is a popular library on the .NET platform for this purpose. This article focuses on inserting text into existing PDF files without using PDF forms, by analyzing core concepts, reorganizing logical structures, and ensuring the method is both comprehensive and easy to understand.

Technical Background

The iTextSharp library includes key classes such as PdfReader for reading existing PDFs, Document and PdfWriter for creating new PDF documents, and PdfContentByte for manipulating PDF content. By combining these classes, fine-grained control over PDFs can be achieved, such as adding text, setting fonts, and positioning.

Method Details

The basic steps for inserting text into an existing PDF are as follows: first, open the original PDF file using PdfReader to obtain page dimensions; then create a new Document instance, associated with PdfWriter to write to a new file; next, add text content via PdfContentByte, setting font, color, and coordinates; finally, import the original page to preserve existing content, and close all resource streams.

Code Implementation

Based on core concepts, a rewritten code example is provided below, demonstrating how to add text to the first page of a PDF:

string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";

// Open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);

// Open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();

// PDF content manipulation
PdfContentByte cb = writer.DirectContent;

// Set font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);

// Write text
cb.BeginText();
string text = "Some random text...";
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();

// Import original page
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);

// Close resources
document.Close();
fs.Close();
writer.Close();
reader.Close();

In this code, the ShowTextAligned method is used to align text at specified coordinates, with parameter 1 indicating alignment, and 520 and 640 as x and y coordinates.

Multi-Page Handling

For multi-page PDFs, text can be added by iterating through all pages. A supplementary example is provided below, showing how to add text to each page:

using (var reader = new PdfReader("Input.pdf"))
{
    using (var fileStream = new FileStream("Output.pdf", FileMode.Create, FileAccess.Write))
    {
        var document = new Document(reader.GetPageSizeWithRotation(1));
        var writer = PdfWriter.GetInstance(document, fileStream);
        document.Open();

        for (var i = 1; i <= reader.NumberOfPages; i++)
        {
            document.NewPage();
            var importedPage = writer.GetImportedPage(reader, i);
            var contentByte = writer.DirectContent;
            contentByte.BeginText();
            BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            contentByte.SetFontAndSize(baseFont, 12);
            string multiLineText = "Hello,\r\nWorld!";
            var lines = multiLineText.Split('\n');
            foreach (var line in lines)
            {
                contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
            }
            contentByte.EndText();
            contentByte.AddTemplate(importedPage, 0, 0);
        }

        document.Close();
        writer.Close();
    }
}

This approach ensures text is added to each page while preserving original content, suitable for handling complex documents.

Conclusion

Using iTextSharp to insert text into existing PDFs is an efficient and flexible method. By leveraging classes like PdfReader, Document, and PdfContentByte, it avoids the need for PDF forms and adapts to various application scenarios. The code examples and explanations provided aim to help developers get started quickly and encourage further exploration of iTextSharp's advanced features.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.