ITextSharp中的新页面不会创建新页面

时间:2013-12-02 12:46:21

标签: c# itextsharp

在下面的代码中,我使用ITextSharp动态创建pdf。 我希望在页面上没有足够的空间时拆分第二个表格。

如何实现这一目标?我在pdf压模上使用newPage方法尝试了它,但是没有创建新页面......

(并非所有代码路径都包含在内以便于阅读)

private byte[] DoGenerateStatisticsPerOrganisationalUnitPdf(
        string emptyPdfFile,
        DateTime currentDateTime,
        string organisationalUnit,
        int? roleId,
        DateTime? fromDate,
        DateTime? toDate)
    {
        var pdfReader = new ITextSharp.pdf.PdfReader(emptyPdfFile); // note that PdfReader is not IDisposeable

        using (MemoryStream memoryStream = new MemoryStream())
        using (ITextSharp.pdf.PdfStamper pdfStamper = new ITextSharp.pdf.PdfStamper(pdfReader, memoryStream))
        {
            // Get content bytes of first page
            var pdfContentByte = pdfStamper.GetOverContent(1);

            // Make a page width/height large rectangle column for write actions
            var ct = new ITextSharp.pdf.ColumnText(pdfContentByte);

            ct.SetSimpleColumn(
                PageStartX,
                PageStartY,
                PageEndX,
                PageEndY);

            var paragraph = new iTextSharp.text.Paragraph(new ITextSharp.Chunk("Statistieken Profchecks", titleFont));
            ct.AddElement(paragraph);

            // Add printed date time
            var dateTimeText = string.Format(
                CultureInfo.CurrentCulture,
                "Afdrukdatum: {0}",
                currentDateTime.ToString(DateFormat, CultureInfo.CurrentCulture));
            paragraph = new iTextSharp.text.Paragraph(new ITextSharp.Chunk(dateTimeText, rowFont));
            ct.AddElement(paragraph);

            // Add selected filter
            var filterItems = string.Empty;

            if (!string.IsNullOrEmpty(organisationalUnit))
            {
                filterItems += "\n" + string.Format(CultureInfo.CurrentCulture, "   ° Organisatie: {0}", organisationalUnit);
            }

            if (roleId.HasValue)
            {
                filterItems += "\n" + string.Format(CultureInfo.CurrentCulture, "   ° Rol: {0}", roleService.GetById(roleId.Value).Name);
            }

            if (fromDate.HasValue)
            {
                filterItems += "\n" + string.Format(CultureInfo.CurrentCulture, "   ° Datum van: {0}", fromDate.Value.ToString(DateFormat, CultureInfo.CurrentCulture));
            }

            if (toDate.HasValue)
            {
                filterItems += "\n" + string.Format(CultureInfo.CurrentCulture, "   ° Datum t/m: {0}", toDate.Value.ToString(DateFormat, CultureInfo.CurrentCulture));
            }

            var filterText = string.Format(
                CultureInfo.CurrentCulture,
                "Geselecteerde filter: {0}",
                filterItems.Length > 0 ? filterItems : "(geen filter)");
            paragraph = new iTextSharp.text.Paragraph(new ITextSharp.Chunk(filterText, rowFont));
            ct.AddElement(paragraph);

            paragraph = new iTextSharp.text.Paragraph(new ITextSharp.Chunk("\nResultaten per game", titleFont));
            ct.AddElement(paragraph);

            // Table: Results per game
            var table = CreateTable(new string[] { "Game", "Unieke spelers", "Resultaat" });

            var gameResultList = statisticsService.GetOrganisationalUnitStatistics(1, 20, organisationalUnit, roleId, fromDate, toDate);
            foreach (var gameResultItem in gameResultList)
            {
                table.AddCell(new iTextSharp.text.Phrase(gameResultItem.Game, rowFont));
                table.AddCell(new iTextSharp.text.Phrase(gameResultItem.NumberOfUsers.ToString(CultureInfo.CurrentCulture), rowFont));
                var percentage = gameResultItem.AveragePercentage.HasValue ? string.Format(CultureInfo.CurrentCulture, "{0}%", gameResultItem.AveragePercentage) : "?";
                table.AddCell(new iTextSharp.text.Phrase(percentage, rowFont));
            }

            table.CompleteRow();

            ct.AddElement(table);

            paragraph = new iTextSharp.text.Paragraph(new ITextSharp.Chunk("\nResultaten per kenniscategorie", titleFont));
            ct.AddElement(paragraph);

            // Table: Results per knowledgecategory
            table = CreateTable(new string[] { "Kenniscategorie", "Gemiddeld", "Laagste", "Hoogste", "Standaard deviatie" });

            var knowledgeCategoryResultList = statisticsService.GetGlobalKnowledgeCategoryResultStatistics(
                organisationalUnit,
                roleId,
                fromDate,
                toDate);

            foreach (var knowledgeCategoryResultItem in knowledgeCategoryResultList)
            {
                table.AddCell(new iTextSharp.text.Phrase(knowledgeCategoryResultItem.KnowledgeCategory.Name, rowFont));
                table.AddCell(new iTextSharp.text.Phrase(
                    knowledgeCategoryResultItem.Statistics.Average.ToString(CultureInfo.CurrentCulture), 
                    rowFont));
                table.AddCell(new iTextSharp.text.Phrase(
                    knowledgeCategoryResultItem.Statistics.Minimum.ToString(CultureInfo.CurrentCulture), 
                    rowFont));
                table.AddCell(new iTextSharp.text.Phrase(
                    knowledgeCategoryResultItem.Statistics.Maximum.ToString(CultureInfo.CurrentCulture), 
                    rowFont));
                table.AddCell(new iTextSharp.text.Phrase(
                    knowledgeCategoryResultItem.Statistics.StDev.HasValue ? knowledgeCategoryResultItem.Statistics.StDev.Value.ToString(
                    CultureInfo.CurrentCulture) : "?", 
                    rowFont));
            }

            table.CompleteRow();

            ct.AddElement(table);

            // Parse
            ct.Go();

            pdfStamper.FormFlattening = true;
            pdfStamper.FreeTextFlattening = true;

            // Close stamper explicitly, otherwise the pdf gets corrupted (don't wait until the Dispose is called in the using-clause)
            pdfStamper.Close();

            // Always call ToArray, to get all the bytes returned.
            return memoryStream.ToArray();
        }
    }

1 个答案:

答案 0 :(得分:1)

我看到您将现有PDF文件(称为"emptyPdfFile")添加到该PDF(2个表)中,并希望根据需要添加页面。所以我假设您确实想要从头开始创建PDF。

在这种情况下,最有可能使用PdfWriter并使用Document.Add()添加表格。将分割表格,并在到达当前页面结束时自动添加页面。 可以在MyFirstTable示例中找到一个添加Document.Add()表的简单示例(这是Java中的iText代码,请查看the C# port以获取iTextSharp代码。)

如果您确实想要遵循示例代码的方法,请使用PdfReaderPdfStamperColumnText

ColumnText.Go()将内容添加到定义的区域,直到该区域已满。任何剩余内容都保留在ColumnText对象中。因此,如果要将内容拆分为多个区域,则必须循环并调用ColumnText.Go(),直到所有内容都被使用。

以下是ColumnText.Go()循环的示例:ColumnTable(同样,您可能需要检查the C# port)。

在该示例中,每个页面上的表格布置为2列,但每页1个表格的方法保持不变。 请注意,示例中使用了Document.NewPage()来添加额外页面。在您的情况下,您必须使用PdfStamper.InsertPage()替换此来电。