问题
I am using iTextSharp to generate PDF documents, and save them to disk like this:
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();
Based on http://www.mazsoft.com/blog/post/2008/04/30/Code-sample-for-using-iTextSharp-PDF-library.aspx
I open any PDF file I just created, but when I try to close it causes a "Do you want to Save?" dialog to appear. This does not happen with PDFs that are not generated with iTextSharp.
What am I missing? I've seen solutions using Response but I don´t use it. Thanks in advance.
Update: Here is a sample http://dl.dropbox.com/u/4582874/test.pdf
EDIT: By following Bruno's link I found this post: iTextSharp + FileStream = Corrupt PDF file
That did the trick! Here is my working code now:
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);
}
}
}
回答1:
Have you tried it without the FileAccess.ReadWrite, FileShare.ReadWrite properties?
I create PDF's using itextSharp everyday and have never ran into this issue - main difference between your code and mine is i don't have these.
I suspect the FileShare is leaving the document somewhat open, waiting for someone to finalise closing it with a save?
来源:https://stackoverflow.com/questions/13054893/itextsharp-generated-pdfs-cause-save-dialog-when-closing