0

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);
            }
        }
    }
4

1 に答える 1

0

FileAccess.ReadWrite、FileShare.ReadWrite プロパティなしで試しましたか?

私は毎日 itextSharp を使用して PDF を作成していますが、この問題に遭遇したことはありません。あなたのコードと私のコードの主な違いは、私がこれらを持っていないことです。

FileShare が文書を開いたままにして、誰かが最終的に保存して閉じるのを待っているのではないでしょうか?

于 2012-10-24T19:00:51.733 に答える