如何用iTextSharp(C#)为PDF添加内容及解决ItemTemplate转PDF问题
Got it, let's break down how to add content like body text and headers to a PDF using iTextSharp in C#—I’ve tackled this exact scenario before, so I’ll share practical, runnable examples to make it clear.
Whether you're starting from a blank PDF or adding to an existing one, iTextSharp makes inserting paragraphs, tables, or custom elements simple. Here’s a step-by-step example for a new document:
First, make sure you’ve installed the iTextSharp NuGet package (you can do this via the Package Manager Console with Install-Package iTextSharp). Then use these core classes:
using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; public void CreatePdfWithBodyContent(string outputPath) { // Initialize a new document with standard A4 page size and custom margins using (var document = new Document(PageSize.A4, 50, 50, 70, 70)) { // Bind the document to a file writer PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create)); // Open the document to start adding content document.Open(); // Add a title paragraph with bold font var titleFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16); document.Add(new Paragraph("My Sample Document", titleFont)); // Add a blank line for spacing document.Add(new Paragraph("")); // Add body text with regular font and adjusted line spacing var bodyFont = FontFactory.GetFont(FontFactory.HELVETICA, 12); var bodyParagraph = new Paragraph( "This is the main body content of the PDF. You can add multiple paragraphs, adjust line spacing, or even include bullet points using List and ListItem classes. For longer content, iTextSharp will automatically wrap text to fit the page margins.", bodyFont ); bodyParagraph.SpacingAfter = 10; // Add space after this paragraph document.Add(bodyParagraph); // Add a table for structured data var table = new PdfPTable(3); // 3 columns table.WidthPercentage = 100; // Take full page width table.SpacingBefore = 15; // Add space before the table // Add table headers with bold font table.AddCell(new Phrase("Product ID", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10))); table.AddCell(new Phrase("Product Name", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10))); table.AddCell(new Phrase("Price", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10))); // Add table rows table.AddCell("P001"); table.AddCell("Wireless Headphones"); table.AddCell("$99.99"); table.AddCell("P002"); table.AddCell("Bluetooth Speaker"); table.AddCell("$49.99"); document.Add(table); // Close the document to finalize document.Close(); } }
Key notes here:
- Adjust the document margins (the 50,50,70,70 values) to reserve space for headers/footers later.
- Use
FontFactoryto access standard fonts, or load custom fonts withBaseFont.CreateFont()if you need brand-specific typography. PdfPTableis ideal for structured data—you can set individual column widths, cell padding, and borders with just a few lines of code.
Headers (and footers) are best handled using iTextSharp's PdfPageEventHelper, since they need to appear on every page automatically. You’ll create a custom event class that overrides the OnEndPage method to draw the header content.
Here’s how to do it:
// Custom event class for headers/footers public class HeaderFooterEvent : PdfPageEventHelper { private string _documentTitle; public HeaderFooterEvent(string documentTitle) { _documentTitle = documentTitle; } public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); // Create a PdfContentByte to draw the header elements var content = writer.DirectContent; // Draw a thin horizontal line to separate the header from body content content.SetLineWidth(0.5f); content.MoveTo(document.LeftMargin, document.Top + 10); content.LineTo(document.PageSize.Width - document.RightMargin, document.Top + 10); content.Stroke(); // Add left-aligned document title to the header var headerFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12); var titlePhrase = new Phrase(_documentTitle, headerFont); ColumnText.ShowTextAligned(content, Element.ALIGN_LEFT, titlePhrase, document.LeftMargin, document.Top + 15, 0); // Add right-aligned page number to the header var pageNumberPhrase = new Phrase($"Page {writer.PageNumber}", FontFactory.GetFont(FontFactory.HELVETICA, 10)); ColumnText.ShowTextAligned(content, Element.ALIGN_RIGHT, pageNumberPhrase, document.PageSize.Width - document.RightMargin, document.Top + 15, 0); } } // Integrate the header event into your PDF creation workflow public void CreatePdfWithHeader(string outputPath) { using (var document = new Document(PageSize.A4, 50, 50, 70, 70)) { var writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create)); // Attach the custom header/footer event to the writer writer.PageEvent = new HeaderFooterEvent("My Document with Custom Header"); document.Open(); // Add your body content here (reuse the paragraph/table code from the first example) document.Add(new Paragraph("This page has a persistent header with the document title and page number. Scroll through multiple pages to see it auto-appear.", FontFactory.GetFont(FontFactory.HELVETICA, 12))); // Add multiple pages to test the header consistency for (int i = 0; i < 4; i++) { document.Add(new Paragraph($"Content for page {i+2}...", FontFactory.GetFont(FontFactory.HELVETICA, 12))); document.NewPage(); } document.Close(); } }
Key points for headers:
- The
OnEndPagemethod triggers after each page is rendered, so your header will show up on every page without manual repetition. - Use
ColumnText.ShowTextAlignedto position text precisely—tweak the X/Y coordinates to move the header up/down or left/right as needed. - To add a logo to the header, load the image with
Image.GetInstance("path/to/logo.png"), set its position withimage.SetAbsolutePosition(x, y), then add it to theDirectContentobject.
If you’re working with an existing PDF (like your earlier ItemTemplate scenario), you can use PdfReader and PdfStamper to inject headers or additional body content into the existing document—just let me know if you want a walkthrough for that!
内容的提问来源于stack exchange,提问作者Donavan Er




