Adding watermark to razorpdf mvc
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 an image. I need a watermark that is displayed in the background.
This is almost the same question
ItextSharp - RazorPdf put image to Pdf
so using the answer you should be working:
<image url="@Context.Server.MapPath("~/Images/sampleImage.png")" />
Edit: In order to overlay text on an image, you need to change your CSS and HTML.
How to place text over image in css
Add Watermark Effect With CSS?
http://www.the-art-of-web.com/css/textoverimage/
You may need to inline CSS.
Here's what I did. 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;
}
I think this is not possible with markup.
If you look at the PdfView.cs in the RazorPDF source, it uses the XmlParser or HtmlParser in iTextsharpt to render the pdf.
https://github.com/RazorAnt/RazorPDF/blob/master/RazorPDF/PdfView.cs
Markup support in these two classes is limited. You can only do what they have implemented.
An alternative way is to use iTextsharp to generate pdf through code.