ITextSharp - 绘制矩形左上角

时间:2018-02-24 07:51:38

标签: itext

我正在尝试使用ITextSharp(5.5.13)在页面的左上角绘制一个矩形。我想在页边距中绘制。但是,矩形大约25像素太低。如何在左上角绘制矩形?

pdf rectangle

以下是我如何将矩形添加到页面中:

using (PdfReader reader = new PdfReader(inputPdf.FullName))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(outputPdf.FullName, FileMode.Create)))
{    
    PdfContentByte contentByte = stamper.GetOverContent(1);    
    PdfDocument doc = contentByte.PdfDocument;

    float X = 0.0f;
    float Y = 0.0f;
    float Height = Utilities.InchesToPoints(0.50f);
    float Width = Utilities.InchesToPoints(0.50f);

    float llx = (doc.Left - doc.LeftMargin) + X;
    float lly = (doc.Top - doc.TopMargin) - (Height + Y);
    float urx = (doc.Left - doc.LeftMargin) + Width + X;
    float ury = (doc.Top - doc.TopMargin) - Y;

    Rectangle rectangle = new Rectangle(llx, lly, urx, ury)
    {
        BackgroundColor = BaseColor.BLACK
    };

    contentByte.Rectangle(rectangle);
}

以下是每个上述变量的调试值:

debug

1 个答案:

答案 0 :(得分:1)

每当你使用PdfStamper时,你可以从其部分检索的PdfDocument不包含敏感信息,它只是一个虚拟对象。

因此,请勿尝试从PdfDocument doc确定页面大小,而应使用PdfReader reader的相应方法或属性,例如

    /** Gets the crop box without taking rotation into account. This
    * is the value of the /CropBox key. The crop box is the part
    * of the document to be displayed or printed. It usually is the same
    * as the media box but may be smaller. If the page doesn't have a crop
    * box the page size will be returned.
    * @param index the page number. The first page is 1
    * @return the crop box
    */
    virtual public Rectangle GetCropBox(int index)