每页打印3条记录到PDF

时间:2011-08-28 11:24:35

标签: c# pdfsharp

我想根据我的记录创建动态PDF文档页面。请帮帮我。

我想每页打印3条记录。

string[] collection = {
    "vivek", "kashyap", "viral", "darshit", "arpit", "sameer", "vanraj"
};

PdfDocument pdfDoc = new PdfDocument();

int records = collection.Length;
int perpage = 3;
int pages = (int)Math.Ceiling((double)records / (double)perpage);


for (int p = 0; p < pages; p++)
{          
    PdfPage pdfPage = new PdfPage();
    pdfPage.Size = PageSize.Letter;
    pdfDoc.Pages.Add(pdfPage);
    XFont NormalFont = new XFont("Helvetica", 10, XFontStyle.Regular);

    using (var pdfGfx = XGraphics.FromPdfPage(pdfPage))
    {
        for (int i = 0,next = 100; i < collection.Length; i++)
        {
            pdfGfx.DrawString( "Name : " + collection[i].ToString()
                             , NormalFont, XBrushes.Black, 55, next
                             , XStringFormats.Default);
            next += 20;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我认为您提供的代码显示相同的顶级条目?您需要做的是在页面之间移动时保持每个条目的开始。我已经调用了这个变量 idx 并更新了下面的代码(注意我实际上没有编译它,除非在我脑海中)。

string[] collection = { "vivek", "kashyap", "viral", "darshit", "arpit", "sameer", "vanraj" };

PdfDocument pdfDoc = new PdfDocument();

int records = collection.Length;
int perpage = 3;
int pages = (int)Math.Ceiling((double)records / (double)perpage);

int idx = 0;

for (int p = 0; p < pages; p++)
{

    PdfPage pdfPage = new PdfPage();
    pdfPage.Size = PageSize.Letter;
    pdfDoc.Pages.Add(pdfPage);
    XFont NormalFont = new XFont("Helvetica", 10, XFontStyle.Regular);
    using (var pdfGfx = XGraphics.FromPdfPage(pdfPage))
    {
        for (int i = 0,next = 100; i < perpage; i++)
        {
            if ((idx + i) >= records.length) break;
            pdfGfx.DrawString("Name : " + collection[idx  + i].ToString(), NormalFont,
                XBrushes.Black, 55, next, XStringFormats.Default);

            next += 20;
        }
    }

    idx += perpage;

}

答案 1 :(得分:0)

我相信这段代码:

for (int i = 0,next = 100; i < collection.Length; i++)

您正在循环收集所有记录。

你应该重新设计你的代码,只在那里打印3条记录然后你可以切换到下一页并打印接下来的3条记录,依此类推。

你可以使用退出循环的break命令执行此操作但是你应该有一个变量来存储引用或索引或最新的打印记录,这样你就可以继续下一页的下一个。

我会在整个代码中重新思考,因为可以改进循环的嵌套,例如我个人在顶层有一个主循环,它循环所有记录而不是所有页面,所以你可以切换到主循环体中的下一页,但永远不要将循环留在所有记录上,直到打印出所有记录。

相关问题