Articles in this section
Category / Section

How to Fix Thread Being Aborted when Saving ASP.NET Web Forms PDF?

6 mins read

Syncfusion Essential® PDF is a .NET PDF library used to create, read, and edit PDF documents. Using this library, you can load and save an existing PDF document in ASP.NET Web Forms.

The HttpResponse is used to save or open the document in browser as follows. When end of the response “Thread was being aborted” exception occurs, it is not an issue, it is an actual behavior of Microsoft “HttpResponse.End”. Refer to the following link for more details.

https://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx

if (fileName == null)
{
    throw new ArgumentNullException("fileName");
}
if (response == null)
{
    throw new ArgumentNullException("response");
}
response.ClearContent();
response.Expires = 0;
response.Buffer = true;
string disposition = "content-disposition";
if (type == HttpReadType.Open)
{
    response.AddHeader(disposition, "inline; filename=" + fileName);
}
else if (type == HttpReadType.Save)
{
    response.AddHeader(disposition, "attachment; filename=" + fileName);
}
response.AddHeader("Content-Type", "application/pdf");
response.Clear();
Save(response.OutputStream);
if (PdfDocumentBase.IsSecurityGranted)
{
    response.Flush();
    response.End();
}
else
{
    response.End();
}

Steps to load and save an existing PDF programmatically:

  1. Create a new ASP.NET Web application project. Create a ASP.NET Web application project  syncfusion PDF
  2. Install the Syncfusion.Pdf.AspNet NuGet package as reference to your .NET Framework applications from NuGet.org. NuGet package as reference  
  3. Add a new Web Form in ASP.NET project. Right-click the project and select Add > New Item and add a Web Form from the list. Name it as MainPage.
  4. Add a new button in the MainPage.aspx as follows.
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Load and save an existing PDF" OnClick="OnButtonClicked" />
        </div>
        </form>
    </body>
    </html> 
    

 

  1. Include the following namespaces in your MainPage.aspx.cs file.

C#

using Syncfusion.Pdf.Parsing;
using System.IO;

 

VB.NET

Imports Syncfusion.Pdf.Parsing
Imports System.IO

 

  1. Include the following code snippet in the click event of the button in MainPage.aspx.cs to load and save an existing PDF file.

C#

protected void OnButtonClicked(object sender, EventArgs e)
{
    //Get input PDF file path
    string file = GetFilePath("Input.pdf");
    //Get byte array from input file
    var byteArray = GetBytesFromFile(file);
    //Load an existing PDF
    PdfLoadedDocument doc = new PdfLoadedDocument(byteArray, true);
    //Save the document into the HTTP response stream
    doc.Save(string.Format("Sample.pdf"), HttpContext.Current.Response, Syncfusion.Pdf.HttpReadType.Save);
    //Open the PDF document
    System.Diagnostics.Process.Start("Sample.pdf");
}
//Helps to get byte array from input file
public byte[] GetBytesFromFile(string fullFilePath)
{
    FileStream fs = File.OpenRead(fullFilePath);
    try
    {
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
        fs.Close();
        return bytes;
    }
    finally
    {
        fs.Close();
    }
}
//Helps to get physical application path of input file
public string GetFilePath(string path)
{
    string _dataPath = GetCommonFolder(new DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath));
    _dataPath += @"\" + path;
    return _dataPath;
}
//Helps to get physical application path of output file
static string GetCommonFolder(DirectoryInfo dtInfo)
{
    var _folderNames = dtInfo.GetDirectories("Data");
    if (_folderNames.Length > 0)
    {
        return _folderNames[0].FullName;
    }
    return dtInfo.Parent != null ? GetCommonFolder(dtInfo.Parent) : string.Empty;
}

 

VB.NET

Protected Sub OnButtonClicked(sender As Object, e As EventArgs)
    'Get input PDF file path
    Dim file As String = GetFilePath("Input.pdf")
    'Get byte array from input file
    Dim byteArray = GetBytesFromFile(file)
    'Load an existing PDF
    Dim doc As New PdfLoadedDocument(byteArray, True)
    'Save the document into the HTTP response stream
    doc.Save(String.Format("Sample.pdf"), HttpContext.Current.Response, Syncfusion.Pdf.HttpReadType.Save)
    'Open the PDF document
    System.Diagnostics.Process.Start("Sample.pdf")
End Sub
'Helps to get byte array from input file
Public Function GetBytesFromFile(fullFilePath As String) As Byte()
    Dim fs As FileStream = File.OpenRead(fullFilePath)
    Try
        Dim bytes As Byte() = New Byte(fs.Length - 1) {}
        fs.Read(bytes, 0, Convert.ToInt32(fs.Length))
        fs.Close()
        Return bytes
     Finally
         fs.Close()
     End Try
End Function
'Helps to get physical application path of input file
Public Function GetFilePath(path As String) As String
    Dim _dataPath As String = GetCommonFolder(New DirectoryInfo(HttpContext.Current.Request.PhysicalApplicationPath))
    _dataPath += "\" + path
    Return _dataPath
End Function
'Helps to get physical application path of output file
Private Shared Function GetCommonFolder(dtInfo As DirectoryInfo) As String
    Dim _folderNames = dtInfo.GetDirectories("Data")
    If _folderNames.Length > 0 Then
        Return _folderNames(0).FullName
    End If
    Return If(dtInfo.Parent IsNot Nothing, GetCommonFolder(dtInfo.Parent), String.Empty)
End Function

 

Find the sample in the following, which loads PDF document with 4 pages and you can find that document is saving properly.

LoadsTheExistingPDF.zip

By executing the program, you will get the PDF document as follows. Output PDF document

Refer here to explore the rich set of Syncfusion Essential® PDF features.

An online sample link to creation of simple PDF document.

Note:

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.


 Conclusion

A new version of Essential Studio® for ASP.NET is available. Versions prior to the release of Essential Studio® 2014, Volume 2 will now be referred to as a classic versions.The new ASP.NET suite is powered by Essential Studio for JavaScript providing client-side rendering of HTML 5-JavaScript controls, offering better performance, and better support for touch interactivity. The new version includes all the features of the old version, so migration is easy.

The Classic controls can be used in existing projects; however, if you are starting a new project, we recommend using the latest version of Essential Studio® for ASP.NET. Although Syncfusion® will continue to support all Classic Versions, we are happy to assist you in migrating to the newest edition.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below.

You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied