您的位置:首页 > 编程语言 > C#

C# 给现有PDF文档添加页眉、页脚

2018-09-11 11:23 477 查看

概述

页眉页脚是一篇完整、精致的文档的重要组成部分。在页眉页脚处,可以呈现的内容很多,如公司名称、页码、工作表名、日期、图片,如LOGO、标记等。在之前的文章中介绍了如何通过新建一页空白PDF页来添加页眉到该页面,包括文字页面、图片页眉。但是在实际应用中,该方法会有一定局限性,通过测试,下面将介绍C#给现有的PDF文档添加页眉页脚的方法。该方法中,丰富了我们对于添加页眉页脚的内容形式,包括添加图片、文字、超链接、页码等。

使用工具

注:下载该类库后,注意在程序中添加引用Spire.Pdf.dll(dll文件可在安装路径下的Bin文件夹中获取)

using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;

namespace PdfHeader
{
class Program
{
static void Main(string[] args)
{
//加载一个测试文档
PdfDocument existingPdf = new PdfDocument();
existingPdf.LoadFromFile("Test.pdf");

//调用DrawHeader()方法在现有文档添加页眉
DrawHeader(existingPdf);

//调用DrawFooter()方法在现有文档添加页脚
DrawFooter(existingPdf);

//保存并打开文档
existingPdf.SaveToFile("output.pdf");
System.Diagnostics.Process.Start("output.pdf");

}
//在页面上方空白部位绘制页眉
static void DrawHeader(PdfDocument doc)
{
//获取页面大小
SizeF pageSize = doc.Pages[0].Size;

//声明x,y两个float型变量
float x = 90;
float y = 20;

for (int i = 0; i < doc.Pages.Count; i++)
{
//在每一页的指定位置绘制图片
PdfImage headerImage = PdfImage.FromFile("logo.png");
float width = headerImage.Width / 7;
float height = headerImage.Height / 7;
doc.Pages[i].Canvas.DrawImage(headerImage, x, y, width, height);

//在每一页的指定位置绘制横线
PdfPen pen = new PdfPen(PdfBrushes.Gray, 0.5f);
doc.Pages[i].Canvas.DrawLine(pen, x, y + height + 2, pageSize.Width - x, y + height + 2);
}
}

//在页面下方空白部位绘制页脚
static void DrawFooter(PdfDocument doc)
{
//获取页面大小
SizeF pageSize = doc.Pages[0].Size;

//声明x,y两个float型变量
float x = 90;
float y = pageSize.Height - 72;

for (int i = 0; i < doc.Pages.Count; i++)
{
//在每一页的指定位置绘制横线
PdfPen pen = new PdfPen(PdfBrushes.Gray, 0.5f);
doc.Pages[i].Canvas.DrawLine(pen, x, y, pageSize.Width - x, y);

//在每一页的指定位置绘制文字
y = y + 5;
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("黑体", 10f, FontStyle.Bold), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
String footerText = " Website\n https://g20.org/";
doc.Pages[i].Canvas.DrawString(footerText, font, PdfBrushes.Black, x, y, format);

//在每一页的指定位置当前页码和总页码
PdfPageNumberField number = new PdfPageNumberField();
PdfPageCountField count = new PdfPageCountField();
PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Black, "{0}/{1}", number, count);
compositeField.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
SizeF size = font.MeasureString(compositeField.Text);
compositeField.Bounds = new RectangleF(pageSize.Width - x - size.Width, y, size.Width, size.Height);
compositeField.Draw(doc.Pages[i].Canvas);
}
}
}
}
View Code

总结

相较于上篇文章中的添加页眉的方法,本方法在处理现有的PDF文档中更具实用性。当然,两种方法针对不同的程序设计需要,满足不同的需求,我们在选择这两种方法时,可酌情而定。

(本文完)

如需转载,请注明出处。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: