iTextSharp 正在生成带有响应的损坏 PDF
Posted
技术标签:
【中文标题】iTextSharp 正在生成带有响应的损坏 PDF【英文标题】:iTextSharp is producing a corrupt PDF with Response 【发布时间】:2014-07-30 09:27:50 【问题描述】:两个都试了,还是不行
iTextSharp + FileStream = Corrupt PDF file
iTextSharp is producing a corrupt PDF
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
//abre o documento para poder editar
document.Open();
//Adiciona os campos de assinatura
document.Add(Assinatura());
//fecha o documento ao finalizar a edição
document.Close();
//Prepara o download
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.ContentType = "image/pdf";
//Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;
filename=ControleDePonto.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
Response.Close();
我做错了什么?
【问题讨论】:
application/pdf
是正确的 MIME 类型。见this question。顺便结束 Response 之后就不用关闭了。
我也试过了,但没有成功
刚刚注意到,您永远不会将document
中的信息传递到您的内存流中。
没关系,我只是放置了“PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);”在错误的线路上
【参考方案1】:
使用 PdfWriter 将 PDF 写入 MemoryStream。
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
//Adiciona os campos de assinatura
document.Add(Assinatura());
//fecha o documento ao finalizar a edição
document.Close();
//Prepara o download
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=ControleDePonto.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
【讨论】:
Assinatura()
返回什么?
@rar 如果您想联系 OP,请使用 @ 语法。以上是关于iTextSharp 正在生成带有响应的损坏 PDF的主要内容,如果未能解决你的问题,请参考以下文章
iTextSharp + FileStream = 损坏的 PDF 文件