使用 C# 使用 PDFsharp 创建多个页面

Creating multiple pages with PDFsharp using C#

我正在使用 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() 的 return 值来创建新的 XGraphics 对象。

这个问题重复:

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

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

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.FromPdfPage(page);在一页中两次。

只需确保处理掉第一个,一切就绪。

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

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

he/she 可能指的是页面不允许有多个活动的 XGraphics 对象。