Пытаетесь открыть PDF после его создания с помощью iTextSharp, но не можете заставить его работать?

У меня есть кнопка при нажатии, вставляет текст в поля формы в pdf и сохраняет заполненный pdf в каталог. Когда я закончу редактирование pdf, я хочу открыть pdf в браузере, но Process.Start() не работает. Есть ли лучший способ сразу же показать PDF-файл после его создания? Вот код кнопки:

protected void btnGenerateQuote_Click(object sender, EventArgs e)
{
    string address = txtAddress.Text;
    string company = txtCompany.Text;
    string outputFilePath = @"C:\Quotes\Quote-" + company + "-.pdf";
    PdfReader reader = null;
    try
    {
        reader = new PdfReader(@"C:\Quotes\Quote_Template.pdf");
        using (FileStream pdfOutputFile = new FileStream
                                          (outputFilePath, FileMode.Create))
        {
            PdfStamper formFiller = null;
            try
            {
                formFiller = new PdfStamper(reader, pdfOutputFile);
                AcroFields quote_template = formFiller.AcroFields;
                //Fill the form
                quote_template.SetField("OldAddress", address);
                //Flatten - make the text go directly onto the pdf 
                //          and close the form.
                //formFiller.FormFlattening = true;
            }
            finally
            {
                if (formFiller != null)
                {
                     formFiller.Close();
                }
            }
        }
    }
    finally
    {
        reader.Close();
    }
    //Process.Start(outputFilePath); // does not work
}

person Xaisoft    schedule 28.05.2009    source источник


Ответы (1)


Поскольку речь идет об ASP.NET в соответствии с тегами, вы не должны использовать Process.Start(), а, например, такой код:

private void respondWithFile(string filePath, string remoteFileName) 
{
    if (!File.Exists(filePath))
        throw new FileNotFoundException(
              string.Format("Final PDF file '{0}' was not found on disk.", 
                             filePath));
    var fi = new FileInfo(filePath);
    Response.Clear();
    Response.AddHeader("Content-Disposition", 
                  String.Format("attachment; filename=\"{0}\"", 
                                 remoteFileName));
    Response.AddHeader("Content-Length", fi.Length.ToString());
    Response.ContentType = "application/octet-stream";
    Response.WriteFile(fi.FullName);
    Response.End();
}

И это заставит браузер дать диалог сохранения/открытия.

person Jan Wikholm    schedule 29.05.2009
comment
Более точный тип содержимого application/pdf упрощает обнаружение браузером. - person devstuff; 29.05.2009
comment
Спасибо, есть ли способ не показывать открытое сохранение и просто показывать pdf в новом окне? - person Xaisoft; 29.05.2009
comment
Content-Disposition встроенный вместо вложения. - person Jan Wikholm; 30.05.2009