應用C#如何給PDF文檔添加文本與圖片頁眉。本站提示廣大學習愛好者:(應用C#如何給PDF文檔添加文本與圖片頁眉)文章只能為提供參考,不一定能成為您想要的結果。以下是應用C#如何給PDF文檔添加文本與圖片頁眉正文
前言
上面這篇文章向大家分享如何運用了收費組件Free Spire.PDF給PDF文檔添加文本和圖片頁眉。這個組件提供了一些辦法,可以協助我們疾速方便地完成此目的。
添加頁眉步驟:
首先,創立一個Visual C#控制台項目,添加組件援用並運用以下命名空間。
using System; using System.Drawing; using Spire.Pdf; using Spire.Pdf.Graphics;
在下列代碼中,我們先定義一個SetDocumentTemplate()辦法來創立一個PDF文檔模板,這個模板只包括文本和圖片頁眉。然後,調用DrawString(string s, PdfFontBase font, PdfBrush brush, float x, float y, PdfStringFormat format)辦法和DrawImage(PdfImage image, float x, float y, float width, float height)辦法,拔出自定義的文本和圖片頁眉。
static void SetDocumentTemplate(PdfDocument doc, SizeF pageSize, PdfMargins margin)
{
//創立PDF模板
PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.Width, margin.Top);
topSpace.Foreground = true;
doc.Template.Top = topSpace;
//添加文本頁眉
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("宋體", 15f), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
String Text = "PDF文本頁眉";
float y = 0;
float x = PdfPageSize.A4.Width;
topSpace.Graphics.DrawString(Text, font1, PdfBrushes.PaleVioletRed, x, y, format);
//添加圖片頁眉
PdfImage headerImage = PdfImage.FromFile(@"logo.png" />
全部代碼:
using System;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.Graphics;
namespace PDF添加頁眉
{
class Program
{
static void Main(string[] args)
{
PdfDocument doc = new PdfDocument();
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(4.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
SetDocumentTemplate(doc, PdfPageSize.A4, margin);
PdfPageBase page = doc.Pages.Add();
doc.Pages.Add();
doc.SaveToFile("頁眉.pdf");
System.Diagnostics.Process.Start("頁眉.pdf");
}
static void SetDocumentTemplate(PdfDocument doc, SizeF pageSize, PdfMargins margin)
{
PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.Width, margin.Top);
topSpace.Foreground = true;
doc.Template.Top = topSpace;
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("宋體", 15f), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
String Text = "PDF文本頁眉";
float y = 0;
float x = PdfPageSize.A4.Width;
topSpace.Graphics.DrawString(Text, font1, PdfBrushes.PaleVioletRed, x, y, format);
PdfImage headerImage = PdfImage.FromFile(@"C:\Users\Administrator\Pictures\under_construction.jpg");
float width = headerImage.Width;
float height = headerImage.Height;
PointF pageLeftTop = new PointF(0, 0);
topSpace.Graphics.DrawImage(headerImage, 0, 0, width / 2, height / 2);
}
}
}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家學習或許運用C#能帶來一定的協助,假如有疑問大家可以留言交流,謝謝大家對的支持。