Sunday, 11 October 2015

PDF Watermark in MVC

Hello friends

In this example, we will learn how to add watermark to existing pdf file in Asp.net MVC.

To download this example Click here

Steps:
1.Add an empty MVC Project.
2.Add reference of itextsharp.dll assembly.
3.Add PdfWaterMark controller.
4.Create View For Index Action.
5.Following is the code in PdfWaterMarkController.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlogMVC.Models;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
namespace BlogMVC.Controllers
{
public class PdfWaterMarkController : Controller
{
//
// GET: /PdfWaterMark/
public ActionResult Index()
{
return View();
}
[HttpPost]
public FileResult Index(WatermarkViewModel model)
{
if (System.IO.File.Exists(Server.MapPath("~/Download/") + model.OutputFileName))
System.IO.File.Delete(Server.MapPath("~/Download/") + model.OutputFileName);
model.SourceFile.SaveAs(Server.MapPath("~/Download/") + Path.GetFileName(model.SourceFile.FileName));
string startFile = Server.MapPath("~/Download/") + Path.GetFileName(model.SourceFile.FileName);
string watermarkedFile = Server.MapPath("~/Download/") + model.OutputFileName;
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document produced by 1 no.
PdfReader reader1 = new PdfReader(startFile);
FileStream fs2 = new FileStream(watermarkedFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
// Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
PdfStamper stamper = new PdfStamper(reader1, fs2);
// Getting total number of pages of the Existing Document
int pageCount = reader1.NumberOfPages;
// Create New Layer for Watermark
PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
// Loop through each Page
for (int i = 1; i <= pageCount; i++)
{
// Getting the Page Size
Rectangle rect = reader1.GetPageSize(i);
// Get the ContentByte object
PdfContentByte cb = stamper.GetUnderContent(i);
// Tell the cb that the next commands should be "bound" to this new layer
cb.BeginLayer(layer);
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 35);
PdfGState gState = new PdfGState();
gState.FillOpacity = 0.2f;
cb.SetGState(gState);
cb.SetColorFill(BaseColor.BLACK);
cb.BeginText();
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, model.WaterMarkText, rect.Width / 2, rect.Height / 2, 45f);
cb.EndText();
// Close the layer
cb.EndLayer();
}
stamper.Close();
fs2.Close();
// Removing the layer created above
// 1. First we bind a reader to the watermarked file
// 2. Then strip out a branch of things
// 3. Finally use a simple stamper to write out the edited reader
PdfReader reader2 = new PdfReader(watermarkedFile);
// NOTE: This will destroy all layers in the Document, only use if you don't have any addtional layers
// Remove the OCG group completely from the Document: reader2.Catalog.Remove(PdfName.OCPROPERTIES);
// Clean up the reader, optional
reader2.RemoveUnusedObjects();
// Placeholder variables
PRStream stream;
string content;
PdfDictionary page;
PdfArray contentArray;
// Get the number of pages
int pageCount2 = reader2.NumberOfPages;
// Loop through each page
for (int i = 1; i <= pageCount2; i++)
{
// Get the page
page = reader2.GetPageN(i);
// Get the raw content
contentArray = page.GetAsArray(PdfName.CONTENTS);
if (contentArray != null)
{
// Loop through content
for (int j = 0; j < contentArray.Size; j++)
{
stream = (PRStream)contentArray.GetAsStream(j);
// Convert to a String, NOTE: you might need a different encoding here
content = System.Text.Encoding.ASCII.GetString(PdfReader.GetStreamBytes(stream));
//Look for the OCG token in the stream as well as our watermarked text
if (content.IndexOf("/OC") >= 0 && content.IndexOf(model.WaterMarkText) >= 0)
{
//Remove it by giving it zero length and zero data
stream.Put(PdfName.LENGTH, new PdfNumber(0));
stream.SetData(new byte[0]);
}
}
}
}
return File("~/Download/" + model.OutputFileName, System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName("~/Download/" + model.OutputFileName));
}
}
}
6.Following is the code in Index.cshtml.
@model BlogMVC.Models.WatermarkViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Index", "PdfWaterMark", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label>Source Pdf File:</label>
<input type="file" name="SourceFile" /><br /><br />
<label>Watermark Text:</label>
@Html.TextBoxFor(m => m.WaterMarkText)<br /><br />
<label>Output File Name:</label>
@Html.TextBoxFor(m => m.OutputFileName)
<br /><br />
<button type="submit">Download Watermark Pdf</button>
}
view raw Index.cshtml hosted with ❤ by GitHub
7.Add WaterMark class file in Models Folder with the following code.
public class WatermarkViewModel
{
public HttpPostedFileBase SourceFile { get; set; }
public string WaterMarkText { get; set; }
public string OutputFileName { get; set; }
}
view raw Watermark.cs hosted with ❤ by GitHub
8.Add Download folder in your solution to save and create the output file.
9.Following is the screen shots for your help.







If you have any queries regarding this example post ur comment or send mail to ranjeetpatil4545@gmail.com


Thank You