如何知道文本是否超过 itextSharp 中的填充框

How to know if text exceeds the fill box in itextSharp

我正在使用以下代码:

PdfReader PDFReader = new PdfReader("c:\file.pdf");

FileStream Stream = new FileStream("c:\new.pdf", FileMode.Create, FileAccess.Write);

PdfStamper PDFStamper = new PdfStamper(PDFReader, Stream);

for (int iCount = 0; iCount < PDFStamper.Reader.NumberOfPages; iCount++)
{
    iTextSharp.text.Rectangle PageSize = PDFReader.GetCropBox(iCount + 1);
    PdfContentByte PDFData = PDFStamper.GetOverContent(iCount + 1);
    BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
    PDFData.BeginText();
    PDFData.SetColorFill(CMYKColor.RED);
    PDFData.SetFontAndSize(baseFont, 20);
    PDFData.ShowTextAligned(PdfContentByte.ALIGN, SAMPLE DOCUMENT", (PageSize.Right + PageSize.Left) / 2, (PageSize.Top + PageSize.Bottom) / 2, 45);
    PDFData.EndText();
}

PDFStamper.Close();
PDFReader.Close();

但是有时重叠的文字会超过页面大小,因为我硬编码了字体为20。那么,有什么办法可以知道重叠的文字是否会超过页面大小?因为我想使用像我将使用的代码:

if(pagesize exceeds)
  reduce font size by 1 point and check again .....

如果上述方法不起作用,那么我的下一步是使用 PNG 图像,其中包含重叠的文本并且其背景为透明。然后根据页面大小调整图像大小,然后叠加它。

不过,我更喜欢第一部分。如果没有,那么我会选择第二个选项。

经过一些小的计算后,此方法应计算出用于此类垂直文本的最大字体大小并应用它:

void Stamp(PdfContentByte cb, Rectangle rect, BaseFont bf, string text)
{
    int altitude = Math.Max(bf.GetAscent(text), bf.GetDescent(text));
    int width = bf.GetWidth(text);
    double horizontalFit = Math.Sqrt(2.0) * 1000 * (rect.Left + rect.Right) / (width + 2 * altitude);
    double verticalFit = Math.Sqrt(2.0) * 1000 * (rect.Bottom + rect.Top) / (width + 2 * altitude);
    double fit = Math.Min(horizontalFit, verticalFit);

    cb.BeginText();
    cb.SetColorFill(CMYKColor.RED);
    cb.SetFontAndSize(bf, (float) fit);
    cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text, (rect.Right + rect.Left) / 2, (rect.Top + rect.Bottom) / 2, 45);
    cb.EndText();
}

你可以这样称呼它:

using (PdfReader reader = new PdfReader(source))
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create, FileAccess.Write)))
{
    for (int iCount = 0; iCount < reader.NumberOfPages; iCount++)
    {
        Rectangle PageSize = reader.GetCropBox(iCount + 1);
        PdfContentByte PDFData = stamper.GetOverContent(iCount + 1);
        BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
        Stamp(PDFData, PageSize, baseFont, "SAMPLE DOCUMENT");
    }
}

(顺便说一句,我使用了你的BaseFont,但你应该知道iText(Sharp)将忽略BaseFont.EMBEDDED标准14种字体,如BaseFont.HELVETICA。)

结果如下所示:

PS:如果您(如您的问题所述)真的不想使用 20 以上的字体大小,则必须再次 Min fit 值20.