News Ticker

Menu

Sử dụng iTextSharp để thêm Watermark vào file PDF trong Asp.net

(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.


Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET


B1: Tạo Project trong Microsoft Visual Studio 2010

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#
<%@ Page Title="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>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <asp:label id="lblHeader" runat="server" Text="Add Watermark to PDF Using iTextSharp in ASP.NET"></asp:label>
                    </div>
                    <div class="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:RequiredFieldValidator ID="valWatermarkText" CssClass="NormalRed" ValidationGroup="Text" runat="server" ErrorMessage="Enter Watermark Text" ControlToValidate="txtWatermarkText"></asp:RequiredFieldValidator>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="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>&nbsp;&nbsp;<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>&nbsp;&nbsp;<asp:label id="Label1" runat="server" Text="Add Image"></asp:label>
                            </asp:LinkButton>
                        </div>
                    </div>
                </div>
            </td>
        </tr>       
    </table>
</asp:Content>
VB.NET Code

<%@ Page Title="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>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <asp:label id="lblHeader" runat="server" Text="Add Watermark to PDF Using iTextSharp in ASP.NET"></asp:label>
                    </div>
                    <div class="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:RequiredFieldValidator ID="valWatermarkText" CssClass="NormalRed" ValidationGroup="Text" runat="server" ErrorMessage="Enter Watermark Text" ControlToValidate="txtWatermarkText"></asp:RequiredFieldValidator>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="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>&nbsp;&nbsp;<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>&nbsp;&nbsp;<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 void AddWatermarkToPDFUsingiTextSharp(string FileName, bool IsText)
        {
            Document oDoc = new Document(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 void cmdInsert_Click(object sender, System.EventArgs e)
        {
            AddWatermarkToPDFUsingiTextSharp("AddWatermark",true);
        }

        protected void cmdInsertImage_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 Sub AddWatermarkToPDFUsingiTextSharp(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 As PdfWriter = 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 Sub cmdInsertText_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdInsertText.Click
            AddWatermarkToPDFUsingiTextSharp("AddWatermark", True)
        End Sub

        Private Sub cmdInsertImage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdInsertImage.Click
            AddWatermarkToPDFUsingiTextSharp("AddWatermark", False)
        End Sub

#End Region

    End Class

End Namespace

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




Chúc các bạn thành công!

Quang Bình

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Sử dụng iTextSharp để thêm Watermark vào file PDF trong Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM