如何在ASP.NET中使用iTextSharp生成PDF并自定义标题与字体大小
Hey there! Let me walk you through how to create PDFs with iTextSharp in ASP.NET, including customizing heading styles and font settings. I'll break this down into clear, actionable steps with code examples you can copy and adapt.
1. 先搞定iTextSharp安装
First, you need to add the iTextSharp library to your project. The easiest way is via NuGet:
- Open the NuGet Package Manager Console in Visual Studio and run:
Install-Package iTextSharp - Or search for "iTextSharp" in the NuGet Package Manager UI and install it directly
2. 基础PDF生成示例(ASP.NET WebForms)
Here's a straightforward example of generating a PDF and sending it to the browser when a button is clicked:
using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; using System.Web; protected void btnGeneratePdf_Click(object sender, EventArgs e) { // Initialize a Document with A4 page size and margins Document pdfDoc = new Document(PageSize.A4, 50, 50, 25, 25); // Configure response headers to trigger PDF download Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=MyFirstPdf.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); // Link the Document to the response output stream PdfWriter.GetInstance(pdfDoc, Response.OutputStream); // Open the document to start adding content pdfDoc.Open(); // Add a basic paragraph (we'll replace this with custom headings next) pdfDoc.Add(new Paragraph("This is a basic PDF generated with iTextSharp!")); // Clean up and send the PDF to the browser pdfDoc.Close(); Response.End(); }
3. 自定义标题样式与字体设置
To create styled headings, we'll use the Font class from iTextSharp.text to define font size, weight, color, and type, then pair it with Paragraph objects for structure.
3.1 Using Built-in Fonts for Headings
iTextSharp comes with a set of default fonts (Helvetica, Times Roman, etc.) that work out of the box:
// Define a main title font: Helvetica Bold, 24pt, dark gray Font mainTitleFont = new Font(Font.FontFamily.HELVETICA, 24, Font.BOLD, BaseColor.DARK_GRAY); // Create a centered title paragraph with spacing after Paragraph mainTitle = new Paragraph("My Custom PDF Title", mainTitleFont); mainTitle.Alignment = Element.ALIGN_CENTER; mainTitle.SpacingAfter = 15f; // Add space between title and next content // Define a secondary heading: Times Roman Bold-Italic, 18pt, blue Font subTitleFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLDITALIC, BaseColor.BLUE); Paragraph subTitle = new Paragraph("Section 1: Getting Started", subTitleFont); subTitle.SpacingAfter = 10f; // Add headings and body content to the document pdfDoc.Add(mainTitle); pdfDoc.Add(subTitle); pdfDoc.Add(new Paragraph("This is the content under the secondary heading. You can add more paragraphs, lists, or images here!"));
3.2 Using Custom Fonts (e.g., Chinese Fonts)
If you need non-default fonts (like Chinese, Arabic, or custom branded fonts), you'll need to load the font file and embed it in the PDF to ensure it displays correctly on any device:
// Path to your custom font file (store it in a Fonts folder in your project) string fontPath = Server.MapPath("~/Fonts/simfang.ttf"); // Load the font with embedding enabled BaseFont customBaseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); // Define font properties: 16pt, bold, black Font customTitleFont = new Font(customBaseFont, 16, Font.BOLD, BaseColor.BLACK); // Create a Chinese heading with the custom font Paragraph chineseTitle = new Paragraph("中文自定义标题", customTitleFont); chineseTitle.Alignment = Element.ALIGN_CENTER; pdfDoc.Add(chineseTitle);
Pro tip: Make sure to set the font file's "Copy to Output Directory" property to "Copy if newer" so it's included in your deployed project.
4. ASP.NET MVC Implementation
If you're working in an MVC project, you can return the PDF directly from a controller action:
using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; using System.Web.Mvc; public class PdfController : Controller { public FileResult GenerateCustomPdf() { using (MemoryStream ms = new MemoryStream()) { Document pdfDoc = new Document(PageSize.A4, 50, 50, 25, 25); PdfWriter.GetInstance(pdfDoc, ms); pdfDoc.Open(); // Add custom heading Font titleFont = new Font(Font.FontFamily.HELVETICA, 22, Font.BOLD, BaseColor.DARK_GRAY); Paragraph title = new Paragraph("MVC Generated PDF", titleFont); title.Alignment = Element.ALIGN_CENTER; pdfDoc.Add(title); // Add body content pdfDoc.Add(new Paragraph("\nThis PDF was generated directly from an MVC controller action!")); pdfDoc.Close(); return File(ms.ToArray(), "application/pdf", "MvcCustomPdf.pdf"); } } }
内容的提问来源于stack exchange,提问作者Atharv Joshi

