【问题标题】:Page X of Y issue第 X 页,共 Y 期
【发布时间】:2012-04-08 09:03:00
【问题描述】:

我尝试了 3 种不同的显示页码的方式,OnCloseDocument 内容没有显示在页面中,它们都不起作用。

我的意图是像这样显示页码

10 个中的 1 个
2 0f 10
.............
......
10 个,共 10 个 在每一页上

我知道怎么显示

1
2
3
4
....
10

不知道如何显示总页码

我正在使用 OnCloseDocument 显示页数,但其中的 内容是 不显示。

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
    }

第一种方式:

    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);
    }    

第二种方式:

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

第三种方式:

    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();
    }

我做错了什么吗?

【问题讨论】:

    标签: itextsharp


    【解决方案1】:

    您的第二种方法可能是最简单的方法。下面是一个非常非常精简但可以工作的版本:

    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);
        }
    }
    

    并使用它:

    //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();
            }
        }
    }
    

    编辑

    对不起,我以为你在事件的基本设置方面有问题,我的错。

    我只看到了两种方法来做你想做的事情,要么做两次,要么使用PdfTemplate syntax which renders an image as far as I know

    我建议只运行两次,第一次只是创建 PDF,第二次是添加页码。您可以将您的第一遍运行到MemoryStream,这样您就不必在需要时敲击磁盘两次。

    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);
            }
        }
    }
    

    【讨论】:

    • 不错的解决方案,但我希望我能弄清楚为什么模板方法不起作用,因为我认为它更强大。
    • 为什么是 secondFile 以及如何创建它?
    • 效果很好。我唯一的问题是我的文档中有一些页面是纵向的,有些是横向的。有没有一种简单的方法可以告诉我哪个是哪个并相应地调整'page x of y'的x坐标?
    • @RachelEdge,PdfReader 对象有一个名为 GetPageSizeWithRotation() 的方法,它应该可以满足您的需求
    【解决方案2】:

    这里是“Chris Haas”解释的示例代码(没有将文件写入硬盘的两遍方法)

    使用内存流的“复制和粘贴代码”用于第 x 页的 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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 2017-11-16
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多