以下代码将从一个PDF文件复制所有页面到一个新文件,并在第一页插入一个带红色边框的矩形,上面有一段简短的文本。
如果我不移动它,在顶部会留下一个间隙(这里放大了很多,字体大小只有8):
如果我不移动它,在顶部会留下一个间隙(这里放大了很多,字体大小只有8):
然而,如果我将矩形向上移动一个经验值 4 :
iText.Kernel.Geom.Rectangle pageSize = firstPage.GetCropBox().MoveUp(4);
顶部将有一个完美的匹配:
数值4与字体大小无关。
我不喜欢代码中的“魔法数字”,所以我的问题是:为什么是4?哪个表达式能揭示这个值为4?
这行代码在第一个方法中。第二个方法是使用它的地方,第三个方法是从第一个方法调用的;它只提供了一种样式:
private static void RegisterDocument(PdfDocument pdfDocument, string registration)
{
// Magic value to close gap between top of page and top of rectangle with the registration.
const float moveUp = 4F;
Document document = new Document(pdfDocument, new PageSize(PageSize.A4));
PdfPage firstPage = document.GetPdfDocument().GetFirstPage();
Paragraph paragraph = new Paragraph(registration).AddStyle(RegistrationStyle());
iText.Kernel.Geom.Rectangle pageSize = firstPage.GetCropBox().MoveUp(moveUp);
LayoutContext layoutContext = new LayoutContext(new LayoutArea(1, pageSize));
IRenderer renderer = paragraph.CreateRendererSubTree();
renderer.SetParent(document.GetRenderer()).Layout(layoutContext);
Canvas canvas = new Canvas(new PdfCanvas(firstPage, true), pageSize);
canvas.Add(paragraph);
document.Close();
}
public static void RegisterPdf(string sourceFilename, string targetFilename, string registration)
{
if (registration.Length > 0)
{
// Open source and target PDF files.
PdfDocument sourcePdf = new PdfDocument(new PdfReader(sourceFilename));
PdfDocument targetPdf = new PdfDocument(new PdfWriter(targetFilename));
// Copy all pages from source PDF to target PDF.
sourcePdf.CopyPagesTo(1, sourcePdf.GetNumberOfPages(), targetPdf);
// Add registration to page 1 of target and save the document.
RegisterDocument(targetPdf, registration);
// Close the files.
sourcePdf.Close();
targetPdf.Close();
}
}
private static Style RegistrationStyle()
{
// Fixed design values for font and rectangle.
PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
const float fontSize = 8F;
const float rightPadding = 3F;
TextAlignment textAlignment = TextAlignment.RIGHT;
iText.Kernel.Colors.Color borderColor = ColorConstants.RED;
iText.Kernel.Colors.Color fillColor = ColorConstants.WHITE;
const float borderWidth = 0.7F;
Style style = new Style()
.SetFont(font)
.SetFontSize(fontSize)
.SetPaddingRight(rightPadding)
.SetTextAlignment(textAlignment)
.SetBackgroundColor(fillColor)
.SetBorder(new SolidBorder(borderColor, borderWidth));
return style;
}