简体   繁体   English

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

[英]New page in ITextSharp does not create new page

In the following code I create a pdf dynamically using ITextSharp. 在以下代码中,我使用ITextSharp动态创建pdf。 I want the 2nd table to be splitted when there is not room enough on the page. 当页面上没有足够的空间时,我希望拆分第二张表。

How can this be accomplished ? 如何做到这一点? I tried it with the newPage method on the pdf stamper, but no new page has been created... 我在pdf压模上使用newPage方法尝试过,但是尚未创建新页面...

(not all codepaths included for readability) (不包括所有代码路径以提高可读性)

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();
        }
    }

I see you take an existing PDF file (referred to as "emptyPdfFile" ) add content to that PDF (2 tables) and want to add pages as necessary. 我看到您将现有的PDF文件(称为"emptyPdfFile" )添加到该PDF(2个表)中,并希望根据需要添加页面。 So I assume you actually want to create a PDF from scratch. 因此,我假设您实际上是想从头开始创建PDF。

In that case it's most likely easier to use PdfWriter and add your tables using Document.Add() . 在这种情况下,最可能使用PdfWriter并使用Document.Add()添加表。 Tables will be split and pages will be added automatically when the end of the current page is reached. 到达当前页面的末尾时,将拆分表并自动添加页面。 A simple example of adding a table with Document.Add() can be found here in the MyFirstTable example (that's iText code in Java, check the C# port for iTextSharp code). MyFirstTable示例中可以找到一个使用Document.Add()添加表的简单示例(这是Java中的iText代码,请在C#端口中查看iTextSharp代码)。

If you do want to follow the approach of your example code, using PdfReader , PdfStamper and ColumnText : 如果您确实想遵循示例代码的方法,请使用PdfReaderPdfStamperColumnText

ColumnText.Go() adds content to the defined area until that area is full. ColumnText.Go()将内容添加到定义的区域,直到该区域已满。 Any remaining content stays in the ColumnText object. 任何剩余的内容都保留在ColumnText对象中。 So if you want to split the content over multiple areas, you have to loop and call ColumnText.Go() until all content is consumed. 因此,如果要将内容拆分为多个区域,则必须循环并调用ColumnText.Go()直到所有内容都被消耗为止。

Here's an example of the ColumnText.Go() looping: ColumnTable (Again, you may want to check the C# port ). 下面是ColumnText.Go()循环的示例: ColumnTable (再次,您可能要检查C#port )。

In that example the tables are layed out in 2 columns on each page, but the approach stays the same for 1 table per page. 在该示例中,表在每页上分为两列,但是对于每页1个表,方法保持不变。 Note that Document.NewPage() is used in the example to add an extra page. 请注意,示例中使用Document.NewPage()添加了额外的页面。 You'll have to replace this call with PdfStamper.InsertPage() in your case. 在这种情况下,您必须用PdfStamper.InsertPage()替换此调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM