2012-03-23 29 views
12

Ho provato 3 diversi modi di visualizzare i numeri di pagina, il contenuto di OnCloseDocument non viene visualizzato nella pagina, nessuno di essi ha funzionato.Pagina X di Y problema

mia intenzione è la visualizzazione I numeri di pagina come questo

1 di 10
2 0f 10
..............
..... .......
10 di 10 in ogni pagina

so come visualizzare

....

ma don `t sanno come visualizzare il numero di pagina totale

` m utilizzando OnCloseDocument per visualizzare Numero di pagine contate, ma il contenuto di in esso è non visualizzato.

public class MyPdfPageEventHelpPageNo : iTextSharp.text.pdf.PdfPageEventHelper 
{ 
    protected PdfTemplate total; 
    protected BaseFont helv; 
    private bool settingFont = false; 

    public override void OnOpenDocument(PdfWriter writer, Document document) 
    { 
     template= writer.DirectContent.CreateTemplate(100, 100);  

     bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); 
    } 
    public override void OnCloseDocument(PdfWriter writer, Document document) 
    { 
    //See below 
    } 

WAY 1ST:

public override void OnCloseDocument(PdfWriter writer, Document document)  
    { 
     //I create a table with one column like below. 
     PdfPTable pageNumber2 = new PdfPTable(1); 
     pageNumber2.TotalWidth = 50; 
     pageNumber2.HorizontalAlignment = Element.ALIGN_RIGHT; 

     pageNumber2.AddCell(BuildTable2RightCells("Page " + writer.PageNumber)); 
     pageNumber.AddCell(BuildTable2LeftCells(writer.PageCount)); 
     pageNumber2.WriteSelectedRows(0, -1, 500, 
     (document.PageSize.GetBottom(140)), cb); 
    }  

2 ° MODO:

public override void OnCloseDocument(PdfWriter writer, Document document)  
    { 
     ColumnText.ShowTextAligned(template,Element.ALIGN_CENTER,new 
     Phrase(writer.PageNumber.ToString()), 500, 140, 0); 
    } 

3RD WAY:

public override void OnCloseDocument(PdfWriter writer, Document document)  
    { 
     template.BeginText(); 
     template.SetFontAndSize(bf, 8); 
     template.SetTextMatrix(500, 140); 
     template.ShowText(Convert.ToString((writer.PageNumber - 1))); 
     template.EndText(); 
    } 

Sto facendo qualcosa di sbagliato?

risposta

16

Il tuo secondo modo è probabilmente il modo più semplice. Qui di seguito è una versione molto, molto snellita ma lavorando:

public class MyPdfPageEventHelpPageNo : iTextSharp.text.pdf.PdfPageEventHelper { 
    public override void OnEndPage(PdfWriter writer, Document document) { 
     ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, new Phrase(writer.PageNumber.ToString()), 500, 140, 0); 
    } 
} 

E per usarlo:

//Create a file on our desktop 
string outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "OnCloseTest.pdf"); 
//Standard PDF creation, adjust as needed 
using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) { 
    using (Document doc = new Document(PageSize.LETTER)) { 
     using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) { 

      //Find our custom event handler 
      writer.PageEvent = new MyPdfPageEventHelpPageNo(); 

      doc.Open(); 

      //Add text the first page 
      doc.Add(new Paragraph("Test")); 

      //Add a new page with more text 
      doc.NewPage(); 
      doc.Add(new Paragraph("Another Test")); 

      doc.Close(); 
     } 
    } 
} 

EDIT

dispiace, ho pensato che si stavano avendo problemi con il impostazione di base degli eventi, errore mio.

Ho visto solo due modi per fare quello che stai cercando di fare, o fare due passaggi o usare lo PdfTemplate syntax which renders an image as far as I know.

Si consiglia di eseguire solo due passaggi, il primo solo per creare il PDF e il secondo per aggiungere i numeri di pagina. È possibile eseguire il primo passaggio su un MemoryStream in modo da non dover colpire il disco due volte se lo si desidera.

PdfReader reader = new PdfReader(outputFile); 
using (FileStream fs = new FileStream(secondFile, FileMode.Create, FileAccess.Write, FileShare.None)) { 
    using (PdfStamper stamper = new PdfStamper(reader, fs)) { 
     int PageCount = reader.NumberOfPages; 
     for (int i = 1; i <= PageCount; i++) { 
      ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, new Phrase(String.Format("Page {0} of {1}", i, PageCount)), 500, 140, 0); 
     } 
    } 
} 
+0

Soluzione piacevole, anche se mi piacerebbe poter capire perché il metodo dei modelli non funziona come posso vedere che è più potente. –

+0

Perché il secondo file e come lo si crea? – spadelives

+0

Che funziona bene. Il mio unico problema è che ho alcune pagine nel mio documento che sono verticali e altre che sono panoramiche. C'è un modo semplice per capire quale è e regolare di conseguenza la coordinata x per la 'pagina x di y'? –

3

Ecco il codice di esempio per la spiegazione "Chris Haas" (il metodo a due passaggi con fuori file in hard disk di scrittura)

Il "codice copia e incolla" utilizzando MemoryStream per la pagina x di uscita y

protected void Button2_Click(object sender, EventArgs e) 
{ 
    byte[] b = CreatePDF2();   
    string ss = HttpContext.Current.Request.PhysicalApplicationPath; 
    string filenamefirst = ss + DateTime.Now.ToString("ddMMyyHHmmss"); 
    string filenamefirstpdf = filenamefirst + ".pdf"; 

    using (PdfReader reader = new PdfReader(b)) 
    { 
     using (FileStream fs = new FileStream(filenamefirstpdf, FileMode.Create, FileAccess.Write, FileShare.None)) 
     { 
      using (PdfStamper stamper = new PdfStamper(reader, fs)) 
      { 
       int PageCount = reader.NumberOfPages; 
       BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); 

       for (int i = 1; i <= PageCount; i++) 
       { 
        string sss = String.Format("Page {0} of {1}", i, PageCount); 
        PdfContentByte over= stamper.GetOverContent(i); 
        over.BeginText();       
        over.SetTextMatrix(500, 750); 
        over.SetFontAndSize(bf, 8);            
        over.ShowText(sss); 
        over.EndText(); 
       } 
      } 
     } 
    } 
} 

private byte[] CreatePDF2() 
{ 
    Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50); 

    using (MemoryStream output = new MemoryStream()) 
    { 
     PdfWriter wri = PdfWriter.GetInstance(doc, output); 
     doc.Open(); 

     Paragraph header = new Paragraph("My Document") { Alignment = Element.ALIGN_CENTER }; 
     Paragraph paragraph = new Paragraph("Testing the iText pdf."); 
     Phrase phrase = new Phrase("This is a phrase but testing some formatting also. \nNew line here."); 
     Chunk chunk = new Chunk("This is a chunk."); 

     PdfPTable tab = new PdfPTable(3); 
     PdfPCell cell = new PdfPCell(new Phrase("Header", new Font(Font.FontFamily.HELVETICA, 24F))); 
     cell.Colspan = 3; 
     cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right //Style 
     cell.BorderColor = new BaseColor(System.Drawing.Color.Red); 
     cell.Border = Rectangle.BOTTOM_BORDER; // | Rectangle.TOP_BORDER; 
     cell.BorderWidthBottom = 3f; 
     tab.AddCell(cell); 
     //row 1 

     for (int i = 1; i < 120; i++) 
     { 
      //row 1 
      tab.AddCell("R1C1"); 
      tab.AddCell("R1C2"); 
      tab.AddCell("R1C3"); 
      //row 2 
      tab.AddCell("R2C1"); 
      tab.AddCell("R2C2"); 
      tab.AddCell("R2C3"); 
     } 

     doc.Add(header); 
     doc.Add(paragraph); 
     doc.Add(phrase); 
     doc.Add(chunk); 
     doc.Add(tab); 
     doc.Close(); 
     return output.ToArray(); 
    } 
} 
Problemi correlati