Aspose.Pdf如何为PDF文件的页眉页脚添加图片和设置页码

作者:控件中国网   出处:控件中国网   2015-12-15 10:24:43   阅读:30

页眉页脚是一个特殊区域,分别在每页的顶部和底部,用于显示一些特殊信息,根据 DOM (Document Object Model)页眉页脚相当于文档里的一个片段,而片段一般由一个或几个段落租成,段落则包含了文本、图片、表单字段、表格、图形等元素。很多时候创建一个PDF文件需要在PDF文件的页眉页脚上添加一个水印或者公司的标志,该水印既可以是文本也可以是图片。
Image--and--Page-Number-in-Header-Footer-section-001.png
Aspose.Pdf可以帮助开发人员轻松地在页眉页脚里添加图片和文本信息,并且很多时候还需要在页眉页脚里添加页码,Aspose.Pdf考虑到了用户的这个需求,专门设置了一个特殊字符用于显示页码,$P显示文档的总页数,& $P则用于显示文档的当前页数,下面的代码讲述如何使用Aspose.Pdf为PDF文档设置页眉页脚,并在页眉页脚里添加图片和设置文档的页码,下面的代码使用Aspose.Pdf For java为例,.NET的代码可以参考帮助文档:
 
// Instantiate Pdf instance by calling its empty constructor
Pdf pdf1 = new Pdf();
// Create a new section in the Pdf object
Section sec1 = pdf1.getSections().add();
//=====================================================//
// Header to show an Image
//=====================================================//
 
// Create Header Section of the document
HeaderFooter hf1 = new HeaderFooter(sec1);
// Set the header of odd pages of the PDF document
sec1.setOddHeader(hf1);
// Set the header of even pages of the PDF document                      
sec1.setEvenHeader(hf1);
// Create an image object in the section
Aspose.Pdf.Image img1 = new Aspose.Pdf.Image(sec1);
// Set the path of image file
img1.getImageInfo().setFile("d:/pdftest/Aspose.JPG");
// Set the Image Width value
img1.getImageInfo().setFixWidth(200);
// Set the Image Height value
img1.getImageInfo().setFixHeight(100);
// Add image object into the Paragraphs collection of the section
hf1.getParagraphs().add(img1);
 
//=====================================================//
// Footer to show Page Number
//=====================================================//
 
// Create Header Section of the document
HeaderFooter footer = new HeaderFooter(sec1);
// Set the Odd footer of the PDF file
sec1.setOddFooter(footer);
// Set the Even footer of the PDF file
sec1.setEvenFooter(footer);
// Create a Text object
Text t1 = new Text(footer, "Page: ($p of $P) ");
// Add text to Header section of the Pdf file
footer.getParagraphs().add(t1);
//Save the document
pdf1.save(("d:/pdftest/Image_PageNumber.pdf");
Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat