Xaisoft
Xaisoft

Reputation: 46651

Trying to open up PDF after creating it with iTextSharp, but can't get it to work?

I have a button when clicked, inserts text into form fields in a pdf and saves the filled pdf to a directory. When I am done editing the pdf, I want to open the pdf in the browswer, but Process.Start() is not working. Is there better way to immediately show the pdf after it has been generated? Here is the code for the button:

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
}

Upvotes: 0

Views: 4173

Answers (1)

Jan Wikholm
Jan Wikholm

Reputation: 1575

Since this is about ASP.NET according to the tags, you should not use Process.Start() but for example code like this:

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

And this would make the browser give the save/open dialog.

Upvotes: 4

Related Questions