我正在使用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.FromPdfPage(页面);一页两次。
只要确保你处腐掉第一个就完成了。
Using (XGraphics gfx = XGraphics.FromPdfPage(page))
{ MakeItRain(); }
要么
if (gfx == null)
gfx.Dispose();
XGraphics gfx = XGraphics.FromPdfPage(page);
他/她可能指的是该页面不允许有多个活动的XGraphics对象。