Generate PDF with iTextSharp

12,668

Solution 1

does the code sample you provided even output a PDF? it looks like you tried a number of different ways to add the barcode image and ended up with excess code that confused things...it confused me ;-)

anyway here's one way to achieve your goal with PdfStamper like you tried; example HTTP Handler (.ashx):

<%@ WebHandler Language='C#' Class='addBarcodeWithStamper' %>
using System;
using System.IO;
using System.Web;
using iTextSharp.text;  
using iTextSharp.text.pdf; 

public class addBarcodeWithStamper : IHttpHandler {
  public void ProcessRequest (HttpContext context) {
    HttpResponse Response = context.Response;
    Response.ContentType = "application/pdf";
    PdfReader reader = new PdfReader(context.Server.MapPath(PATH_TO_PDF));
/*
 * save __one__ instance of barcode image;
 * see MakeBarcode() method below
 */
    iTextSharp.text.Image barcode = null;
    float barcodeWidth = 0;
    float barcodeHeight = 0;
    using (PdfStamper stamper = new PdfStamper(reader, Response.OutputStream)) 
    {
      int n = reader.NumberOfPages;
      for (int i = 1; i <= n; i++) {
        PdfContentByte cb = stamper.GetOverContent(i);
/*
 *  re-use image bytes so they are added only __once__
 */
        if (barcode == null) {
          barcode = MakeBarcode(cb);
          barcodeWidth= barcode.Width;
          barcodeHeight= barcode.Height;
        }
/*
 * calculate in case individual page sizes are different
 */
        Rectangle rect = stamper.Reader.GetPageSize(i);
        float x = (rect.Width - barcodeWidth) / 2;
// modify/remove 10 offset as you see fit
        float y = rect.Top - barcodeHeight - 10;
        barcode.SetAbsolutePosition(x, y);
        cb.AddImage(barcode);
      }    
    }
  }
  public bool IsReusable {
    get { return false; }
  }
// ----------------------------------------------------------------------------  
  public iTextSharp.text.Image MakeBarcode(PdfContentByte cb) {
    Barcode128 barcode128 = new Barcode128();
    string text2 = "650-M5-013";
    barcode128.Code = text2;
    barcode128.ChecksumText = true;        
    return barcode128.CreateImageWithBarcode(cb, null, null);  
  }
}

obviously you need to change PATH_TO_PDF above to the actual path of the PDF. there are also other ways to achieve the same goal. for example using PdfPageEventHelper.

Solution 2

take a look at this;

http://www.mikesdotnetting.com/Article/87/iTextSharp-Working-with-images

Also this for all itextsharp related posts;

http://www.mikesdotnetting.com/Category/20

Share:
12,668

Related videos on Youtube

matcha
Author by

matcha

Updated on May 27, 2022

Comments

  • matcha
    matcha about 2 years

    I am trying to add an image to the top of every page on an existing PDF. I have tried using PdfStamp but for some reason when I try to print the pdf from Chrome all I get is a black page. Also Adobe Reader only shows the original document. Does anyone have any ideas on how to get it working? Here is the code.

    public partial class MakePdf : System.Web.UI.Page
    {
        public MemoryStream m = new MemoryStream();
        protected void Page_Load(object sender, EventArgs e)
        {
            Document document = new Document(PageSize.LETTER);
    
            Response.ContentType = "application/pdf";
            string RESULT = @"C:\Users\maitchison\Documents\Pdf\Service Report Search - 650-10-067 4114.pdf";
            PdfReader reader = new PdfReader(RESULT);
            PdfStamper stamp = new PdfStamper(reader, m);
            try
            {
                // Set ContentType and create an instance of the Writer.
    
                Response.ContentType = "application/pdf";
                PdfWriter writer = PdfWriter.GetInstance(document, m);
                writer.CloseStream = false;
    
                // Open Document
    
                document.Open();
    
                int n = reader.NumberOfPages;
                int i = 1;
    
                PdfContentByte cb = writer.DirectContent;
                PdfContentByte over;
    
                Barcode128 barcode128 = new Barcode128();
                string text2 = "650-M5-013";
                barcode128.Code = text2;
                barcode128.ChecksumText = true;
                float x = document.Right;
                float y = document.Top;
                iTextSharp.text.Image img2 = barcode128.CreateImageWithBarcode(cb, null, null);
    
                img2.SetAbsolutePosition((x - img2.ScaledWidth), (y - img2.ScaledHeight));
    
                while (i <= n)
                {
                    over = stamp.GetOverContent(i);
                    over.AddImage(img2);
    
                    i++;
    
                }
    
            }
    
            catch (DocumentException ex)
            {
                Console.Error.WriteLine(ex.StackTrace);
                Console.Error.WriteLine(ex.Message);
            }
    
            // Close document
            stamp.Close();
            //document.Close();
    
            // Write pdf bytes to outputstream.
    
            Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
            m.Close();
    
    
        }
    
    
    }
    

    }

  • matcha
    matcha about 13 years
    I have actually already read them. I can write the image to the PDF and print it with no problem until I try to use PdfStamper.
  • tugberk
    tugberk about 13 years
    no idea what PdfStamper is :S maybe the problem is wşth PdfStamper? I have used iTextSharper for some project couple of months ago and never had that problem with images.
  • matcha
    matcha about 13 years
    PdfStamper is used to put content over other content. If I don't use it I can't see the images at all.
  • matcha
    matcha about 13 years
    Thanks for the help. This works perfectly and I also understand how it all works now. I just started with c# a few weeks ago so I am having lots of issues.