Itext7 overContent 替换为 PdfCanvas

Itext7 overContent replaced with PdfCanvas

我不确定如何将此文本添加到 iText7 中的 canvas。在旧版本中我使用这个 BaseFont.CreateFontoverContent。在 iText7 中,我看到了这个 PdfCanvas 控件和这个 PdfCanvas.BeginText 方法,但是我收到了一个与 no overoad 相关的错误。

  PdfPage pdfPage = pdfDocument.GetPage(i);
  Rectangle pageSizeWithRotation = pdfPage.GetPageSizeWithRotation();

  PdfCanvas canvas = new PdfCanvas(pdfPage);

  Text pdfText = new Text(disclaimerText)
  .SetFontColor(ColorConstants.BLACK)
  .SetFont(PdfFontFactory.CreateFont(StandardFonts.HELVETICA, "Cp1250"))
  .SetFontSize(7F);

  canvas.BeginText(pdfText);

旧版本我有这样的东西

PdfContentByte overContent = pdfStamper.GetOverContent(i);
overContent.BeginText();
BaseFont baseFont = BaseFont.CreateFont("Helvetica", "Cp1250", false);
overContent.SetFontAndSize(baseFont, 7F);
overContent.SetRGBColorFill(0, 0, 0);
float n2 = 15F;
float n3 = pageSizeWithRotation.Height - 10F;

overContent.ShowTextAligned(0, disclaimerText, n2, n3, 0F);
                                   
overContent.EndText();

您可以参考以下代码了解BeginText和EndText如何与PdfCanvas协同工作。

//Get the page from the pdf
PdfPage page = pdfDoc.GetPage(i);
Rectangle pageSize = page.GetPageSizeWithRotation();
int pageNumber = pdfDoc.GetPageNumber(page);
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
//Set background
Color limeColor = new DeviceCmyk(0.208 f, 0, 0.584 f, 0);
Color blueColor = new DeviceCmyk(0.445 f, 0.0546 f, 0, 0.0667 f);
pdfCanvas.SaveState()
  .SetFillColor(pageNumber % 2 == 1 ? limeColor : blueColor)
  .Rectangle(pageSize.GetLeft(), pageSize.GetBottom(),
    pageSize.GetWidth(), pageSize.GetHeight())
  .Fill()
  .RestoreState();
//Add header and footer
pdfCanvas.BeginText()
  .SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.HELVETICA), 9)
  .MoveText(pageSize.GetWidth() / 2 - 60, pageSize.GetTop() - 20)
  .ShowText("THE TRUTH IS OUT THERE")
  .MoveText(60, -pageSize.GetTop() + 30)
  .ShowText(pageNumber.ToString())
  .EndText();

//Add watermark
iText.Layout.Canvas canvas = new iText.Layout.Canvas(pdfCanvas, pdfDoc, page.GetPageSize());
canvas.SetProperty(Property.FONT_COLOR, Color.WHITE);
canvas.SetProperty(Property.FONT_SIZE, 60);
canvas.SetProperty(Property.FONT, PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD));
canvas.ShowTextAligned(new Paragraph("CONFIDENTIAL"), 298, 421, pdfDoc.GetPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
pdfCanvas.Release();

此示例也可在 iText 7 的知识库中找到,位于 https://kb.itextpdf.com/home/it7kb/examples/itext-7-jump-start-tutorial-chapter-3 示例“c03e03_ufo”