【问题标题】:PdfStamper always assuming A4 dimensionsPdfStamper 始终采用 A4 尺寸
【发布时间】:2018-05-05 19:39:52
【问题描述】:

我正在尝试使用 itextsharp 将页码写入我的 PDF 文档。 我遵循了示例here。这个答案将我指向this implementation in C#的方向。

现在,一切正常 - 假设页面方向为 A4。在我的情况下,它不是。我正在使用横​​向 A3 页面。因为我想很好地定位页码,所以我需要我正在处理的页面的尺寸。

stamper.GetOverContent().PdfDocument.PageSize 似乎总是返回 A4 页面的尺寸。

这是一个可重现的例子:

using (var ms = new MemoryStream())
{
    using (var doc = new Document(PageSize.A3.Rotate()))
    {
        Debug.WriteLine(doc.PageSize);
        var writer = PdfWriter.GetInstance(doc, ms);

        doc.Open();
        doc.Add(new Paragraph("Hello!"));
    }

    byte[] firstPass = ms.ToArray();

    PdfReader reader = new PdfReader(firstPass);
    using (var fs = new FileStream("out2.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
    {
        using (PdfStamper stamper = new PdfStamper(reader, fs))
        {
            int totalPages = reader.NumberOfPages;
            for (var i = 1; i <= totalPages; i++)
            {
                var under = stamper.GetUnderContent(i); 
                var over = stamper.GetOverContent(i);

                Debug.WriteLine(under.PdfDocument.PageSize);
                Debug.WriteLine(over.PdfDocument.PageSize);
            }
        }
    }
}

其输出为:

矩形:1191x842(旋转:90 度)
RectangleReadOnly:595x842(旋转:0 度)
RectangleReadOnly:595x842(旋转:0 度)

如何正确地获得带有PdfStamper的文档的页面大小?

请注意,这个问题不是关于使用 iTextSharp 生成页码的问题。有各种解决方法。这个问题特别是关于通过PdfStamper 阅读文档的正确尺寸。

【问题讨论】:

    标签: c# itext


    【解决方案1】:

    我没有解释为什么stamper.GetUnderContent(i).PdfDocument 默认为 A4,但是,获取页面大小的正确方法是:

    var pageSize = reader.GetPageSizeWithRotation(i);
    

    请注意,这是完整页面大小,包括边距。

    【讨论】:

    • 没有理由获取PdfStamper 页面的PdfContentBytePdfDocument 实例。我们永远不应该暴露那个对象,因为通过暴露它,人们认为他们可以使用它。自从 iText 的第一个版本以来,我们一直在拖着这样的设计错误(我是一个自学成才的开发人员;我在 2000 年发布了 iText 的第一个版本;当我看到那些日子的代码时,我仍然感觉很糟糕)。 2016 年,我们终于有办法从头开始重写 iText。您不会在 iText 7 中看到类似的设计错误(如果您希望您的代码面向未来,您应该使用它)。
    • 您正在使用带有旧(7.0 之前)API 的 iText。该 API 增长了很多,有时甚至很疯狂,这导致了一些怪异。 PdfDocumentPageSize 仅在该类用于使用真正的 PdfWriter 从头开始​​创建 pdf 时才有意义。在PdfStamper 用例中,它包含一个不感兴趣的默认值。
    • @BrunoLowagie 现在我觉得有点愚蠢——我实际上并没有意识到 iText7 是一个独立于 iTextSharp 的 NuGet 包。现在看看;感觉好多了。为小费干杯
    • 无需感到愚蠢。这就是我在看 10 年前写的代码时的感受(可能也是我今天看代码时的感受)。
    猜你喜欢
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    • 2016-09-30
    相关资源
    最近更新 更多