【问题标题】:ItextSharp - Add text watermark on separate linesItextSharp - 在单独的行上添加文本水印
【发布时间】:2018-06-27 17:05:50
【问题描述】:

我正在尝试使用 itextsharp 5.1.2.0 在 pdf 文件上添加水印。

我希望水印位于页面中心,呈 45° 角,这些线条周围有边框。

这是我的代码:

 for (int i = 1; i <= reader.NumberOfPages; i++)
{
    iTextSharp.text.Rectangle pageSize = reader.GetPageSizeWithRotation(i);

    PdfContentByte pdfPageContents;
    pdfPageContents = pdfStamper.GetOverContent(i);

    pdfPageContents.BeginText();
    PdfGState gstate = new PdfGState();
    gstate.FillOpacity = 0.4f;
    gstate.StrokeOpacity = 0.4f;
    pdfPageContents.SaveState();
    pdfPageContents.SetGState(gstate);

    BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, Encoding.ASCII.EncodingName, false);

    pdfPageContents.SetRGBColorFill(255, 0, 0);

    double radians = Math.Atan2(pageSize.Height, pageSize.Width);
    float textAngle = radians * (180 / Math.PI);

    pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Phrase 1 This is Phrase 2 and must be centered below phrase 1" , pageSize.Width / 2, pageSize.Height / 2, textAngle);
    //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Phrase 1", pageSize.Width / 2, pageSize.Height / 2, textAngle);
    //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "This is Phrase 2 and must be centered below phrase 1", pageSize.Width / 2 + 20 , pageSize.Height / 2 - 20, textAngle);
}

这会在一行上添加水印。

我可以有两行带有注释的代码。 我不喜欢的是第二行位置的硬编码值。 我相信一定有更好的方法来实现这一点。

关于边框我没有设法将它添加到线条周围。

如果有人可以帮我解决这个问题。 谢谢

【问题讨论】:

  • 您可以添加一个变量 lineHeight 并在该变量中指定行的高度。然后可以为下一行添加该变量...
  • 使用 iText 7 更容易。iText 5.2.1.0 日期为 2011 年 8 月,不再受支持。

标签: itext watermark


【解决方案1】:

基本上我为我的项目所做的如下......这里 font_size 和 style 是变量......还有 llx、lly、urx、ury 是坐标位置和大小的变量......在对齐变量中,你可以轻松设置对齐方式.... 对于不透明度,您的代码可以正常工作(您可以添加状态选项)

             Dim Font = New Font(arial, FONT_SIZE, STYLE, iTextSharp.text.Color.BLACK )


            dim text = GetRowValue(row, "CONTROL_MAP")
            Dim ct As ColumnText = New ColumnText(pdf_cb)
            ct.SetSimpleColumn(LLX, LLY, URX, URY, FONT_SIZE, ALIGNMENT)
            ct.SetText(New Paragraph(0, text, Font))
            ct.Go()

【讨论】:

  • 谢谢!我设法使用您提供的代码完成了它,并根据我的要求对其进行了修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-19
  • 1970-01-01
  • 2021-01-12
  • 2012-11-01
  • 2018-07-12
  • 1970-01-01
相关资源
最近更新 更多