java itextsharp_使用iTextSharp生成PDF

您提供的代码示例甚至输出PDF吗?它看起来像你尝试了许多不同的方式来添加条形码图像,结果是多余的代码混淆了事情......它让我很困惑;-)

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

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 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值