Watermarking PDF documents using httphandlers

Source: Internet
Author: User
Tags adobe acrobat reader
ArticleDirectory
    • Itextsharp
    • PDF Handler
    • Test Web Application
    • Demo
    • Summary
    • References
Watermarking PDF documents using httphandlers

Published:03 Oct 2007
By:Deepak Raghavan
Download Sample Code

This article shows how to watermark PDFs using the open source PDF generation library itextsharp, C #, and ASP. NET.

Introduction

Often enough, web applications usePDFDocumentsWhich may be printable versions of pages, Custom forms, manuals etc. when the document consists of critical or sensitive information, the pages are watermarked with the company logo or some other custom image file. there are some off-the-shelf implements cial products which have this feature. this article looks at such an implementation using the open source PDF generation library itextsharp, C #, and ASP. net.

Using HTTP handlers

when a client sends an HTTP request to the browser, the IIS on the webserver gets to see it first. if the requested resource has. aspx ,. asmx, or. ashx extension, the request is routed to. net engine as these files are registered with IIS to be handled by the ASP. net runtime engine. at this point, the request passes through the ASP. net HTTP pipeline. the first step is to process the request through an array of HTTP modules such as caching, authentication, authorization, sesssionstate; before associating it with a httphandler endpoint. the. net runtime processes the request through multiple modules and sends it to an httphandler factory. the factory chooses an appropriate handler depending on the file extension, which is used to create the output response. the response can be HTML output in the case of. aspx request, soap response in the case of. asmx request and custom handling of the request in the case of. ashx request.

When a PDF file is requested through a browser, IIS is responsible to handle the request and, for example, invokes the Adobe Acrobat Reader to launch the requested file. in the current article, we want to intercept the PDF file requested, add a watermark to it and render it over the browser. if such a custom behavior is desired, we can perform the following steps:

    • Register. pdf file types within the web application with. Net Runtime
    • Create a Custom Handler inheritingIhttphandlerTo process the. pdf requests
    • Let the Web. config file know that we have a Custom Handler in place for. PDF files.
Itextsharp

Itextsharp is an open source. net port of the itext library used for Java applications. the library can be used to automate PDF creation and/or manipulation. in the current article, the itextsharp API is used within the custom HTTP handler to intercept the PDF request, read the PDF stream, add an image to it and stream it back to the browser.

PDF Handler

All custom handlers shoshould implementIhttphandlerInterface shown below.

View sourceprint? 1. Public Interface Ihttphandler 2. { 3. Bool Isreusable { Get ;} 4.    5. Void Processrequest (httpcontext context ); 6. }

TheIhttphandlerInterface has two methods to be implemented.

    • IsresuableIndicates whetherIhttphandlerInstance is reusable
    • ProcessrequestHas the main implementation for the associated request type

To create a custom handler, a class library is created within Visual Studio 2005 and a class (Pdfhandler) Is added to it which implementsIhttphandler. The source codePdfhandlerImplementation is shown below

Listing 2: Using handler implementing ihttphandler view sourceprint? 01. /// <Summary> 02. /// Reads the requested PDF file, adds the watermark and streams the modified PDF file. 03. /// </Summary> 04. /// <Param name = "context"> </param> 05. Public Void Processrequest (httpcontext context) 06. { 07. Memorystream outputstream = New Memorystream (); 08. Pdfreader = New Pdfreader (context. Request. physicalpath ); 09. Int Numberofpages = pdfreader. numberofpages; 10. Optional Stamper = New Pdfstamper (pdfreader, outputstream ); 11. Protected contentbyte watermarkcontent; 12. Image image = image. getinstance (context. server. mappath ( "Watermark.jpg" )); 13. Image. setabsoluteposition (250,300 ); 14. For ( Int I = 1; I <= numberofpages; I ++) 15. { 16. Watermarkcontent = effecstamper. getundercontent (I ); 17. Watermarkcontent. addimage (image ); 18. } 19. Pdfstamper. Close (); 20. Byte [] Content = outputstream. toarray (); 21. Outputstream. Close (); 22. Context. response. contenttype = "Application/pdf" ; 23. Context. response. binarywrite (content ); 24. Context. response. End (); 25. } 26. /// <Summary> 27. /// Marks the handler reusable into SS multiple requests 28. /// </Summary> 29. Public Bool Isreusable 30. { 31. Get 32. { 33. Return True ; 34. } 35. }

The classes used inProcessrequestMethod and their brief descriptions are listed in the table below:

Table 1: classes within itextsharp API and their descriptions
Class Name Usage description
Pdfreader Reads and parses a PDF document at the provided URL string
Pdfstamper Used to add new content to multiple pages of a document. The content is an instance of your contentbyte
Pdfcontentbyte Object containing user positioned text and/or graphics on a pdf page.

In the previous listing,IsreusableProperty always returnsTrue. This means that a singlePdfhandlerInstance can be used to process multiple concurrent requests (from different clients) served on multiple worker threads. This is possible because we don't have common shared resources or data processing SS multiple requests.

Test Web Application

The following steps are followed to create the demo web application:

    • Create a new web site in your choice of directory and name it testpdfrender.
    • Add the binary output of the Custom Handler as a reference
    • Add the image used for watermarking purposes. We have used the sample image provided on the itextsharp website, but this can be replaced by any image of choice.
    • Modify the Web. config file with the following code. The path is set to A. pdf file andVerb = "*"Means that the handler is used into SS get, post, head. Trace, and debug operations.
View sourceprint? 1. < Httphandlers > 2. < Add Verb = "*" Path = "*. Pdf"  3. Type = "Handlers. Handler, handlers" /> 4. </ Httphandlers >
    • Create a virtual directory within IIS called testpdfrender and point it to the website.
    • In the Project Properties of testpdfrenderer, within start options, set the server section to "use custom server" and set the base URL to the location of this test web site within IIS (in our case, it is http: // localhost/testpdfrender ).
    • To map. PDF extension through IIS: within IIS, right click on testpdfrender-> properties-> under virtual directory tab, click on configuration-> Add a new extension with extension. PDF and set executable to. net Runtime ("C: \ WINDOWS \ microsoft.net \ framework \ v2.0.50727 \ aspnet_isapi.dll"), keep the rest of the sections to their default values. click on OK to close all the Open configuration windows.
Demo

The application is ready to be tested. The sample code files need ded use a test PDF document and an image file which can be replaced. Open "default. aspx" and add this test hyperlink control:

View sourceprint? 1. < ASP: hyperlink ID = "Hyperlink1" Runat = "Server" Navigateurl = "Testbench" 2. Target = "_ Blank" > Pdf document </ ASP: hyperlink >

Now, set default. aspx to be the start page. when the link is clicked the demo file shows the image watermarked in the center. the actual position of the image can be altered by changing the coordinates in Listing 1, withinProcessrequestMethod:

View sourceprint? 1. Image. setabsoluteposition (250,300 ); Summary

In this article we have seen how to implement a custom httphandler to watermark PDF documents. The meat of the implementation is withinProcessrequestMETHOD WITHPdfhandler. This handler can be used using SS multiple Web applications if the handler is registered through IIS and referenced within the web. config file.

References
    • Http://itextsharp.sourceforge.net/
    • Http://itext.ugent.be/library/api/

From: http://dotnetslackers.com/articles/aspnet/WatermarkingPDFDocumentsUsingHttpHandlers.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.