首页 > 解决方案 > ItextSharp - 在单独的行上添加文本水印

问题描述

我正在尝试使用 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);
}

这会在一行上添加水印。

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

关于边界,我没有设法在线条周围添加它。

如果有人可以帮助我处理这个案子。谢谢

标签: itextwatermark

解决方案


基本上我为我的项目所做的如下......这里 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()

推荐阅读