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}");
}
}
iTextSharp 库来处理 PDF 文件。需要通过 NuGet 安装 iTextSharp 包。Document 类创建一个 A4 大小的文档。PdfWriter.GetInstance 方法将文档内容写入指定的文件路径。document.Open() 方法使文档可以编辑。document.AddAuthor 和 document.AddTitle 方法为 PDF 添加作者和标题信息。Paragraph 对象并将其添加到文档中。try-catch 块中处理可能发生的异常。GeneratePdf 方法生成 PDF 文件。这段代码展示了如何使用 C# 和 iTextSharp 生成一个简单的 PDF 文件。
上一篇:c# 正则
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站