使用iTextSharp生成PDF

时间:2011-04-01 21:10:19

标签: c# asp.net pdf itext barcode

我正在尝试将图像添加到现有PDF的每个页面的顶部。我尝试过使用PdfStamp,但出于某种原因,当我尝试从Chrome打印pdf时,我得到的是一个黑页。 Adobe Reader也只显示原始文档。有没有人对如何使其工作有任何想法?这是代码。

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();


    }


}

}

2 个答案:

答案 0 :(得分:5)

您提供的代码示例是否输出PDF?看起来你尝试了许多不同的方法来添加条形码图像,并最终得到了混淆事物的多余代码......它让我感到困惑; - )

无论如何,这是使用PdfStamper实现目标的一种方式,就像你尝试过的那样;示例HTTP Handler(。atx):

<%@ 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);  
  }
}

显然,您需要将上面的 PATH_TO_PDF 更改为PDF的实际路径。还有其他方法可以实现相同的目标。例如,使用PdfPageEventHelper

答案 1 :(得分:1)