现在的位置: 首页 > 综合 > 正文

iTextSharp生成的PDF显示“Page X of Y”的效果,IPdfPageEvent的应用一例

2012年08月02日 ⁄ 综合 ⁄ 共 8243字 ⁄ 字号 评论关闭
网友来信提出这个需求,看到iText的另外一个版本的教程中有这么个demo,就把它转换成C#,贴出来了,有需要的朋友可以根据自己的需求再进行适当的修改就可以。原java代码见如下地址:
http://itextdocs.lowagie.com/tutorial/directcontent/pageevents/
注,运行下面的程序,你需要个叫logo.gif的图片(http://itextdocs.lowagie.com/tutorial/directcontent/pageevents/logo.gif)

using System;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace iTextSharp.Demo
{
    
/// <summary>
    
/// Making a document with a header containing 'page x of y' and with a watermark on every page.
    
/// </summary>

    public class PageNumbersWatermark : IPdfPageEvent
    
{
        
/** An Image that goes in the header. */
        
public Image headerImage;
        
/** The headertable. */
        
public PdfPTable table;
        
/** The Graphic state */
        
public PdfGState gstate;
        
/** A template that will hold the total number of pages. */
        
public PdfTemplate tpl;
        
/** The font that will be used. */
        
public BaseFont helv;

        
public PageNumbersWatermark()
        
{
            
try 
            
{
                
// step 1: creating the document
                Document doc = new Document(PageSize.A4, 505010072);
                
// step 2: creating the writer
                
                PdfWriter writer 
= PdfWriter.GetInstance(doc, new FileStream("pageNumbersWatermark.pdf",FileMode.Create));
                
// step 3: initialisations + opening the document
                writer.PageEvent =new PageNumbersWatermark();
                doc.Open();
                
// step 4: adding content
                string text = "some padding text ";
                
for (int k = 0; k < 10++k)
                    text 
+= text;
                Paragraph p 
= new Paragraph(text);
                p.Alignment
=(Element.ALIGN_JUSTIFIED);
                doc.Add(p);
                
// step 5: closing the document
                doc.Close();
            }

            
catch ( Exception e ) 
            
{
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
            }

        }

        
IPdfPageEvent Members
    }

}

更多iTextSharp的教程请访问:
iTextSharp (iText#) tutorial update vers

抱歉!评论已关闭.