本操作指南解释了如何在 C#** 中**创建 PDF。您可以 **从 C# 生成 PDF **,按照下面给出的简单步骤,在任何基于 .NET 的应用程序的几个 API 调用中进行操作。
在 C# 中创建 PDF 的步骤
- 使用 NuGet 包管理器安装 Aspose.PDF for .NET
- 在应用程序中包含 Aspose.PDF 引用
- 创建 Document 类的实例以创建一个空的 PDF
- 创建 TextFragment 类的实例以添加文本及其属性
- 最后,通过保存在磁盘上使用 C# 创建 PDF
以下示例说明了如何在 C# 中生成 PDF。您将看到如何使用 Document Class 创建一个空白 PDF 并在其中添加一个页面。然后通过使用 TextBuilder Class 添加文本并设置其各自的属性。最后,文本将附加到 PDF 中。
从 C# 创建 PDF 的代码
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Reflection; | |
using Aspose.Pdf; | |
using Aspose.Pdf.Annotations; | |
using Aspose.Pdf.Devices; | |
using Aspose.Pdf.Facades; | |
using Aspose.Pdf.Forms; | |
using Aspose.Pdf.Text; | |
namespace TestPDF | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Applying product license to create PDF in C# | |
License lic = new License(); | |
lic.SetLicense("Total.Product.Family.lic"); | |
// Initialize document object generate PDF from C# | |
Document document = new Document(); | |
// Insert page in PDF | |
Page pdfPage = document.Pages.Add(); | |
// Create instance of Text fragment | |
TextFragment textFragment = new TextFragment("Knowledgebase Text"); | |
// Set textual properties | |
textFragment.Position = new Position(100, 600); | |
textFragment.TextState.FontSize = 12; | |
textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman"); | |
textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray); | |
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red); | |
// Initialize TextBuilder object | |
TextBuilder textBuilder = new TextBuilder(pdfPage); | |
// Append added fragment to the PDF page | |
textBuilder.AppendText(textFragment); | |
// Create PDF using C# | |
document.Save("Generated_out.pdf"); | |
} | |
} | |
} |
在上面的示例代码中,我们观察了如何在不依赖 Adobe PDF 或任何其他 API 的情况下使用 C#* 创建 PDF 文件。通过使用几个简单的 API 调用,我们通过添加文本和设置其各自的属性从头开始创建 PDF。
在上一主题中,您学习了如何在 C# 中阅读 PDF。鉴于以上说明和 C# 中的示例代码以编程方式创建 PDF 文件。