(How to add Watermark in PDF file using iTextSharp in ASP.NET) – Để bảo vệ bản quyền tác giả đối với các tài liệu khi xuất bản, tác giả thường sử dụng chức năng Watermark. Khi chèn Watermark vào tài liệu, dòng chữ này sẽ hiển thị mờ ở nền mà không ảnh hưởng đến nội dung. Bài viết dưới đây,chúng tôi sẽ giới thiệu với các bạn cách sử dụng thư viện iTextSharp để chèn Watermark vào file PDF. Chương trình sẽ cho phép người sử dụng 1 trong 2 cách đó là sử dụng ký tự (Text) hoặc sử dụng hình ảnh (Image) để chèn Watermark.
- B2: Download thư viện iTextSharp tại đây
- B3: References itextsharp.dll trong thư mục vừa giải nén vào Project.
- B4: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ PageTitle="Add Watermark to PDF Using iTextSharp in ASP.NET" Language="C#"MasterPageFile="~/Site.master"AutoEventWireup="true"CodeBehind="Default.aspx.cs"Inherits="AddWatermarkToPDFUsingiTextSharp._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table cellpadding="3"cellspacing="5"border="0"width="50%">
<tr>
<td>
<divclass="panel panel-default">
<divclass="panel-heading">
<asp:label id="lblHeader" runat="server" Text="Add Watermark to PDF Using iTextSharp in ASP.NET"></asp:label>
</div>
<divclass="panel-body">
<table cellspacing="2"cellpadding="3"border="0"width="100%">
<tr>
<td style="width:25%;" valign="top">
<asp:Label ID="plWatermarkText"runat="server"Text="WatermarkText"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtWatermarkText"CssClass="form-control"Width="280px"runat="server"></asp:TextBox>
<asp:RequiredFieldValidatorID="valWatermarkText"CssClass="NormalRed"ValidationGroup="Text"runat="server"ErrorMessage="Enter Watermark Text" ControlToValidate="txtWatermarkText"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
</div>
<divclass="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdInsert"runat="server"CssClass="btn btn-small" ValidationGroup="Text" OnClick="cmdInsert_Click" Causesvalidation="true">
<i class="icon-insert"></i> <asp:label id="lblInsert" runat="server" Text="Add"></asp:label>
</asp:LinkButton>
<asp:LinkButton id="cmdInsertImage"runat="server"CssClass="btn btn-small" OnClick="cmdInsertImage_Click" Causesvalidation="true">
<i class="icon-insert"></i> <asp:label id="Label1" runat="server" Text="Add Image"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</td>
</tr>
</table>
</asp:Content>VB.NET Code
<%@ PageTitle="Add Watermark to PDF Using iTextSharp in ASP.NET" Language="vb"MasterPageFile="~/Site.Master"AutoEventWireup="false"CodeBehind="Default.aspx.vb"Inherits="AddWatermarkToPDFUsingiTextSharp._Default"%>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table cellpadding="3"cellspacing="5"border="0"width="50%">
<tr>
<td>
<divclass="panel panel-default">
<divclass="panel-heading">
<asp:label id="lblHeader" runat="server" Text="Add Watermark to PDF Using iTextSharp in ASP.NET"></asp:label>
</div>
<divclass="panel-body">
<table cellspacing="2"cellpadding="3"border="0"width="100%">
<tr>
<td style="width:25%;" valign="top">
<asp:Label ID="plWatermarkText"runat="server"Text="WatermarkText"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtWatermarkText"CssClass="form-control"Width="280px"runat="server"></asp:TextBox>
<asp:RequiredFieldValidatorID="valWatermarkText"CssClass="NormalRed"ValidationGroup="Text"runat="server"ErrorMessage="Enter Watermark Text" ControlToValidate="txtWatermarkText"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
</div>
<divclass="modal-footer">
<div class="btn-group">
<asp:LinkButton id="cmdInsertText"runat="server"CssClass="btn btn-small" ValidationGroup="Text" Causesvalidation="true">
<i class="icon-insert"></i> <asp:label id="lblInsert" runat="server" Text="Add Text"></asp:label>
</asp:LinkButton>
<asp:LinkButton id="cmdInsertImage"runat="server"CssClass="btn btn-small" Causesvalidation="true">
<i class="icon-insert"></i> <asp:label id="Label1" runat="server" Text="Add Image"></asp:label>
</asp:LinkButton>
</div>
</div>
</div>
</td>
</tr>
</table>
</asp:Content>- B5: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web;
using iTextSharp.text.html;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace AddWatermarkToPDFUsingiTextSharp
{
public partial class _Default : System.Web.UI.Page
{
#region"Add Watermark"
private voidAddWatermarkToPDFUsingiTextSharp(stringFileName, bool IsText)
{
Document oDoc = newDocument(PageSize.A4, 20f, 20f, 30f, 20f);
oDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
System.IO.MemoryStream msReport = new System.IO.MemoryStream();
string WatermarkText = "www.laptrinhdotnet.com";
string ImagePath = Server.MapPath("Images\\dotnet.jpg");
float fontSize = 45;
float xPosition = (iTextSharp.text.PageSize.A4.Width + 320f) / 2;
float yPosition = (iTextSharp.text.PageSize.A4.Height - 220f) / 2;
float angle = 45;
BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
try
{
PdfWriter writer = PdfWriter.GetInstance(oDoc, msReport);
oDoc.AddAuthor("laptrinhdotnet.com");
oDoc.AddSubject("Add Watermark To PDF");
oDoc.Open();
PdfContentByte ContentUnder = writer.DirectContentUnder;
if (IsText)
{
if (!string.IsNullOrEmpty(txtWatermarkText.Text))
{
WatermarkText = txtWatermarkText.Text.Trim();
}
xPosition = (iTextSharp.text.PageSize.A4.Width + 320f) / 2;
yPosition = (iTextSharp.text.PageSize.A4.Height - 220f) / 2;
ContentUnder.BeginText();
ContentUnder.SetColorFill(iTextSharp.text.pdf.CMYKColor.LIGHT_GRAY);
ContentUnder.SetFontAndSize(baseFont, fontSize);
ContentUnder.ShowTextAligned(PdfContentByte.ALIGN_CENTER, WatermarkText, xPosition, yPosition, angle);
ContentUnder.EndText();
}
else
{
if (File.Exists(ImagePath))
{
xPosition = (iTextSharp.text.PageSize.A4.Width) / 2;
yPosition = (iTextSharp.text.PageSize.A4.Height - 220f) / 2;
Image pdfImage = Image.GetInstance(ImagePath);
pdfImage.SetAbsolutePosition(xPosition, yPosition);
ContentUnder.AddImage(pdfImage);
}
}
}
catch
{
}
oDoc.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(msReport.ToArray());
Response.End();
}
#endregion
#region"Event Handles"
protected voidcmdInsert_Click(object sender, System.EventArgs e)
{
AddWatermarkToPDFUsingiTextSharp("AddWatermark",true);
}
protected voidcmdInsertImage_Click(object sender, System.EventArgs e)
{
AddWatermarkToPDFUsingiTextSharp("AddWatermark", false);
}
#endregion
}
}VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports iTextSharp.text.html
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports System.IO
Namespace AddWatermarkToPDFUsingiTextSharp
Public Class _Default
Inherits System.Web.UI.Page
#Region "Add Watermark"
Private SubAddWatermarkToPDFUsingiTextSharp(ByVal FileName As String, ByVal IsText As Boolean)
Dim oDoc As New Document(PageSize.A4.Rotate, 20, 20, 30, 20)
oDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate())
Dim msReport As New System.IO.MemoryStream()
Dim WatermarkText As String = "www.laptrinhdotnet.com"
Dim fontSize As Single = 45
Dim xPosition As Single = 0
Dim yPosition As Single = 0
Dim angle As Single = 45
Dim ImagePath As String = Server.MapPath("Images\dotnet.jpg")
Dim baseFont As BaseFont = baseFont.CreateFont(baseFont.HELVETICA, baseFont.WINANSI, baseFont.EMBEDDED)
Try
Dim writer AsPdfWriter = PdfWriter.GetInstance(oDoc, msReport)
oDoc.AddAuthor("laptrinhdotnet.com")
oDoc.AddSubject("Add Watermark To PDF")
oDoc.Open()
Dim ContentUnder As PdfContentByte = writer.DirectContentUnder
If IsText Then
xPosition = (iTextSharp.text.PageSize.A4.Width + 320.0F) / 2
yPosition = (iTextSharp.text.PageSize.A4.Height - 220.0F) / 2
If txtWatermarkText.Text <> "" Then
WatermarkText = txtWatermarkText.Text.Trim
End If
With ContentUnder
.BeginText()
.SetColorFill(iTextSharp.text.pdf.CMYKColor.LIGHT_GRAY)
.SetFontAndSize(baseFont, fontSize)
.ShowTextAligned(PdfContentByte.ALIGN_CENTER, WatermarkText, xPosition, yPosition, angle)
.EndText()
End With
Else
If File.Exists(ImagePath) Then
xPosition = (iTextSharp.text.PageSize.A4.Width) / 2
yPosition = (iTextSharp.text.PageSize.A4.Height - 220.0F) / 2
Dim pdfImage As Image = Image.GetInstance(ImagePath)
pdfImage.SetAbsolutePosition(xPosition, yPosition)
ContentUnder.AddImage(pdfImage)
End If
End If
Catch e As Exception
Console.Error.WriteLine(e.Message)
End Try
oDoc.Close()
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=" & FileName & ".pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(msReport.ToArray())
Response.End()
End Sub
#End Region
#Region "Event Handles"
Private SubcmdInsertText_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdInsertText.Click
AddWatermarkToPDFUsingiTextSharp("AddWatermark", True)
End Sub
Private SubcmdInsertImage_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdInsertImage.Click
AddWatermarkToPDFUsingiTextSharp("AddWatermark", False)
End Sub
#End Region
End Class
End Namespace
Chúc các bạn thành công!
Quang Bình
0 comments Blogger 0 Facebook
Post a Comment