【问题标题】:New page in ITextSharp does not create new pageITextSharp 中的新页面不会创建新页面
【发布时间】:2013-12-03 00:37:42
【问题描述】:

在以下代码中,我使用 ITextSharp 动态创建了一个 pdf。 当页面上没有足够的空间时,我希望拆分第二张桌子。

如何做到这一点?我用pdf stamper上的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();
        }
    }

【问题讨论】:

  • 一般来说,PdfStamper 旨在用于现有 PDF,而不是新 PDF。你这样做有理由吗?如果您切换到正常的DocumentPdfWriter 模型,那么表格将完全按照您的预期包装。但是,如果由于某种原因您需要这样做,您可以尝试 Bruno 在这里谈论的内容,尽管我从未尝试过。 stackoverflow.com/a/13539904/231316
  • 哦,是的,EmptyPdf 实际上是带有页脚标志的 A4 pdf,必须这样盖章。
  • 然后我会尝试 HasMoreText() 路线,如果它有效,那很好,但如果不是,我建议将“添加徽标”作为第二遍的一部分,因为这真的很容易做到。

标签: c# itextsharp


【解决方案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() 替换这个调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多