使用c#创建PDFsharp多个页面



我正在使用PDFsharp创建一个PDF页面。这对于只有一页的文档非常有效。在这种情况下,行需要填满两页。当行数等于20时,我想创建一个新的页面,并将剩余的内容写入其中。

此代码在第一页上写入内容,但一旦行数等于20,它将继续在第一页上写入而不是第二个。

我该如何解决这个问题?

PdfDocument document = new PdfDocument();
document.Info.Title = "Created with PDFsharp";
// Create an empty page
PdfPage page = document.AddPage();
//page.Width = 
//page.Height = 
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
//XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
// Create a font
XFont font = new XFont("Times New Roman", 8, XFontStyle.BoldItalic);
int headeroneX = 30;
int headerOney = 25;
Int32 countLines = 0;
foreach (var item in queryResult)
{
    if ((playerIndex % TotalNumberOfUsersInGrp) == 0)
    {
        gfx.DrawString("Group:" + groupindex, font, XBrushes.DarkRed, new XRect(headeroneX, headerOney, page.Width, page.Height), XStringFormats.TopLeft);
        groupindex++;           
        headerOney = headerOney + 12;
    }
    gfx.DrawString(item.FullName + ',' + item.Rating, font, XBrushes.Black, new XRect(headeroneX, headerOney, page.Width, page.Height), XStringFormats.TopLeft);
    playerIndex++;
    headerOney = headerOney + 12;
    countLines = countLines + 1;
    if (countLines == 20)
    {
        countLines = 1;
        headerOney = 25;
        document.AddPage();
        gfx.DrawString(item.FullName + ',' + item.Rating, font, XBrushes.Black, new XRect(headeroneX, headerOney, page.Width, page.Height), XStringFormats.TopLeft);
    }
}

我敢肯定这是重复的。

调用AddPage()来创建第二个页面,但继续使用为第一个页面创建的XGraphics对象。您必须使用AddPage()的返回值来创建一个新的XGraphics对象。

这个问题的重复:
https://stackoverflow.com/a/21143712/1015447

另一个家伙试图创建一个新的XGraphics对象,但也没有使用AddPage()的返回值。

更新:未经测试的代码-我希望它能编译。

if (countLines == 20)
{
    countLines = 1;
    headerOney = 25;
    // Wrong: document.AddPage();
    // Better:
    page = document.AddPage();
    // Also missing:
    gfx = XGraphics.FromPdfPage(page);
    gfx.DrawString(item.FullName + ',' + item.Rating, font, XBrushes.Black, new XRect(headeroneX, headerOney, page.Width, page.Height), XStringFormats.TopLeft);
}

这是一个有点老的话题或线程,但添加一些输入来澄清。

user2320476错误。您可以(并且允许)使用xgraphics . frommpdfpage (page);一页两次

只要确保你处理了第一个,你就没事了。

Using (XGraphics gfx = XGraphics.FromPdfPage(page))
{ MakeItRain(); }

if (gfx == null)
gfx.Dispose();
XGraphics gfx = XGraphics.FromPdfPage(page);

他/她可能指的是页面不允许有多个活动的XGraphics对象

最新更新