这个精确的教程讨论了有关如何使用 C# 在 PDF 中添加页眉和页脚的信息。它有助于我们了解在 C# 中在 PDF 中添加页眉和页脚的过程,其中可以根据您的应用程序要求配置不同的属性。此外,任何第三方工具或任何插件都不是将此功能集成到您的项目中的先决条件。
在 C# 中将页眉页脚添加到 PDF 的步骤
- 添加对 Aspose.PDF for .NET 库的引用,以便将页眉和页脚插入 PDF 文件
- 使用 Document 类加载源 PDF 文件以添加页眉和页脚
- 为所有页面上的页眉和页脚指定不同的属性
- 编写包含页眉和页脚部分的输出 PDF 文档
上述步骤总结了使用 C#* 在 PDF 中插入页眉和页脚的工作流程。您可以注意到,通过几个 API 调用即可实现这些要求。此外,您可以在多个线程中同时处理多个 PDF 文档。
使用 C# 在 PDF 中添加页眉和页脚的代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace HowToAddHeaderAndFooterInPDFUsingCSharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to rotate a cell in Excel using CSharp | |
{ | |
// Instantiate a Cell License to avoid watermark in the output XLSX after | |
// rotating text in the cell | |
Aspose.Pdf.License licForCells = new Aspose.Pdf.License(); | |
licForCells.SetLicense("Aspose.Pdf.lic"); | |
// Open document | |
Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document("Input.pdf"); | |
// Create header | |
Aspose.Pdf.TextStamp headerTextStamp = new Aspose.Pdf.TextStamp("Header Text"); | |
// Set properties of the stamp | |
headerTextStamp.TopMargin = 10; | |
headerTextStamp.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center; | |
headerTextStamp.VerticalAlignment = Aspose.Pdf.VerticalAlignment.Top; | |
// Create footer | |
Aspose.Pdf.TextStamp footerTextStamp = new Aspose.Pdf.TextStamp("Footer Text"); | |
// Set properties of the stamp | |
footerTextStamp.BottomMargin = 10; | |
footerTextStamp.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center; | |
footerTextStamp.VerticalAlignment = Aspose.Pdf.VerticalAlignment.Bottom; | |
// Add header and footer on all pages | |
foreach (Aspose.Pdf.Page page in pdfDocument.Pages) | |
{ | |
page.AddStamp(headerTextStamp); | |
page.AddStamp(footerTextStamp); | |
} | |
// Save updated document | |
pdfDocument.Save("PdfHeaderFooterText.pdf"); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
此代码示例可以在 C#* 应用程序中有效地*将页眉页脚添加到 PDF。您可以增强代码以操作文本字符串、字体样式、大小或颜色以及页码。例如,奇数页码上的页眉和页脚不同,而偶数页码上的页眉页脚的另一种变体。
在本文中,我们学习了在 PDF 页面中插入页眉和页脚的过程。然而,如果您想学习压缩 PDF 文档,请参阅有关 如何在 C# 中压缩 PDF 的文章。