Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 生成pdf

作者:缺爱╮不缺钙   发布日期:2026-04-06   浏览:105

using System;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

public class PdfGenerator
{
    public static void GeneratePdf(string outputPath)
    {
        // 创建一个文档对象
        Document document = new Document(PageSize.A4);

        try
        {
            // 创建一个PdfWriter实例,将文档写入指定的文件路径
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputPath, FileMode.Create));

            // 打开文档以供编辑
            document.Open();

            // 添加元数据
            document.AddAuthor("Author Name");
            document.AddTitle("PDF Title");

            // 添加段落
            Paragraph paragraph = new Paragraph("Hello, this is a PDF generated using C# and iTextSharp.");
            document.Add(paragraph);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
        finally
        {
            // 关闭文档
            if (document.IsOpen())
            {
                document.Close();
            }
        }
    }

    public static void Main(string[] args)
    {
        string outputPath = "output.pdf";
        GeneratePdf(outputPath);
        Console.WriteLine($"PDF has been generated at: {outputPath}");
    }
}

解释说明:

  1. 引入命名空间:使用 iTextSharp 库来处理 PDF 文件。需要通过 NuGet 安装 iTextSharp 包。
  2. 创建文档对象:使用 Document 类创建一个 A4 大小的文档。
  3. 创建 PdfWriter 实例:通过 PdfWriter.GetInstance 方法将文档内容写入指定的文件路径。
  4. 打开文档:调用 document.Open() 方法使文档可以编辑。
  5. 添加元数据:使用 document.AddAuthordocument.AddTitle 方法为 PDF 添加作者和标题信息。
  6. 添加段落:创建一个 Paragraph 对象并将其添加到文档中。
  7. 异常处理:在 try-catch 块中处理可能发生的异常。
  8. 关闭文档:确保文档在操作完成后关闭。
  9. 主方法:定义输出路径并调用 GeneratePdf 方法生成 PDF 文件。

这段代码展示了如何使用 C# 和 iTextSharp 生成一个简单的 PDF 文件。

上一篇:c# 正则

下一篇:c# savefiledialog

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站