我正在使用 iTextSharp 生成 PDF 文档,并将它们保存到磁盘,如下所示:
Document document = new Document(PageSize.LETTER, 50, 50, 80, 50);
FileStream fs = new FileStream(Ruta, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
PdfWriter PDFWriter = PdfWriter.GetInstance(document, fs);
EsquemaFormato PageEventHandler = new EsquemaFormato();
PageEventHandler.Title = TitleMiddle;
PageEventHandler.TitleHeaderFont = FontFactory.GetFont(BaseFont.HELVETICA, 12, Font.NORMAL);
PageEventHandler.TitleRightHeaderFont = FontFactory.GetFont(BaseFont.HELVETICA, 9, Font.NORMAL);
PageEventHandler.HeaderLeft = "Nombre";
PageEventHandler.HeaderRight = TitleRight;
PageEventHandler.RutaImagen = RutaImagen;
PageEventHandler.Cuerpo = Cuerpo;
PDFWriter.PageEvent = PageEventHandler;
document.Open();
document.Close();
基于http://www.mazsoft.com/blog/post/2008/04/30/Code-sample-for-using-iTextSharp-PDF-library.aspx
我打开了我刚刚创建的任何 PDF 文件,但是当我尝试关闭它时会出现“您要保存吗?” 对话框出现。不是使用 iTextSharp 生成的 PDF 不会发生这种情况。
我错过了什么?我见过使用 Response 的解决方案,但我不使用它。提前致谢。
更新:这是一个示例http://dl.dropbox.com/u/4582874/test.pdf
编辑:通过关注布鲁诺的链接,我发现了这篇文章:iTextSharp + FileStream = Corrupt PDF file
那成功了!这是我现在的工作代码:
public void CreatePDF(string TitleMiddle, string Ruta, string RutaImagen, string TitleRight, string Cuerpo)
{
using (MemoryStream ms = new MemoryStream())
{
Document document = new Document(PageSize.LETTER, 50, 50, 80, 50);
PdfWriter PDFWriter = PdfWriter.GetInstance(document, ms);
EsquemaFormato PageEventHandler = new EsquemaFormato();
PageEventHandler.Title = TitleMiddle;
PageEventHandler.TitleHeaderFont = FontFactory.GetFont(BaseFont.HELVETICA, 12, Font.NORMAL);
PageEventHandler.TitleRightHeaderFont = FontFactory.GetFont(BaseFont.HELVETICA, 9, Font.NORMAL);
PageEventHandler.HeaderLeft = "Nombre";
PageEventHandler.HeaderRight = TitleRight;
PageEventHandler.RutaImagen = RutaImagen;
PageEventHandler.Cuerpo = Cuerpo;
PDFWriter.PageEvent = PageEventHandler;
document.Open();
document.Close();
byte[] content = ms.ToArray();
using (FileStream fs = File.Create(Ruta))
{
fs.Write(content, 0, (int)content.Length);
}
}
}