Adding watermark to razorpdf mvc

2.1k Views Asked by At

I am using the following code to generate pdf in mvc using itext with razorpdf producer

@model myModel.Models.Examform
@{
    Layout = null;
}
<itext creationdate="@DateTime.Now.ToString()" producer="RazorPDF">
    Hello
</text>

This code works fine. I want to add a watermark to the generated pdf. I know how to add the image. I need a watermark which shows in the background.

3

There are 3 best solutions below

4
On

this is pretty much the exact same question

ItextSharp - RazorPdf put image on Pdf

so using the answer there should work for you:

<image url="@Context.Server.MapPath("~/Images/sampleImage.png")" />

Edit: To overlay text on the image, you need to modify your CSS and HTML.

How to position text over an image in css

Add "Watermark" effect with CSS?

http://www.the-art-of-web.com/css/textoverimage/

You might need to put the CSS inline.

0
On

I think it is not possible via markup.

If you have a look at PdfView.cs in RazorPDF source code, it uses XmlParser or HtmlParser in iTextsharpt to render pdf.

https://github.com/RazorAnt/RazorPDF/blob/master/RazorPDF/PdfView.cs

The support of markups in these two classes are limited. You can only do what they have implemented.

The alternative way is to use iTextsharp to create pdf via code.

0
On

Here is what I have done. The code goes in the controller.

[HttpPost]
public FileStreamResult Certificate(MyModel model)
{
    Stream fileStream = GeneratePDF(model);
    HttpContext.Response.AddHeader("content-disposition", "inline; filename=Certificate.pdf");

    var fileStreamResult = new FileStreamResult(fileStream, "application/pdf");
    return fileStreamResult;
}

public Stream GeneratePDF(HomeViewModel model)
{ 
    var rect = new Rectangle(288f, 144f);
    var doc = new Document(rect, 0, 0, 0, 0);

    BaseFont bfArialNarrow = BaseFont.CreateFont(Server.MapPath("../Content/fonts/ARIALN.ttf"), BaseFont.CP1252, BaseFont.EMBEDDED);

    //Full Background Image (Includes watermark)
    Image fullBackground = null;
    fullBackground = Image.GetInstance(Server.MapPath("../Content/images/Certificate/Cert1.jpg"));

    doc.SetPageSize(PageSize.LETTER.Rotate());

    MemoryStream memoryStream = new MemoryStream();
    PdfWriter pdfWriter = PdfWriter.GetInstance(doc, memoryStream);
    doc.Open();

    //Full Background Image
    fullBackground.Alignment = Image.UNDERLYING | Image.ALIGN_CENTER | Image.ALIGN_MIDDLE;
    doc.Add(fullBackground);

    Font myFont = new Font(bfArialNarrow, 57);
    var myParagraph = new Paragraph("Some text here.", myFont);
    doc.Add(myParagraph);

    pdfWriter.CloseStream = false;
    doc.Close();

    memoryStream.Position = 0;

    return memoryStream;
}